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
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
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
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceCustomEventAccessorSymbol.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// This class represents an event accessor declared in source /// (i.e. not one synthesized for a field-like event). /// </summary> /// <remarks> /// The accessors are associated with <see cref="SourceCustomEventSymbol"/>. /// </remarks> internal sealed class SourceCustomEventAccessorSymbol : SourceEventAccessorSymbol { internal SourceCustomEventAccessorSymbol( SourceEventSymbol @event, AccessorDeclarationSyntax syntax, EventSymbol explicitlyImplementedEventOpt, string aliasQualifierOpt, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(@event, syntax.GetReference(), ImmutableArray.Create(syntax.Keyword.GetLocation()), explicitlyImplementedEventOpt, aliasQualifierOpt, isAdder: syntax.Kind() == SyntaxKind.AddAccessorDeclaration, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isNullableAnalysisEnabled: isNullableAnalysisEnabled) { Debug.Assert(syntax != null); Debug.Assert(syntax.Kind() == SyntaxKind.AddAccessorDeclaration || syntax.Kind() == SyntaxKind.RemoveAccessorDeclaration); CheckFeatureAvailabilityAndRuntimeSupport(syntax, this.Location, hasBody: true, diagnostics: diagnostics); if (syntax.Body != null || syntax.ExpressionBody != null) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, this.Location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } if (syntax.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_NoModifiersOnAccessor, syntax.Modifiers[0].GetLocation()); } CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } internal AccessorDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (AccessorDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } public override Accessibility DeclaredAccessibility { get { return this.AssociatedSymbol.DeclaredAccessibility; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(GetSyntax().AttributeLists); } public override bool IsImplicitlyDeclared { get { return false; } } internal override bool GenerateDebugInfo { get { return true; } } internal override bool IsExpressionBodied { get { var syntax = GetSyntax(); var hasBody = syntax.Body != null; var hasExpressionBody = syntax.ExpressionBody != null; return !hasBody && hasExpressionBody; } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// This class represents an event accessor declared in source /// (i.e. not one synthesized for a field-like event). /// </summary> /// <remarks> /// The accessors are associated with <see cref="SourceCustomEventSymbol"/>. /// </remarks> internal sealed class SourceCustomEventAccessorSymbol : SourceEventAccessorSymbol { internal SourceCustomEventAccessorSymbol( SourceEventSymbol @event, AccessorDeclarationSyntax syntax, EventSymbol explicitlyImplementedEventOpt, string aliasQualifierOpt, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(@event, syntax.GetReference(), ImmutableArray.Create(syntax.Keyword.GetLocation()), explicitlyImplementedEventOpt, aliasQualifierOpt, isAdder: syntax.Kind() == SyntaxKind.AddAccessorDeclaration, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isNullableAnalysisEnabled: isNullableAnalysisEnabled) { Debug.Assert(syntax != null); Debug.Assert(syntax.Kind() == SyntaxKind.AddAccessorDeclaration || syntax.Kind() == SyntaxKind.RemoveAccessorDeclaration); CheckFeatureAvailabilityAndRuntimeSupport(syntax, this.Location, hasBody: true, diagnostics: diagnostics); if (syntax.Body != null || syntax.ExpressionBody != null) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, this.Location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } if (syntax.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_NoModifiersOnAccessor, syntax.Modifiers[0].GetLocation()); } CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } internal AccessorDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (AccessorDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } public override Accessibility DeclaredAccessibility { get { return this.AssociatedSymbol.DeclaredAccessibility; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(GetSyntax().AttributeLists); } public override bool IsImplicitlyDeclared { get { return false; } } internal override bool GenerateDebugInfo { get { return true; } } internal override bool IsExpressionBodied { get { var syntax = GetSyntax(); var hasBody = syntax.Body != null; var hasExpressionBody = syntax.ExpressionBody != null; return !hasBody && hasExpressionBody; } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Core/Extensibility/NavigationBar/INavigationBarPresenter.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.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarPresenter { void Disconnect(); void PresentItems( ImmutableArray<NavigationBarProjectItem> projects, NavigationBarProjectItem? selectedProject, ImmutableArray<NavigationBarItem> typesWithMembers, NavigationBarItem? selectedType, NavigationBarItem? selectedMember); ITextView TryGetCurrentView(); event EventHandler<EventArgs> ViewFocused; event EventHandler<CaretPositionChangedEventArgs> CaretMoved; event EventHandler<NavigationBarItemSelectedEventArgs> ItemSelected; } }
// 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.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface INavigationBarPresenter { void Disconnect(); void PresentItems( ImmutableArray<NavigationBarProjectItem> projects, NavigationBarProjectItem? selectedProject, ImmutableArray<NavigationBarItem> typesWithMembers, NavigationBarItem? selectedType, NavigationBarItem? selectedMember); ITextView TryGetCurrentView(); event EventHandler<EventArgs> ViewFocused; event EventHandler<CaretPositionChangedEventArgs> CaretMoved; event EventHandler<NavigationBarItemSelectedEventArgs> ItemSelected; } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.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.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { [Export] [Shared] internal sealed class SQLiteConnectionPoolService : IDisposable { private const string LockFile = "db.lock"; private readonly object _gate = new(); /// <summary> /// Maps from database file path to connection pool. /// </summary> /// <remarks> /// Access to this field is synchronized through <see cref="_gate"/>. /// </remarks> private readonly Dictionary<string, ReferenceCountedDisposable<SQLiteConnectionPool>> _connectionPools = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SQLiteConnectionPoolService() { } /// <summary> /// Use a <see cref="ConcurrentExclusiveSchedulerPair"/> to simulate a reader-writer lock. /// Read operations are performed on the <see cref="ConcurrentExclusiveSchedulerPair.ConcurrentScheduler"/> /// and writes are performed on the <see cref="ConcurrentExclusiveSchedulerPair.ExclusiveScheduler"/>. /// /// We use this as a condition of using the in-memory shared-cache sqlite DB. This DB /// doesn't busy-wait when attempts are made to lock the tables in it, which can lead to /// deadlocks. Specifically, consider two threads doing the following: /// /// Thread A starts a transaction that starts as a reader, and later attempts to perform a /// write. Thread B is a writer (either started that way, or started as a reader and /// promoted to a writer first). B holds a RESERVED lock, waiting for readers to clear so it /// can start writing. A holds a SHARED lock (it's a reader) and tries to acquire RESERVED /// lock (so it can start writing). The only way to make progress in this situation is for /// one of the transactions to roll back. No amount of waiting will help, so when SQLite /// detects this situation, it doesn't honor the busy timeout. /// /// To prevent this scenario, we control our access to the db explicitly with operations that /// can concurrently read, and operations that exclusively write. /// /// All code that reads or writes from the db should go through this. /// </summary> public ConcurrentExclusiveSchedulerPair Scheduler { get; } = new(); public void Dispose() { lock (_gate) { foreach (var (_, pool) in _connectionPools) pool.Dispose(); _connectionPools.Clear(); } } public ReferenceCountedDisposable<SQLiteConnectionPool>? TryOpenDatabase( string databaseFilePath, IPersistentStorageFaultInjector? faultInjector, Action<SqlConnection, CancellationToken> initializer, CancellationToken cancellationToken) { lock (_gate) { if (_connectionPools.TryGetValue(databaseFilePath, out var pool)) { return pool.TryAddReference() ?? throw ExceptionUtilities.Unreachable; } // try to get db ownership lock. if someone else already has the lock. it will throw var ownershipLock = TryGetDatabaseOwnership(databaseFilePath); if (ownershipLock == null) { return null; } try { pool = new ReferenceCountedDisposable<SQLiteConnectionPool>( new SQLiteConnectionPool(this, faultInjector, databaseFilePath, ownershipLock)); pool.Target.Initialize(initializer, cancellationToken); // Place the initial ownership reference in _connectionPools, and return another _connectionPools.Add(databaseFilePath, pool); return pool.TryAddReference() ?? throw ExceptionUtilities.Unreachable; } catch (Exception ex) when (FatalError.ReportAndCatchUnlessCanceled(ex, cancellationToken)) { if (pool is not null) { // Dispose of the connection pool, releasing the ownership lock. pool.Dispose(); } else { // The storage was not created so nothing owns the lock. // Dispose the lock to allow reuse. ownershipLock.Dispose(); } throw; } } } /// <summary> /// Returns null in the case where an IO exception prevented us from being able to acquire /// the db lock file. /// </summary> private static IDisposable? TryGetDatabaseOwnership(string databaseFilePath) { return IOUtilities.PerformIO<IDisposable?>(() => { // make sure directory exist first. EnsureDirectory(databaseFilePath); var directoryName = Path.GetDirectoryName(databaseFilePath); Contract.ThrowIfNull(directoryName); return File.Open( Path.Combine(directoryName, LockFile), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }, defaultValue: null); } private static void EnsureDirectory(string databaseFilePath) { var directory = Path.GetDirectoryName(databaseFilePath); Contract.ThrowIfNull(directory); if (Directory.Exists(directory)) { return; } Directory.CreateDirectory(directory); } } }
// 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.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { [Export] [Shared] internal sealed class SQLiteConnectionPoolService : IDisposable { private const string LockFile = "db.lock"; private readonly object _gate = new(); /// <summary> /// Maps from database file path to connection pool. /// </summary> /// <remarks> /// Access to this field is synchronized through <see cref="_gate"/>. /// </remarks> private readonly Dictionary<string, ReferenceCountedDisposable<SQLiteConnectionPool>> _connectionPools = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SQLiteConnectionPoolService() { } /// <summary> /// Use a <see cref="ConcurrentExclusiveSchedulerPair"/> to simulate a reader-writer lock. /// Read operations are performed on the <see cref="ConcurrentExclusiveSchedulerPair.ConcurrentScheduler"/> /// and writes are performed on the <see cref="ConcurrentExclusiveSchedulerPair.ExclusiveScheduler"/>. /// /// We use this as a condition of using the in-memory shared-cache sqlite DB. This DB /// doesn't busy-wait when attempts are made to lock the tables in it, which can lead to /// deadlocks. Specifically, consider two threads doing the following: /// /// Thread A starts a transaction that starts as a reader, and later attempts to perform a /// write. Thread B is a writer (either started that way, or started as a reader and /// promoted to a writer first). B holds a RESERVED lock, waiting for readers to clear so it /// can start writing. A holds a SHARED lock (it's a reader) and tries to acquire RESERVED /// lock (so it can start writing). The only way to make progress in this situation is for /// one of the transactions to roll back. No amount of waiting will help, so when SQLite /// detects this situation, it doesn't honor the busy timeout. /// /// To prevent this scenario, we control our access to the db explicitly with operations that /// can concurrently read, and operations that exclusively write. /// /// All code that reads or writes from the db should go through this. /// </summary> public ConcurrentExclusiveSchedulerPair Scheduler { get; } = new(); public void Dispose() { lock (_gate) { foreach (var (_, pool) in _connectionPools) pool.Dispose(); _connectionPools.Clear(); } } public ReferenceCountedDisposable<SQLiteConnectionPool>? TryOpenDatabase( string databaseFilePath, IPersistentStorageFaultInjector? faultInjector, Action<SqlConnection, CancellationToken> initializer, CancellationToken cancellationToken) { lock (_gate) { if (_connectionPools.TryGetValue(databaseFilePath, out var pool)) { return pool.TryAddReference() ?? throw ExceptionUtilities.Unreachable; } // try to get db ownership lock. if someone else already has the lock. it will throw var ownershipLock = TryGetDatabaseOwnership(databaseFilePath); if (ownershipLock == null) { return null; } try { pool = new ReferenceCountedDisposable<SQLiteConnectionPool>( new SQLiteConnectionPool(this, faultInjector, databaseFilePath, ownershipLock)); pool.Target.Initialize(initializer, cancellationToken); // Place the initial ownership reference in _connectionPools, and return another _connectionPools.Add(databaseFilePath, pool); return pool.TryAddReference() ?? throw ExceptionUtilities.Unreachable; } catch (Exception ex) when (FatalError.ReportAndCatchUnlessCanceled(ex, cancellationToken)) { if (pool is not null) { // Dispose of the connection pool, releasing the ownership lock. pool.Dispose(); } else { // The storage was not created so nothing owns the lock. // Dispose the lock to allow reuse. ownershipLock.Dispose(); } throw; } } } /// <summary> /// Returns null in the case where an IO exception prevented us from being able to acquire /// the db lock file. /// </summary> private static IDisposable? TryGetDatabaseOwnership(string databaseFilePath) { return IOUtilities.PerformIO<IDisposable?>(() => { // make sure directory exist first. EnsureDirectory(databaseFilePath); var directoryName = Path.GetDirectoryName(databaseFilePath); Contract.ThrowIfNull(directoryName); return File.Open( Path.Combine(directoryName, LockFile), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }, defaultValue: null); } private static void EnsureDirectory(string databaseFilePath) { var directory = Path.GetDirectoryName(databaseFilePath); Contract.ThrowIfNull(directory); if (Directory.Exists(directory)) { return; } Directory.CreateDirectory(directory); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionForReturnCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : AbstractUseConditionalExpressionCodeFixProvider<TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var ifStatement = (TIfStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var ifOperation = (IConditionalOperation)semanticModel.GetOperation(ifStatement, cancellationToken)!; var containingSymbol = semanticModel.GetRequiredEnclosingSymbol(ifStatement.SpanStart, cancellationToken); if (!UseConditionalExpressionForReturnHelpers.TryMatchPattern( syntaxFacts, ifOperation, containingSymbol, out var trueStatement, out var falseStatement, out var trueReturn, out var falseReturn)) { return; } var anyReturn = (trueReturn ?? falseReturn)!; var conditionalExpression = await CreateConditionalExpressionAsync( document, ifOperation, trueStatement, falseStatement, trueReturn?.ReturnedValue ?? trueStatement, falseReturn?.ReturnedValue ?? falseStatement, anyReturn.GetRefKind(containingSymbol) != RefKind.None, cancellationToken).ConfigureAwait(false); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var returnStatement = anyReturn.Kind == OperationKind.YieldReturn ? (TStatementSyntax)generatorInternal.YieldReturnStatement(conditionalExpression) : (TStatementSyntax)editor.Generator.ReturnStatement(conditionalExpression); returnStatement = returnStatement.WithTriviaFrom(ifStatement); editor.ReplaceNode( ifStatement, WrapWithBlockIfAppropriate(ifStatement, returnStatement)); // if the if-statement had no 'else' clause, then we were using the following statement // as the 'false' statement. If so, remove it explicitly. if (ifOperation.WhenFalse == null) { editor.RemoveNode(falseStatement.Syntax, GetRemoveOptions(syntaxFacts, falseStatement.Syntax)); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Convert_to_conditional_expression, createChangedDocument, IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId) { } } } }
// 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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionForReturnCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : AbstractUseConditionalExpressionCodeFixProvider<TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var ifStatement = (TIfStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var ifOperation = (IConditionalOperation)semanticModel.GetOperation(ifStatement, cancellationToken)!; var containingSymbol = semanticModel.GetRequiredEnclosingSymbol(ifStatement.SpanStart, cancellationToken); if (!UseConditionalExpressionForReturnHelpers.TryMatchPattern( syntaxFacts, ifOperation, containingSymbol, out var trueStatement, out var falseStatement, out var trueReturn, out var falseReturn)) { return; } var anyReturn = (trueReturn ?? falseReturn)!; var conditionalExpression = await CreateConditionalExpressionAsync( document, ifOperation, trueStatement, falseStatement, trueReturn?.ReturnedValue ?? trueStatement, falseReturn?.ReturnedValue ?? falseStatement, anyReturn.GetRefKind(containingSymbol) != RefKind.None, cancellationToken).ConfigureAwait(false); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var returnStatement = anyReturn.Kind == OperationKind.YieldReturn ? (TStatementSyntax)generatorInternal.YieldReturnStatement(conditionalExpression) : (TStatementSyntax)editor.Generator.ReturnStatement(conditionalExpression); returnStatement = returnStatement.WithTriviaFrom(ifStatement); editor.ReplaceNode( ifStatement, WrapWithBlockIfAppropriate(ifStatement, returnStatement)); // if the if-statement had no 'else' clause, then we were using the following statement // as the 'false' statement. If so, remove it explicitly. if (ifOperation.WhenFalse == null) { editor.RemoveNode(falseStatement.Syntax, GetRemoveOptions(syntaxFacts, falseStatement.Syntax)); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Convert_to_conditional_expression, createChangedDocument, IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId) { } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/EncapsulateField_OutOfProc.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.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
// 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.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Shared/Extensions/ArrayExtensions.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.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ArrayExtensions { public static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this T[]? array) => array == null || array.Length == 0; public static bool Contains<T>(this T[] array, T item) => Array.IndexOf(array, item) >= 0; } }
// 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.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ArrayExtensions { public static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this T[]? array) => array == null || array.Length == 0; public static bool Contains<T>(this T[] array, T item) => Array.IndexOf(array, item) >= 0; } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal interface IXamlTypeRenameService : ILanguageService { public Task<XamlTypeRenameResult> GetTypeRenameAsync(TextDocument document, int position, 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal interface IXamlTypeRenameService : ILanguageService { public Task<XamlTypeRenameResult> GetTypeRenameAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.NativeMethods.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.Runtime.InteropServices; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioMetadataReferenceManager { [ComImport] [Guid("7998EA64-7F95-48B8-86FC-17CAF48BF5CB")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMetaDataInfo { // MetaData scope is opened (there's a reference to a MetaData interface for this scope). // Returns S_OK, COR_E_NOTSUPPORTED, or E_INVALIDARG (if NULL is passed). // STDMETHOD(GetFileMapping)( // const void ** ppvData, // [out] Pointer to the start of the mapped file. // ULONG * pcbData, // [out] Size of the mapped memory region. // DWORD * pdwMappingType) PURE; // [out] Type of file mapping (code:CorFileMapping). [PreserveSig] int GetFileMapping(out IntPtr ppvData, out long pcbData, out CorFileMapping pdwMappingType); } // Flags returned from IMetaDataInfo.GetFileMapping internal enum CorFileMapping : uint { Flat = 0, // Flat file mapping - file is mapped as data file (code:SEC_IMAGE flag was not // passed to code:CreateFileMapping). ExecutableImage = 1 // Executable image file mapping - file is mapped for execution // (either via code:LoadLibrary or code:CreateFileMapping with code:SEC_IMAGE flag). } internal enum CorOpenFlags : uint { Read = 0, Write = 1, ReadWriteMask = 1, CopyMemory = 2, ManifestMetadata = 8, ReadOnly = 16, TakeOwnership = 32, CacheImage = 4, NoTypeLib = 128 } } }
// 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioMetadataReferenceManager { [ComImport] [Guid("7998EA64-7F95-48B8-86FC-17CAF48BF5CB")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMetaDataInfo { // MetaData scope is opened (there's a reference to a MetaData interface for this scope). // Returns S_OK, COR_E_NOTSUPPORTED, or E_INVALIDARG (if NULL is passed). // STDMETHOD(GetFileMapping)( // const void ** ppvData, // [out] Pointer to the start of the mapped file. // ULONG * pcbData, // [out] Size of the mapped memory region. // DWORD * pdwMappingType) PURE; // [out] Type of file mapping (code:CorFileMapping). [PreserveSig] int GetFileMapping(out IntPtr ppvData, out long pcbData, out CorFileMapping pdwMappingType); } // Flags returned from IMetaDataInfo.GetFileMapping internal enum CorFileMapping : uint { Flat = 0, // Flat file mapping - file is mapped as data file (code:SEC_IMAGE flag was not // passed to code:CreateFileMapping). ExecutableImage = 1 // Executable image file mapping - file is mapped for execution // (either via code:LoadLibrary or code:CreateFileMapping with code:SEC_IMAGE flag). } internal enum CorOpenFlags : uint { Read = 0, Write = 1, ReadWriteMask = 1, CopyMemory = 2, ManifestMetadata = 8, ReadOnly = 16, TakeOwnership = 32, CacheImage = 4, NoTypeLib = 128 } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal abstract class AbstractSemanticModelReuseLanguageService< TMemberDeclarationSyntax, TBaseMethodDeclarationSyntax, TBasePropertyDeclarationSyntax, TAccessorDeclarationSyntax> : ISemanticModelReuseLanguageService where TMemberDeclarationSyntax : SyntaxNode where TBaseMethodDeclarationSyntax : TMemberDeclarationSyntax where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { /// <summary> /// Used to make sure we only report one watson per sessoin here. /// </summary> private static bool s_watsonReported; protected abstract ISyntaxFacts SyntaxFacts { get; } public abstract SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); protected abstract Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken); protected abstract SyntaxList<TAccessorDeclarationSyntax> GetAccessors(TBasePropertyDeclarationSyntax baseProperty); protected abstract TBasePropertyDeclarationSyntax GetBasePropertyDeclaration(TAccessorDeclarationSyntax accessor); public async Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousSyntaxTree = previousSemanticModel.SyntaxTree; var currentSyntaxTree = currentBodyNode.SyntaxTree; // This operation is only valid if top-level equivalent trees were passed in. If they're not equivalent // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was // still the same. So somehow w don't have top-level equivalence, but we do have the same semantic version. // // log a NFW to help diagnose what the source looks like as it may help us determine what sort of edit is // causing this. if (!previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)) { if (!s_watsonReported) { s_watsonReported = true; try { throw new InvalidOperationException( $@"Syntax trees should have been equivalent. --- {previousSyntaxTree.GetText(CancellationToken.None)} --- {currentSyntaxTree.GetText(CancellationToken.None)} ---"); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } return null; } return await TryGetSpeculativeSemanticModelWorkerAsync( previousSemanticModel, currentBodyNode, cancellationToken).ConfigureAwait(false); } protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) { if (currentBodyNode is TAccessorDeclarationSyntax currentAccessor) { // in the case of an accessor, have to find the previous accessor in the previous prop/event corresponding // to the current prop/event. var currentContainer = GetBasePropertyDeclaration(currentAccessor); var previousContainer = GetPreviousBodyNode(previousRoot, currentRoot, currentContainer); if (previousContainer is not TBasePropertyDeclarationSyntax previousMember) { Debug.Fail("Previous container didn't map back to a normal accessor container."); return null; } var currentAccessors = GetAccessors(currentContainer); var previousAccessors = GetAccessors(previousMember); if (currentAccessors.Count != previousAccessors.Count) { Debug.Fail("Accessor count shouldn't have changed as there were no top level edits."); return null; } return previousAccessors[currentAccessors.IndexOf(currentAccessor)]; } else { var currentMembers = this.SyntaxFacts.GetMethodLevelMembers(currentRoot); var index = currentMembers.IndexOf(currentBodyNode); if (index < 0) { Debug.Fail($"Unhandled member type in {nameof(GetPreviousBodyNode)}"); return null; } var previousMembers = this.SyntaxFacts.GetMethodLevelMembers(previousRoot); if (currentMembers.Count != previousMembers.Count) { Debug.Fail("Member count shouldn't have changed as there were no top level edits."); return null; } return previousMembers[index]; } } } }
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal abstract class AbstractSemanticModelReuseLanguageService< TMemberDeclarationSyntax, TBaseMethodDeclarationSyntax, TBasePropertyDeclarationSyntax, TAccessorDeclarationSyntax> : ISemanticModelReuseLanguageService where TMemberDeclarationSyntax : SyntaxNode where TBaseMethodDeclarationSyntax : TMemberDeclarationSyntax where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { /// <summary> /// Used to make sure we only report one watson per sessoin here. /// </summary> private static bool s_watsonReported; protected abstract ISyntaxFacts SyntaxFacts { get; } public abstract SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); protected abstract Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken); protected abstract SyntaxList<TAccessorDeclarationSyntax> GetAccessors(TBasePropertyDeclarationSyntax baseProperty); protected abstract TBasePropertyDeclarationSyntax GetBasePropertyDeclaration(TAccessorDeclarationSyntax accessor); public async Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousSyntaxTree = previousSemanticModel.SyntaxTree; var currentSyntaxTree = currentBodyNode.SyntaxTree; // This operation is only valid if top-level equivalent trees were passed in. If they're not equivalent // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was // still the same. So somehow w don't have top-level equivalence, but we do have the same semantic version. // // log a NFW to help diagnose what the source looks like as it may help us determine what sort of edit is // causing this. if (!previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)) { if (!s_watsonReported) { s_watsonReported = true; try { throw new InvalidOperationException( $@"Syntax trees should have been equivalent. --- {previousSyntaxTree.GetText(CancellationToken.None)} --- {currentSyntaxTree.GetText(CancellationToken.None)} ---"); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } return null; } return await TryGetSpeculativeSemanticModelWorkerAsync( previousSemanticModel, currentBodyNode, cancellationToken).ConfigureAwait(false); } protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) { if (currentBodyNode is TAccessorDeclarationSyntax currentAccessor) { // in the case of an accessor, have to find the previous accessor in the previous prop/event corresponding // to the current prop/event. var currentContainer = GetBasePropertyDeclaration(currentAccessor); var previousContainer = GetPreviousBodyNode(previousRoot, currentRoot, currentContainer); if (previousContainer is not TBasePropertyDeclarationSyntax previousMember) { Debug.Fail("Previous container didn't map back to a normal accessor container."); return null; } var currentAccessors = GetAccessors(currentContainer); var previousAccessors = GetAccessors(previousMember); if (currentAccessors.Count != previousAccessors.Count) { Debug.Fail("Accessor count shouldn't have changed as there were no top level edits."); return null; } return previousAccessors[currentAccessors.IndexOf(currentAccessor)]; } else { var currentMembers = this.SyntaxFacts.GetMethodLevelMembers(currentRoot); var index = currentMembers.IndexOf(currentBodyNode); if (index < 0) { Debug.Fail($"Unhandled member type in {nameof(GetPreviousBodyNode)}"); return null; } var previousMembers = this.SyntaxFacts.GetMethodLevelMembers(previousRoot); if (currentMembers.Count != previousMembers.Count) { Debug.Fail("Member count shouldn't have changed as there were no top level edits."); return null; } return previousMembers[index]; } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenReadonlyStructTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenReadOnlyStructTests : CompilingTestBase { [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticField() { var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""Program.S1 Program.sf"" IL_0005: call ""string Program.S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""Program.S1 Program.sf"" IL_0014: constrained. ""Program.S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldsfld ""Program.S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string Program.S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""Program.S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticFieldMetadata() { var text1 = @" public readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""S1 Program.sf"" IL_0005: call ""string S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""S1 Program.sf"" IL_0014: constrained. ""S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (S1 V_0) IL_0000: ldsfld ""S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceField() { var text = @" class Program { readonly S1 f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1()); System.Console.Write(p.f.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1 Program.f"" IL_000b: call ""string Program.S1.M1()"" IL_0010: call ""void System.Console.Write(string)"" IL_0015: ldflda ""Program.S1 Program.f"" IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1 Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""string Program.S1.M1()"" IL_0013: call ""void System.Console.Write(string)"" IL_0018: ldfld ""Program.S1 Program.f"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: constrained. ""Program.S1"" IL_0026: callvirt ""string object.ToString()"" IL_002b: call ""void System.Console.Write(string)"" IL_0030: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGeneric() { var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } readonly struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string Program.S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""Program.S1<string> Program.f"" IL_001f: constrained. ""Program.S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Program.S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string Program.S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""Program.S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""Program.S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGenericMetadata() { var text1 = @" readonly public struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""S1<string> Program.f"" IL_001f: constrained. ""S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] public void InvokeOnReadOnlyThis() { var text = @" class Program { static void Main() { Test(default(S1)); } static void Test(in S1 arg) { System.Console.Write(arg.M1()); System.Console.Write(arg.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Test", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); } [Fact] public void InvokeOnThis() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.M1()); System.Console.Write(ToString()); } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); comp.VerifyIL("Program.Main()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: dup IL_0003: initobj ""Program.S1"" IL_0009: call ""void Program.S1.Test()"" IL_000e: ret }"); } [Fact] public void InvokeOnThisBaseMethods() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.GetType()); System.Console.Write(ToString()); } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 39 (0x27) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""Program.S1"" IL_0006: box ""Program.S1"" IL_000b: call ""System.Type object.GetType()"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ldarg.0 IL_0016: constrained. ""Program.S1"" IL_001c: callvirt ""string object.ToString()"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void AssignThis() { var text = @" class Program { static void Main() { S1 v = new S1(42); System.Console.Write(v.x); S1 v2 = new S1(v); System.Console.Write(v2.x); } readonly struct S1 { public readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242"); comp.VerifyIL("Program.S1..ctor(int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int Program.S1.x"" IL_0007: ret }"); comp.VerifyIL("Program.S1..ctor(Program.S1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stobj ""Program.S1"" IL_0007: ret }"); } [Fact] public void AssignThisErr() { var text = @" class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } public void Test1() { this = default; // error } public void Test2() { TakesRef(ref this); // error } public void Test3() { TakesRef(ref this.x); // error } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (27,13): error CS1604: Cannot assign to 'this' because it is read-only // this = default; // error Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13), // (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // TakesRef(ref this); // error Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26), // (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor) // TakesRef(ref this.x); // error Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26) ); } [Fact] public void AssignThisNestedMethods() { var text = @" using System; class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { void F() { x = i;} // Error Action a = () => { x = i;}; // Error F(); } public S1(S1 arg) { void F() { this = arg;} // Error Action a = () => { this = arg;}; // Error F(); } public void Test1() { void F() { this = default;} // Error Action a = () => { this = default;}; // Error F(); } public void Test2() { void F() { TakesRef(ref this);} // Error Action a = () => { TakesRef(ref this);}; // Error F(); } public void Test3() { void F() { TakesRef(ref this.x);} // Error Action a = () => { TakesRef(ref this.x);}; // Error F(); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { x = i;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24), // (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { x = i;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32), // (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = arg;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24), // (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = arg;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32), // (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = default;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24), // (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = default;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32), // (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37), // (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45), // (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this.x);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37), // (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this.x);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45) ); } [Fact] public void ReadOnlyStructApi() { var text = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); void validate(ModuleSymbol module) { var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } CompileAndVerify(comp, symbolValidator: validate); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); // S1 from image var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() }); NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsReadOnly); Assert.Empty(s1.GetAttributes()); Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind); } [Fact] public void ReadOnlyStructApiMetadata() { var text1 = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); } [Fact] public void CorrectOverloadOfStackAllocSpanChosen() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { unsafe public static void Main() { bool condition = false; var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2); Console.Write(span1.Length); var span2 = condition ? stackalloc int[1] : stackalloc int[4]; Console.Write(span2.Length); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails); } [Fact] public void StackAllocExpressionIL() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { Span<int> x = stackalloc int[10]; Console.WriteLine(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 40 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 10 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthNotEvaluatedTwice() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { private static int length = 0; private static int GetLength() { return ++length; } public static void Main() { for (int i = 0; i < 5; i++) { Span<int> x = stackalloc int[GetLength()]; Console.Write(x.Length); } } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int V_0, //i System.Span<int> V_1, //x int V_2) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0027 IL_0004: call ""int Test.GetLength()"" IL_0009: stloc.2 IL_000a: ldloc.2 IL_000b: conv.u IL_000c: ldc.i4.4 IL_000d: mul.ovf.un IL_000e: localloc IL_0010: ldloc.2 IL_0011: newobj ""System.Span<int>..ctor(void*, int)"" IL_0016: stloc.1 IL_0017: ldloca.s V_1 IL_0019: call ""int System.Span<int>.Length.get"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: ldloc.0 IL_0028: ldc.i4.5 IL_0029: blt.s IL_0004 IL_002b: ret }"); } [Fact] public void StackAllocSpanLengthConstantFolding() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { const int a = 5, b = 6; Span<int> x = stackalloc int[a * b]; Console.Write(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 120 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 30 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthOverflow() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void M() { Span<int> x = stackalloc int[int.MaxValue]; } public static void Main() { try { M(); } catch (OverflowException) { Console.WriteLine(""overflow""); } } }", TestOptions.ReleaseExe); var expectedIL = @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4 0x7fffffff IL_0005: conv.u IL_0006: ldc.i4.4 IL_0007: mul.ovf.un IL_0008: localloc IL_000a: ldc.i4 0x7fffffff IL_000f: newobj ""System.Span<int>..ctor(void*, int)"" IL_0014: pop IL_0015: ret }"; var isx86 = (IntPtr.Size == 4); if (isx86) { CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } else { // On 64bit the native int does not overflow, so we get StackOverflow instead // therefore we will just check the IL CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } } [Fact] public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = stackalloc int[10]; Console.Write(""|""); Test obj2 = stackalloc double[10]; } public static implicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } public static implicit operator Test(double* value) { Console.Write(""PointerOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails); } [Fact] public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails); } [Fact] public void ReadOnlyMembers_Metadata() { var csharp = @" public struct S { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_RefReturn_Metadata() { var csharp = @" public struct S { static int i; public ref int M1() => ref i; public readonly ref int M2() => ref i; public ref readonly int M3() => ref i; public readonly ref readonly int M4() => ref i; public ref int P1 { get => ref i; } public readonly ref int P2 { get => ref i; } public ref readonly int P3 { get => ref i; } public readonly ref readonly int P4 { get => ref i; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var m3 = type.GetMethod("M3"); var m4 = type.GetMethod("M4"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyStruct_ReadOnlyMembers_Metadata() { var csharp = @" // note that both the type and member declarations are marked 'readonly' public readonly struct S { public void M1() {} public readonly void M2() {} public int P1 { get; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_MetadataRoundTrip() { var external = @" using System; public struct S1 { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } public readonly event Action<EventArgs> E { add {} remove {} } } public readonly struct S2 { public void M1() {} public int P1 { get; } public int P2 => 42; public int P3 { set {} } public static int P4 { get; set; } public event Action<EventArgs> E { add {} remove {} } } "; var externalComp = CreateCompilation(external); externalComp.VerifyDiagnostics(); verify(externalComp); var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() }); verify(comp); var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() }); verify(comp2); void verify(CSharpCompilation comp) { var s1 = comp.GetMember<NamedTypeSymbol>("S1"); verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref); verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null); verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null); verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); var s2 = comp.GetMember<NamedTypeSymbol>("S2"); verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null); verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null); verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind) { Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly); Assert.Equal(refKind, method.ThisParameter?.RefKind); } } } [Fact] public void StaticReadOnlyMethod_FromMetadata() { var il = @" .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // 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 IsReadOnlyAttribute::.ctor } // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance void M1 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M1 // Methods .method public hidebysig static void M2 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M2 } // end of class S "; var ilRef = CompileIL(il); var comp = CreateCompilation("", references: new[] { ilRef }); var s = comp.GetMember<NamedTypeSymbol>("S"); var m1 = s.GetMethod("M1"); Assert.True(m1.IsDeclaredReadOnly); Assert.True(m1.IsEffectivelyReadOnly); // even though the IsReadOnlyAttribute is in metadata, // we ruled out the possibility of the method being readonly because it's static var m2 = s.GetMethod("M2"); Assert.False(m2.IsDeclaredReadOnly); Assert.False(m2.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public readonly void M1() { // should create local copy M2(); System.Console.Write(i); // explicit local copy, no warning var copy = this; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; s.M1(); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); verifier.VerifyDiagnostics( // (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'. // M2(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9)); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public static void M1(in S s) { // should create local copy s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallMethodFromMetadata() { var external = @" public struct S { public int i; public readonly void M1() {} public void M2() { i = 23; } } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning s.M1(); System.Console.Write(s.i); // should create local copy, warn in warning wave s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 68 (0x44) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly void S.M1()"" IL_0006: ldarg.0 IL_0007: ldfld ""int S.i"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldobj ""S"" IL_0017: stloc.1 IL_0018: ldloca.s V_1 IL_001a: call ""void S.M2()"" IL_001f: ldarg.0 IL_0020: ldfld ""int S.i"" IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""void S.M2()"" IL_0038: ldloc.0 IL_0039: ldfld ""int S.i"" IL_003e: call ""void System.Console.Write(int)"" IL_0043: ret }"); } [Fact] public void InMethod_CallGetAccessorFromMetadata() { var external = @" public struct S { public int i; public readonly int P1 => 42; public int P2 => i = 23; } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning _ = s.P1; System.Console.Write(s.i); // should create local copy, warn in warning wave _ = s.P2; System.Console.Write(s.i); // explicit local copy, no warning var copy = s; _ = copy.P2; System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 71 (0x47) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly int S.P1.get"" IL_0006: pop IL_0007: ldarg.0 IL_0008: ldfld ""int S.i"" IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldarg.0 IL_0013: ldobj ""S"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int S.P2.get"" IL_0020: pop IL_0021: ldarg.0 IL_0022: ldfld ""int S.i"" IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldarg.0 IL_002d: ldobj ""S"" IL_0032: stloc.0 IL_0033: ldloca.s V_0 IL_0035: call ""int S.P2.get"" IL_003a: pop IL_003b: ldloc.0 IL_003c: ldfld ""int S.i"" IL_0041: call ""void System.Console.Write(int)"" IL_0046: ret }"); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public readonly int M1() => M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor() { var csharp = @" public struct S { public int i; public readonly int P1 { get => P2 + 1; } public readonly int P2 { get => i; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallAutoGetAccessor() { var csharp = @" public struct S { public readonly int P1 { get => P2 + 1; } public int P2 { get; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void InParam_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public static int M1(in S s) => s.M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethodOnField() { var csharp = @" public struct S1 { public readonly void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""S1 S2.s1"" IL_0006: call ""readonly void S1.M1()"" IL_000b: ret }"); comp.VerifyDiagnostics( // (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value // S1 s1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8) ); } [Fact] public void ReadOnlyMethod_CallNormalMethodOnField() { var csharp = @" public struct S1 { public void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 15 (0xf) .maxstack 1 .locals init (S1 V_0) IL_0000: ldarg.0 IL_0001: ldfld ""S1 S2.s1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""void S1.M1()"" IL_000e: ret }"); // should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallBaseMethod() { var csharp = @" public struct S { readonly void M() { // no warnings for calls to base members GetType(); ToString(); GetHashCode(); Equals(null); } } "; var comp = CompileAndVerify(csharp); comp.VerifyDiagnostics(); // ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'. comp.VerifyIL("S.M", @" { // Code size 58 (0x3a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""System.Type object.GetType()"" IL_0010: pop IL_0011: ldarg.0 IL_0012: constrained. ""S"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: constrained. ""S"" IL_0025: callvirt ""int object.GetHashCode()"" IL_002a: pop IL_002b: ldarg.0 IL_002c: ldnull IL_002d: constrained. ""S"" IL_0033: callvirt ""bool object.Equals(object)"" IL_0038: pop IL_0039: ret }"); } [Fact] public void ReadOnlyMethod_OverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public override string ToString() => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation ToString(); GetHashCode(); Equals(null); // ok base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9)); // Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this' verifier.VerifyIL("S.M", @" { // Code size 117 (0x75) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""S"" IL_000f: callvirt ""string object.ToString()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldobj ""S"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: constrained. ""S"" IL_0024: callvirt ""int object.GetHashCode()"" IL_0029: pop IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: ldnull IL_0034: constrained. ""S"" IL_003a: callvirt ""bool object.Equals(object)"" IL_003f: pop IL_0040: ldarg.0 IL_0041: ldobj ""S"" IL_0046: box ""S"" IL_004b: call ""string System.ValueType.ToString()"" IL_0050: pop IL_0051: ldarg.0 IL_0052: ldobj ""S"" IL_0057: box ""S"" IL_005c: call ""int System.ValueType.GetHashCode()"" IL_0061: pop IL_0062: ldarg.0 IL_0063: ldobj ""S"" IL_0068: box ""S"" IL_006d: ldnull IL_006e: call ""bool System.ValueType.Equals(object)"" IL_0073: pop IL_0074: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public readonly override string ToString() => throw null; public readonly override int GetHashCode() => throw null; public readonly override bool Equals(object o) => throw null; readonly void M() { // no warnings ToString(); GetHashCode(); Equals(null); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly override members pass the address of 'this' (not a temp) verifier.VerifyIL("S.M", @" { // Code size 93 (0x5d) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""S"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: ldarg.0 IL_000e: constrained. ""S"" IL_0014: callvirt ""int object.GetHashCode()"" IL_0019: pop IL_001a: ldarg.0 IL_001b: ldnull IL_001c: constrained. ""S"" IL_0022: callvirt ""bool object.Equals(object)"" IL_0027: pop IL_0028: ldarg.0 IL_0029: ldobj ""S"" IL_002e: box ""S"" IL_0033: call ""string System.ValueType.ToString()"" IL_0038: pop IL_0039: ldarg.0 IL_003a: ldobj ""S"" IL_003f: box ""S"" IL_0044: call ""int System.ValueType.GetHashCode()"" IL_0049: pop IL_004a: ldarg.0 IL_004b: ldobj ""S"" IL_0050: box ""S"" IL_0055: ldnull IL_0056: call ""bool System.ValueType.Equals(object)"" IL_005b: pop IL_005c: ret }"); } [Fact] public void ReadOnlyMethod_NewBaseMethod() { var csharp = @" public struct S { public new System.Type GetType() => throw null; public new string ToString() => throw null; public new int GetHashCode() => throw null; public new bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation GetType(); ToString(); GetHashCode(); Equals(null); // ok base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'. // GetType(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9), // (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9)); // Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 131 (0x83) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""System.Type S.GetType()"" IL_000e: pop IL_000f: ldarg.0 IL_0010: ldobj ""S"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: call ""string S.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldobj ""S"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""int S.GetHashCode()"" IL_002c: pop IL_002d: ldarg.0 IL_002e: ldobj ""S"" IL_0033: stloc.0 IL_0034: ldloca.s V_0 IL_0036: ldnull IL_0037: call ""bool S.Equals(object)"" IL_003c: pop IL_003d: ldarg.0 IL_003e: ldobj ""S"" IL_0043: box ""S"" IL_0048: call ""System.Type object.GetType()"" IL_004d: pop IL_004e: ldarg.0 IL_004f: ldobj ""S"" IL_0054: box ""S"" IL_0059: call ""string System.ValueType.ToString()"" IL_005e: pop IL_005f: ldarg.0 IL_0060: ldobj ""S"" IL_0065: box ""S"" IL_006a: call ""int System.ValueType.GetHashCode()"" IL_006f: pop IL_0070: ldarg.0 IL_0071: ldobj ""S"" IL_0076: box ""S"" IL_007b: ldnull IL_007c: call ""bool System.ValueType.Equals(object)"" IL_0081: pop IL_0082: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyNewBaseMethod() { var csharp = @" public struct S { public readonly new System.Type GetType() => throw null; public readonly new string ToString() => throw null; public readonly new int GetHashCode() => throw null; public readonly new bool Equals(object o) => throw null; readonly void M() { // no warnings GetType(); ToString(); GetHashCode(); Equals(null); base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 99 (0x63) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly System.Type S.GetType()"" IL_0006: pop IL_0007: ldarg.0 IL_0008: call ""readonly string S.ToString()"" IL_000d: pop IL_000e: ldarg.0 IL_000f: call ""readonly int S.GetHashCode()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldnull IL_0017: call ""readonly bool S.Equals(object)"" IL_001c: pop IL_001d: ldarg.0 IL_001e: ldobj ""S"" IL_0023: box ""S"" IL_0028: call ""System.Type object.GetType()"" IL_002d: pop IL_002e: ldarg.0 IL_002f: ldobj ""S"" IL_0034: box ""S"" IL_0039: call ""string System.ValueType.ToString()"" IL_003e: pop IL_003f: ldarg.0 IL_0040: ldobj ""S"" IL_0045: box ""S"" IL_004a: call ""int System.ValueType.GetHashCode()"" IL_004f: pop IL_0050: ldarg.0 IL_0051: ldobj ""S"" IL_0056: box ""S"" IL_005b: ldnull IL_005c: call ""bool System.ValueType.Equals(object)"" IL_0061: pop IL_0062: ret }"); } [Fact] public void ReadOnlyMethod_FixedThis() { var csharp = @" struct S { int i; readonly unsafe void M() { fixed (S* sp = &this) { sp->i = 42; } } static void Main() { var s = new S(); s.M(); System.Console.Write(s.i); } } "; CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42"); } public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() => new TheoryData<bool, CSharpParseOptions, Verification> { { false, TestOptions.Regular7_3, Verification.Passes }, { true, null, Verification.Fails } }; [Theory] [MemberData(nameof(ReadOnlyGetter_LangVersion_Data))] public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify) { var csharp = @" struct S { public int P { get; } static readonly S Field = default; static void M() { _ = Field.P; } } "; var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify); var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S"); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyEvent_Emit() { var csharp = @" public struct S { public readonly event System.Action E { add { } remove { } } } "; CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics(); void validate(ModuleSymbol module) { var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenReadOnlyStructTests : CompilingTestBase { [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticField() { var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""Program.S1 Program.sf"" IL_0005: call ""string Program.S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""Program.S1 Program.sf"" IL_0014: constrained. ""Program.S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldsfld ""Program.S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string Program.S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""Program.S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticFieldMetadata() { var text1 = @" public readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""S1 Program.sf"" IL_0005: call ""string S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""S1 Program.sf"" IL_0014: constrained. ""S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (S1 V_0) IL_0000: ldsfld ""S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceField() { var text = @" class Program { readonly S1 f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1()); System.Console.Write(p.f.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1 Program.f"" IL_000b: call ""string Program.S1.M1()"" IL_0010: call ""void System.Console.Write(string)"" IL_0015: ldflda ""Program.S1 Program.f"" IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1 Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""string Program.S1.M1()"" IL_0013: call ""void System.Console.Write(string)"" IL_0018: ldfld ""Program.S1 Program.f"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: constrained. ""Program.S1"" IL_0026: callvirt ""string object.ToString()"" IL_002b: call ""void System.Console.Write(string)"" IL_0030: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGeneric() { var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } readonly struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string Program.S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""Program.S1<string> Program.f"" IL_001f: constrained. ""Program.S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Program.S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string Program.S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""Program.S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""Program.S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGenericMetadata() { var text1 = @" readonly public struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""S1<string> Program.f"" IL_001f: constrained. ""S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] public void InvokeOnReadOnlyThis() { var text = @" class Program { static void Main() { Test(default(S1)); } static void Test(in S1 arg) { System.Console.Write(arg.M1()); System.Console.Write(arg.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Test", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); } [Fact] public void InvokeOnThis() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.M1()); System.Console.Write(ToString()); } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); comp.VerifyIL("Program.Main()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: dup IL_0003: initobj ""Program.S1"" IL_0009: call ""void Program.S1.Test()"" IL_000e: ret }"); } [Fact] public void InvokeOnThisBaseMethods() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.GetType()); System.Console.Write(ToString()); } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 39 (0x27) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""Program.S1"" IL_0006: box ""Program.S1"" IL_000b: call ""System.Type object.GetType()"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ldarg.0 IL_0016: constrained. ""Program.S1"" IL_001c: callvirt ""string object.ToString()"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void AssignThis() { var text = @" class Program { static void Main() { S1 v = new S1(42); System.Console.Write(v.x); S1 v2 = new S1(v); System.Console.Write(v2.x); } readonly struct S1 { public readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242"); comp.VerifyIL("Program.S1..ctor(int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int Program.S1.x"" IL_0007: ret }"); comp.VerifyIL("Program.S1..ctor(Program.S1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stobj ""Program.S1"" IL_0007: ret }"); } [Fact] public void AssignThisErr() { var text = @" class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } public void Test1() { this = default; // error } public void Test2() { TakesRef(ref this); // error } public void Test3() { TakesRef(ref this.x); // error } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (27,13): error CS1604: Cannot assign to 'this' because it is read-only // this = default; // error Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13), // (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // TakesRef(ref this); // error Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26), // (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor) // TakesRef(ref this.x); // error Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26) ); } [Fact] public void AssignThisNestedMethods() { var text = @" using System; class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { void F() { x = i;} // Error Action a = () => { x = i;}; // Error F(); } public S1(S1 arg) { void F() { this = arg;} // Error Action a = () => { this = arg;}; // Error F(); } public void Test1() { void F() { this = default;} // Error Action a = () => { this = default;}; // Error F(); } public void Test2() { void F() { TakesRef(ref this);} // Error Action a = () => { TakesRef(ref this);}; // Error F(); } public void Test3() { void F() { TakesRef(ref this.x);} // Error Action a = () => { TakesRef(ref this.x);}; // Error F(); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { x = i;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24), // (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { x = i;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32), // (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = arg;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24), // (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = arg;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32), // (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = default;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24), // (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = default;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32), // (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37), // (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45), // (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this.x);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37), // (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this.x);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45) ); } [Fact] public void ReadOnlyStructApi() { var text = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); void validate(ModuleSymbol module) { var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } CompileAndVerify(comp, symbolValidator: validate); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); // S1 from image var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() }); NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsReadOnly); Assert.Empty(s1.GetAttributes()); Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind); } [Fact] public void ReadOnlyStructApiMetadata() { var text1 = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); } [Fact] public void CorrectOverloadOfStackAllocSpanChosen() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { unsafe public static void Main() { bool condition = false; var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2); Console.Write(span1.Length); var span2 = condition ? stackalloc int[1] : stackalloc int[4]; Console.Write(span2.Length); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails); } [Fact] public void StackAllocExpressionIL() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { Span<int> x = stackalloc int[10]; Console.WriteLine(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 40 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 10 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthNotEvaluatedTwice() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { private static int length = 0; private static int GetLength() { return ++length; } public static void Main() { for (int i = 0; i < 5; i++) { Span<int> x = stackalloc int[GetLength()]; Console.Write(x.Length); } } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int V_0, //i System.Span<int> V_1, //x int V_2) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0027 IL_0004: call ""int Test.GetLength()"" IL_0009: stloc.2 IL_000a: ldloc.2 IL_000b: conv.u IL_000c: ldc.i4.4 IL_000d: mul.ovf.un IL_000e: localloc IL_0010: ldloc.2 IL_0011: newobj ""System.Span<int>..ctor(void*, int)"" IL_0016: stloc.1 IL_0017: ldloca.s V_1 IL_0019: call ""int System.Span<int>.Length.get"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: ldloc.0 IL_0028: ldc.i4.5 IL_0029: blt.s IL_0004 IL_002b: ret }"); } [Fact] public void StackAllocSpanLengthConstantFolding() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { const int a = 5, b = 6; Span<int> x = stackalloc int[a * b]; Console.Write(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 120 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 30 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthOverflow() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void M() { Span<int> x = stackalloc int[int.MaxValue]; } public static void Main() { try { M(); } catch (OverflowException) { Console.WriteLine(""overflow""); } } }", TestOptions.ReleaseExe); var expectedIL = @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4 0x7fffffff IL_0005: conv.u IL_0006: ldc.i4.4 IL_0007: mul.ovf.un IL_0008: localloc IL_000a: ldc.i4 0x7fffffff IL_000f: newobj ""System.Span<int>..ctor(void*, int)"" IL_0014: pop IL_0015: ret }"; var isx86 = (IntPtr.Size == 4); if (isx86) { CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } else { // On 64bit the native int does not overflow, so we get StackOverflow instead // therefore we will just check the IL CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } } [Fact] public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = stackalloc int[10]; Console.Write(""|""); Test obj2 = stackalloc double[10]; } public static implicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } public static implicit operator Test(double* value) { Console.Write(""PointerOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails); } [Fact] public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails); } [Fact] public void ReadOnlyMembers_Metadata() { var csharp = @" public struct S { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_RefReturn_Metadata() { var csharp = @" public struct S { static int i; public ref int M1() => ref i; public readonly ref int M2() => ref i; public ref readonly int M3() => ref i; public readonly ref readonly int M4() => ref i; public ref int P1 { get => ref i; } public readonly ref int P2 { get => ref i; } public ref readonly int P3 { get => ref i; } public readonly ref readonly int P4 { get => ref i; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var m3 = type.GetMethod("M3"); var m4 = type.GetMethod("M4"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyStruct_ReadOnlyMembers_Metadata() { var csharp = @" // note that both the type and member declarations are marked 'readonly' public readonly struct S { public void M1() {} public readonly void M2() {} public int P1 { get; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_MetadataRoundTrip() { var external = @" using System; public struct S1 { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } public readonly event Action<EventArgs> E { add {} remove {} } } public readonly struct S2 { public void M1() {} public int P1 { get; } public int P2 => 42; public int P3 { set {} } public static int P4 { get; set; } public event Action<EventArgs> E { add {} remove {} } } "; var externalComp = CreateCompilation(external); externalComp.VerifyDiagnostics(); verify(externalComp); var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() }); verify(comp); var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() }); verify(comp2); void verify(CSharpCompilation comp) { var s1 = comp.GetMember<NamedTypeSymbol>("S1"); verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref); verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null); verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null); verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); var s2 = comp.GetMember<NamedTypeSymbol>("S2"); verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null); verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null); verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind) { Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly); Assert.Equal(refKind, method.ThisParameter?.RefKind); } } } [Fact] public void StaticReadOnlyMethod_FromMetadata() { var il = @" .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // 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 IsReadOnlyAttribute::.ctor } // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance void M1 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M1 // Methods .method public hidebysig static void M2 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M2 } // end of class S "; var ilRef = CompileIL(il); var comp = CreateCompilation("", references: new[] { ilRef }); var s = comp.GetMember<NamedTypeSymbol>("S"); var m1 = s.GetMethod("M1"); Assert.True(m1.IsDeclaredReadOnly); Assert.True(m1.IsEffectivelyReadOnly); // even though the IsReadOnlyAttribute is in metadata, // we ruled out the possibility of the method being readonly because it's static var m2 = s.GetMethod("M2"); Assert.False(m2.IsDeclaredReadOnly); Assert.False(m2.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public readonly void M1() { // should create local copy M2(); System.Console.Write(i); // explicit local copy, no warning var copy = this; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; s.M1(); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); verifier.VerifyDiagnostics( // (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'. // M2(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9)); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public static void M1(in S s) { // should create local copy s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallMethodFromMetadata() { var external = @" public struct S { public int i; public readonly void M1() {} public void M2() { i = 23; } } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning s.M1(); System.Console.Write(s.i); // should create local copy, warn in warning wave s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 68 (0x44) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly void S.M1()"" IL_0006: ldarg.0 IL_0007: ldfld ""int S.i"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldobj ""S"" IL_0017: stloc.1 IL_0018: ldloca.s V_1 IL_001a: call ""void S.M2()"" IL_001f: ldarg.0 IL_0020: ldfld ""int S.i"" IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""void S.M2()"" IL_0038: ldloc.0 IL_0039: ldfld ""int S.i"" IL_003e: call ""void System.Console.Write(int)"" IL_0043: ret }"); } [Fact] public void InMethod_CallGetAccessorFromMetadata() { var external = @" public struct S { public int i; public readonly int P1 => 42; public int P2 => i = 23; } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning _ = s.P1; System.Console.Write(s.i); // should create local copy, warn in warning wave _ = s.P2; System.Console.Write(s.i); // explicit local copy, no warning var copy = s; _ = copy.P2; System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 71 (0x47) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly int S.P1.get"" IL_0006: pop IL_0007: ldarg.0 IL_0008: ldfld ""int S.i"" IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldarg.0 IL_0013: ldobj ""S"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int S.P2.get"" IL_0020: pop IL_0021: ldarg.0 IL_0022: ldfld ""int S.i"" IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldarg.0 IL_002d: ldobj ""S"" IL_0032: stloc.0 IL_0033: ldloca.s V_0 IL_0035: call ""int S.P2.get"" IL_003a: pop IL_003b: ldloc.0 IL_003c: ldfld ""int S.i"" IL_0041: call ""void System.Console.Write(int)"" IL_0046: ret }"); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public readonly int M1() => M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor() { var csharp = @" public struct S { public int i; public readonly int P1 { get => P2 + 1; } public readonly int P2 { get => i; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallAutoGetAccessor() { var csharp = @" public struct S { public readonly int P1 { get => P2 + 1; } public int P2 { get; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void InParam_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public static int M1(in S s) => s.M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethodOnField() { var csharp = @" public struct S1 { public readonly void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""S1 S2.s1"" IL_0006: call ""readonly void S1.M1()"" IL_000b: ret }"); comp.VerifyDiagnostics( // (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value // S1 s1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8) ); } [Fact] public void ReadOnlyMethod_CallNormalMethodOnField() { var csharp = @" public struct S1 { public void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 15 (0xf) .maxstack 1 .locals init (S1 V_0) IL_0000: ldarg.0 IL_0001: ldfld ""S1 S2.s1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""void S1.M1()"" IL_000e: ret }"); // should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallBaseMethod() { var csharp = @" public struct S { readonly void M() { // no warnings for calls to base members GetType(); ToString(); GetHashCode(); Equals(null); } } "; var comp = CompileAndVerify(csharp); comp.VerifyDiagnostics(); // ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'. comp.VerifyIL("S.M", @" { // Code size 58 (0x3a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""System.Type object.GetType()"" IL_0010: pop IL_0011: ldarg.0 IL_0012: constrained. ""S"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: constrained. ""S"" IL_0025: callvirt ""int object.GetHashCode()"" IL_002a: pop IL_002b: ldarg.0 IL_002c: ldnull IL_002d: constrained. ""S"" IL_0033: callvirt ""bool object.Equals(object)"" IL_0038: pop IL_0039: ret }"); } [Fact] public void ReadOnlyMethod_OverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public override string ToString() => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation ToString(); GetHashCode(); Equals(null); // ok base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9)); // Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this' verifier.VerifyIL("S.M", @" { // Code size 117 (0x75) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""S"" IL_000f: callvirt ""string object.ToString()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldobj ""S"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: constrained. ""S"" IL_0024: callvirt ""int object.GetHashCode()"" IL_0029: pop IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: ldnull IL_0034: constrained. ""S"" IL_003a: callvirt ""bool object.Equals(object)"" IL_003f: pop IL_0040: ldarg.0 IL_0041: ldobj ""S"" IL_0046: box ""S"" IL_004b: call ""string System.ValueType.ToString()"" IL_0050: pop IL_0051: ldarg.0 IL_0052: ldobj ""S"" IL_0057: box ""S"" IL_005c: call ""int System.ValueType.GetHashCode()"" IL_0061: pop IL_0062: ldarg.0 IL_0063: ldobj ""S"" IL_0068: box ""S"" IL_006d: ldnull IL_006e: call ""bool System.ValueType.Equals(object)"" IL_0073: pop IL_0074: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public readonly override string ToString() => throw null; public readonly override int GetHashCode() => throw null; public readonly override bool Equals(object o) => throw null; readonly void M() { // no warnings ToString(); GetHashCode(); Equals(null); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly override members pass the address of 'this' (not a temp) verifier.VerifyIL("S.M", @" { // Code size 93 (0x5d) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""S"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: ldarg.0 IL_000e: constrained. ""S"" IL_0014: callvirt ""int object.GetHashCode()"" IL_0019: pop IL_001a: ldarg.0 IL_001b: ldnull IL_001c: constrained. ""S"" IL_0022: callvirt ""bool object.Equals(object)"" IL_0027: pop IL_0028: ldarg.0 IL_0029: ldobj ""S"" IL_002e: box ""S"" IL_0033: call ""string System.ValueType.ToString()"" IL_0038: pop IL_0039: ldarg.0 IL_003a: ldobj ""S"" IL_003f: box ""S"" IL_0044: call ""int System.ValueType.GetHashCode()"" IL_0049: pop IL_004a: ldarg.0 IL_004b: ldobj ""S"" IL_0050: box ""S"" IL_0055: ldnull IL_0056: call ""bool System.ValueType.Equals(object)"" IL_005b: pop IL_005c: ret }"); } [Fact] public void ReadOnlyMethod_NewBaseMethod() { var csharp = @" public struct S { public new System.Type GetType() => throw null; public new string ToString() => throw null; public new int GetHashCode() => throw null; public new bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation GetType(); ToString(); GetHashCode(); Equals(null); // ok base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'. // GetType(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9), // (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9)); // Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 131 (0x83) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""System.Type S.GetType()"" IL_000e: pop IL_000f: ldarg.0 IL_0010: ldobj ""S"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: call ""string S.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldobj ""S"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""int S.GetHashCode()"" IL_002c: pop IL_002d: ldarg.0 IL_002e: ldobj ""S"" IL_0033: stloc.0 IL_0034: ldloca.s V_0 IL_0036: ldnull IL_0037: call ""bool S.Equals(object)"" IL_003c: pop IL_003d: ldarg.0 IL_003e: ldobj ""S"" IL_0043: box ""S"" IL_0048: call ""System.Type object.GetType()"" IL_004d: pop IL_004e: ldarg.0 IL_004f: ldobj ""S"" IL_0054: box ""S"" IL_0059: call ""string System.ValueType.ToString()"" IL_005e: pop IL_005f: ldarg.0 IL_0060: ldobj ""S"" IL_0065: box ""S"" IL_006a: call ""int System.ValueType.GetHashCode()"" IL_006f: pop IL_0070: ldarg.0 IL_0071: ldobj ""S"" IL_0076: box ""S"" IL_007b: ldnull IL_007c: call ""bool System.ValueType.Equals(object)"" IL_0081: pop IL_0082: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyNewBaseMethod() { var csharp = @" public struct S { public readonly new System.Type GetType() => throw null; public readonly new string ToString() => throw null; public readonly new int GetHashCode() => throw null; public readonly new bool Equals(object o) => throw null; readonly void M() { // no warnings GetType(); ToString(); GetHashCode(); Equals(null); base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 99 (0x63) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly System.Type S.GetType()"" IL_0006: pop IL_0007: ldarg.0 IL_0008: call ""readonly string S.ToString()"" IL_000d: pop IL_000e: ldarg.0 IL_000f: call ""readonly int S.GetHashCode()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldnull IL_0017: call ""readonly bool S.Equals(object)"" IL_001c: pop IL_001d: ldarg.0 IL_001e: ldobj ""S"" IL_0023: box ""S"" IL_0028: call ""System.Type object.GetType()"" IL_002d: pop IL_002e: ldarg.0 IL_002f: ldobj ""S"" IL_0034: box ""S"" IL_0039: call ""string System.ValueType.ToString()"" IL_003e: pop IL_003f: ldarg.0 IL_0040: ldobj ""S"" IL_0045: box ""S"" IL_004a: call ""int System.ValueType.GetHashCode()"" IL_004f: pop IL_0050: ldarg.0 IL_0051: ldobj ""S"" IL_0056: box ""S"" IL_005b: ldnull IL_005c: call ""bool System.ValueType.Equals(object)"" IL_0061: pop IL_0062: ret }"); } [Fact] public void ReadOnlyMethod_FixedThis() { var csharp = @" struct S { int i; readonly unsafe void M() { fixed (S* sp = &this) { sp->i = 42; } } static void Main() { var s = new S(); s.M(); System.Console.Write(s.i); } } "; CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42"); } public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() => new TheoryData<bool, CSharpParseOptions, Verification> { { false, TestOptions.Regular7_3, Verification.Passes }, { true, null, Verification.Fails } }; [Theory] [MemberData(nameof(ReadOnlyGetter_LangVersion_Data))] public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify) { var csharp = @" struct S { public int P { get; } static readonly S Field = default; static void M() { _ = Field.P; } } "; var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify); var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S"); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyEvent_Emit() { var csharp = @" public struct S { public readonly event System.Action E { add { } remove { } } } "; CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics(); void validate(ModuleSymbol module) { var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller.Session_ComputeModel.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session { public void ComputeModel( ImmutableArray<ISignatureHelpProvider> providers, SignatureHelpTriggerInfo triggerInfo) { AssertIsForeground(); var caretPosition = Controller.TextView.GetCaretPoint(Controller.SubjectBuffer).Value; var disconnectedBufferGraph = new DisconnectedBufferGraph(Controller.SubjectBuffer, Controller.TextView.TextBuffer); // If we've already computed a model, then just use that. Otherwise, actually // compute a new model and send that along. Computation.ChainTaskAndNotifyControllerWhenFinished( (model, cancellationToken) => ComputeModelInBackgroundAsync( model, providers, caretPosition, disconnectedBufferGraph, triggerInfo, cancellationToken)); } private async Task<Model> ComputeModelInBackgroundAsync( Model currentModel, ImmutableArray<ISignatureHelpProvider> providers, SnapshotPoint caretPosition, DisconnectedBufferGraph disconnectedBufferGraph, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SignatureHelp_ModelComputation_ComputeModelInBackground, cancellationToken)) { AssertIsBackground(); cancellationToken.ThrowIfCancellationRequested(); var document = Controller.DocumentProvider.GetDocument(caretPosition.Snapshot, cancellationToken); if (document == null) { return currentModel; } // Let LSP handle signature help in the cloud scenario if (Controller.SubjectBuffer.IsInLspEditorContext()) { return null; } if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (currentModel == null) { return null; } if (triggerInfo.TriggerCharacter.HasValue && !currentModel.Provider.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value)) { return currentModel; } } // first try to query the providers that can trigger on the specified character var (provider, items) = await ComputeItemsAsync( providers, caretPosition, triggerInfo, document, cancellationToken).ConfigureAwait(false); if (provider == null) { // No provider produced items. So we can't produce a model return null; } if (currentModel != null && currentModel.Provider == provider && currentModel.GetCurrentSpanInSubjectBuffer(disconnectedBufferGraph.SubjectBufferSnapshot).Span.Start == items.ApplicableSpan.Start && currentModel.Items.IndexOf(currentModel.SelectedItem) == items.SelectedItemIndex && currentModel.ArgumentIndex == items.ArgumentIndex && currentModel.ArgumentCount == items.ArgumentCount && currentModel.ArgumentName == items.ArgumentName) { // The new model is the same as the current model. Return the currentModel // so we keep the active selection. return currentModel; } var selectedItem = GetSelectedItem(currentModel, items, provider, out var userSelected); var model = new Model(disconnectedBufferGraph, items.ApplicableSpan, provider, items.Items, selectedItem, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, selectedParameter: 0, userSelected); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var isCaseSensitive = syntaxFactsService == null || syntaxFactsService.IsCaseSensitive; var selection = DefaultSignatureHelpSelector.GetSelection(model.Items, model.SelectedItem, model.UserSelected, model.ArgumentIndex, model.ArgumentCount, model.ArgumentName, isCaseSensitive); return model.WithSelectedItem(selection.SelectedItem, selection.UserSelected) .WithSelectedParameter(selection.SelectedParameter); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static SignatureHelpItem GetSelectedItem(Model currentModel, SignatureHelpItems items, ISignatureHelpProvider provider, out bool userSelected) { // Try to find the most appropriate item in the list to select by default. // If it's the same provider as the previous model we have, and we had a user-selection, // then try to return the user-selection. if (currentModel != null && currentModel.Provider == provider && currentModel.UserSelected) { var userSelectedItem = items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)); if (userSelectedItem != null) { userSelected = true; return userSelectedItem; } } userSelected = false; // If the provider specified a selected item, then pick that one. if (items.SelectedItemIndex.HasValue) { return items.Items[items.SelectedItemIndex.Value]; } SignatureHelpItem lastSelectionOrDefault = null; if (currentModel != null && currentModel.Provider == provider) { // If the provider did not pick a default, and it's the same provider as the previous // model we have, then try to return the same item that we had before. lastSelectionOrDefault = items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)); } if (lastSelectionOrDefault == null) { // Otherwise, just pick the first item we have. lastSelectionOrDefault = items.Items.First(); } return lastSelectionOrDefault; } private static bool DisplayPartsMatch(SignatureHelpItem i1, SignatureHelpItem i2) => i1.GetAllParts().SequenceEqual(i2.GetAllParts(), CompareParts); private static bool CompareParts(TaggedText p1, TaggedText p2) => p1.ToString() == p2.ToString(); private static async Task<(ISignatureHelpProvider provider, SignatureHelpItems items)> ComputeItemsAsync( ImmutableArray<ISignatureHelpProvider> providers, SnapshotPoint caretPosition, SignatureHelpTriggerInfo triggerInfo, Document document, CancellationToken cancellationToken) { try { ISignatureHelpProvider bestProvider = null; SignatureHelpItems bestItems = null; // TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient // to the extension crashing. foreach (var provider in providers) { cancellationToken.ThrowIfCancellationRequested(); var currentItems = await provider.GetItemsAsync(document, caretPosition, triggerInfo, cancellationToken).ConfigureAwait(false); if (currentItems != null && currentItems.ApplicableSpan.IntersectsWith(caretPosition.Position)) { // If another provider provides sig help items, then only take them if they // start after the last batch of items. i.e. we want the set of items that // conceptually are closer to where the caret position is. This way if you have: // // Goo(new Bar($$ // // Then invoking sig help will only show the items for "new Bar(" and not also // the items for "Goo(..." if (IsBetter(bestItems, currentItems.ApplicableSpan)) { bestItems = currentItems; bestProvider = provider; } } } return (bestProvider, bestItems); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return (null, null); } } private static bool IsBetter(SignatureHelpItems bestItems, TextSpan? currentTextSpan) { // If we have no best text span, then this span is definitely better. if (bestItems == null) { return true; } // Otherwise we want the one that is conceptually the innermost signature. So it's // only better if the distance from it to the caret position is less than the best // one so far. return currentTextSpan.Value.Start > bestItems.ApplicableSpan.Start; } } } }
// 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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session { public void ComputeModel( ImmutableArray<ISignatureHelpProvider> providers, SignatureHelpTriggerInfo triggerInfo) { AssertIsForeground(); var caretPosition = Controller.TextView.GetCaretPoint(Controller.SubjectBuffer).Value; var disconnectedBufferGraph = new DisconnectedBufferGraph(Controller.SubjectBuffer, Controller.TextView.TextBuffer); // If we've already computed a model, then just use that. Otherwise, actually // compute a new model and send that along. Computation.ChainTaskAndNotifyControllerWhenFinished( (model, cancellationToken) => ComputeModelInBackgroundAsync( model, providers, caretPosition, disconnectedBufferGraph, triggerInfo, cancellationToken)); } private async Task<Model> ComputeModelInBackgroundAsync( Model currentModel, ImmutableArray<ISignatureHelpProvider> providers, SnapshotPoint caretPosition, DisconnectedBufferGraph disconnectedBufferGraph, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SignatureHelp_ModelComputation_ComputeModelInBackground, cancellationToken)) { AssertIsBackground(); cancellationToken.ThrowIfCancellationRequested(); var document = Controller.DocumentProvider.GetDocument(caretPosition.Snapshot, cancellationToken); if (document == null) { return currentModel; } // Let LSP handle signature help in the cloud scenario if (Controller.SubjectBuffer.IsInLspEditorContext()) { return null; } if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (currentModel == null) { return null; } if (triggerInfo.TriggerCharacter.HasValue && !currentModel.Provider.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value)) { return currentModel; } } // first try to query the providers that can trigger on the specified character var (provider, items) = await ComputeItemsAsync( providers, caretPosition, triggerInfo, document, cancellationToken).ConfigureAwait(false); if (provider == null) { // No provider produced items. So we can't produce a model return null; } if (currentModel != null && currentModel.Provider == provider && currentModel.GetCurrentSpanInSubjectBuffer(disconnectedBufferGraph.SubjectBufferSnapshot).Span.Start == items.ApplicableSpan.Start && currentModel.Items.IndexOf(currentModel.SelectedItem) == items.SelectedItemIndex && currentModel.ArgumentIndex == items.ArgumentIndex && currentModel.ArgumentCount == items.ArgumentCount && currentModel.ArgumentName == items.ArgumentName) { // The new model is the same as the current model. Return the currentModel // so we keep the active selection. return currentModel; } var selectedItem = GetSelectedItem(currentModel, items, provider, out var userSelected); var model = new Model(disconnectedBufferGraph, items.ApplicableSpan, provider, items.Items, selectedItem, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, selectedParameter: 0, userSelected); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var isCaseSensitive = syntaxFactsService == null || syntaxFactsService.IsCaseSensitive; var selection = DefaultSignatureHelpSelector.GetSelection(model.Items, model.SelectedItem, model.UserSelected, model.ArgumentIndex, model.ArgumentCount, model.ArgumentName, isCaseSensitive); return model.WithSelectedItem(selection.SelectedItem, selection.UserSelected) .WithSelectedParameter(selection.SelectedParameter); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static SignatureHelpItem GetSelectedItem(Model currentModel, SignatureHelpItems items, ISignatureHelpProvider provider, out bool userSelected) { // Try to find the most appropriate item in the list to select by default. // If it's the same provider as the previous model we have, and we had a user-selection, // then try to return the user-selection. if (currentModel != null && currentModel.Provider == provider && currentModel.UserSelected) { var userSelectedItem = items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)); if (userSelectedItem != null) { userSelected = true; return userSelectedItem; } } userSelected = false; // If the provider specified a selected item, then pick that one. if (items.SelectedItemIndex.HasValue) { return items.Items[items.SelectedItemIndex.Value]; } SignatureHelpItem lastSelectionOrDefault = null; if (currentModel != null && currentModel.Provider == provider) { // If the provider did not pick a default, and it's the same provider as the previous // model we have, then try to return the same item that we had before. lastSelectionOrDefault = items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)); } if (lastSelectionOrDefault == null) { // Otherwise, just pick the first item we have. lastSelectionOrDefault = items.Items.First(); } return lastSelectionOrDefault; } private static bool DisplayPartsMatch(SignatureHelpItem i1, SignatureHelpItem i2) => i1.GetAllParts().SequenceEqual(i2.GetAllParts(), CompareParts); private static bool CompareParts(TaggedText p1, TaggedText p2) => p1.ToString() == p2.ToString(); private static async Task<(ISignatureHelpProvider provider, SignatureHelpItems items)> ComputeItemsAsync( ImmutableArray<ISignatureHelpProvider> providers, SnapshotPoint caretPosition, SignatureHelpTriggerInfo triggerInfo, Document document, CancellationToken cancellationToken) { try { ISignatureHelpProvider bestProvider = null; SignatureHelpItems bestItems = null; // TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient // to the extension crashing. foreach (var provider in providers) { cancellationToken.ThrowIfCancellationRequested(); var currentItems = await provider.GetItemsAsync(document, caretPosition, triggerInfo, cancellationToken).ConfigureAwait(false); if (currentItems != null && currentItems.ApplicableSpan.IntersectsWith(caretPosition.Position)) { // If another provider provides sig help items, then only take them if they // start after the last batch of items. i.e. we want the set of items that // conceptually are closer to where the caret position is. This way if you have: // // Goo(new Bar($$ // // Then invoking sig help will only show the items for "new Bar(" and not also // the items for "Goo(..." if (IsBetter(bestItems, currentItems.ApplicableSpan)) { bestItems = currentItems; bestProvider = provider; } } } return (bestProvider, bestItems); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return (null, null); } } private static bool IsBetter(SignatureHelpItems bestItems, TextSpan? currentTextSpan) { // If we have no best text span, then this span is definitely better. if (bestItems == null) { return true; } // Otherwise we want the one that is conceptually the innermost signature. So it's // only better if the distance from it to the caret position is less than the best // one so far. return currentTextSpan.Value.Start > bestItems.ApplicableSpan.Start; } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Core/Portable/CodeGen/LocalSlotDebugInfo.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.CodeGen { internal struct LocalSlotDebugInfo : IEquatable<LocalSlotDebugInfo> { public readonly SynthesizedLocalKind SynthesizedKind; public readonly LocalDebugId Id; public LocalSlotDebugInfo(SynthesizedLocalKind synthesizedKind, LocalDebugId id) { this.SynthesizedKind = synthesizedKind; this.Id = id; } public bool Equals(LocalSlotDebugInfo other) { return this.SynthesizedKind == other.SynthesizedKind && this.Id.Equals(other.Id); } public override bool Equals(object? obj) { return obj is LocalSlotDebugInfo && Equals((LocalSlotDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine((int)SynthesizedKind, Id.GetHashCode()); } public override string ToString() { return SynthesizedKind.ToString() + " " + Id.ToString(); } } }
// 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.CodeGen { internal struct LocalSlotDebugInfo : IEquatable<LocalSlotDebugInfo> { public readonly SynthesizedLocalKind SynthesizedKind; public readonly LocalDebugId Id; public LocalSlotDebugInfo(SynthesizedLocalKind synthesizedKind, LocalDebugId id) { this.SynthesizedKind = synthesizedKind; this.Id = id; } public bool Equals(LocalSlotDebugInfo other) { return this.SynthesizedKind == other.SynthesizedKind && this.Id.Equals(other.Id); } public override bool Equals(object? obj) { return obj is LocalSlotDebugInfo && Equals((LocalSlotDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine((int)SynthesizedKind, Id.GetHashCode()); } public override string ToString() { return SynthesizedKind.ToString() + " " + Id.ToString(); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The parsed representation of a C# source document. /// </summary> public abstract partial class CSharpSyntaxTree : SyntaxTree { internal static readonly SyntaxTree Dummy = new DummySyntaxTree(); /// <summary> /// The options used by the parser to produce the syntax tree. /// </summary> public new abstract CSharpParseOptions Options { get; } // REVIEW: I would prefer to not expose CloneAsRoot and make the functionality // internal to CaaS layer, to ensure that for a given SyntaxTree there can not // be multiple trees claiming to be its children. // // However, as long as we provide GetRoot extensibility point on SyntaxTree // the guarantee above cannot be implemented and we have to provide some way for // creating root nodes. // // Therefore I place CloneAsRoot API on SyntaxTree and make it protected to // at least limit its visibility to SyntaxTree extenders. /// <summary> /// Produces a clone of a <see cref="CSharpSyntaxNode"/> which will have current syntax tree as its parent. /// /// Caller must guarantee that if the same instance of <see cref="CSharpSyntaxNode"/> makes multiple calls /// to this function, only one result is observable. /// </summary> /// <typeparam name="T">Type of the syntax node.</typeparam> /// <param name="node">The original syntax node.</param> /// <returns>A clone of the original syntax node that has current <see cref="CSharpSyntaxTree"/> as its parent.</returns> protected T CloneNodeAsRoot<T>(T node) where T : CSharpSyntaxNode { return CSharpSyntaxNode.CloneNodeAsRoot(node, this); } /// <summary> /// Gets the root node of the syntax tree. /// </summary> public new abstract CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default); /// <summary> /// Gets the root node of the syntax tree if it is already available. /// </summary> public abstract bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root); /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <remarks> /// By default, the work associated with this method will be executed immediately on the current thread. /// Implementations that wish to schedule this work differently should override <see cref="GetRootAsync(CancellationToken)"/>. /// </remarks> public new virtual Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken = default) { return Task.FromResult(this.TryGetRoot(out CSharpSyntaxNode? node) ? node : this.GetRoot(cancellationToken)); } /// <summary> /// Gets the root of the syntax tree statically typed as <see cref="CompilationUnitSyntax"/>. /// </summary> /// <remarks> /// Ensure that <see cref="SyntaxTree.HasCompilationUnitRoot"/> is true for this tree prior to invoking this method. /// </remarks> /// <exception cref="InvalidCastException">Throws this exception if <see cref="SyntaxTree.HasCompilationUnitRoot"/> is false.</exception> public CompilationUnitSyntax GetCompilationUnitRoot(CancellationToken cancellationToken = default) { return (CompilationUnitSyntax)this.GetRoot(cancellationToken); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="tree">The tree to compare against.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring metadata visible symbolic information are equivalent, /// ignoring any differences of nodes inside method bodies or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public override bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, tree, topLevel); } internal bool HasReferenceDirectives { get { Debug.Assert(HasCompilationUnitRoot); return Options.Kind == SourceCodeKind.Script && GetCompilationUnitRoot().GetReferenceDirectives().Count > 0; } } internal bool HasReferenceOrLoadDirectives { get { Debug.Assert(HasCompilationUnitRoot); if (Options.Kind == SourceCodeKind.Script) { var compilationUnitRoot = GetCompilationUnitRoot(); return compilationUnitRoot.GetReferenceDirectives().Count > 0 || compilationUnitRoot.GetLoadDirectives().Count > 0; } return false; } } #region Preprocessor Symbols private bool _hasDirectives; private InternalSyntax.DirectiveStack _directives; internal void SetDirectiveStack(InternalSyntax.DirectiveStack directives) { _directives = directives; _hasDirectives = true; } private InternalSyntax.DirectiveStack GetDirectives() { if (!_hasDirectives) { var stack = this.GetRoot().CsGreen.ApplyDirectives(default); SetDirectiveStack(stack); } return _directives; } internal bool IsAnyPreprocessorSymbolDefined(ImmutableArray<string> conditionalSymbols) { Debug.Assert(conditionalSymbols != null); foreach (string conditionalSymbol in conditionalSymbols) { if (IsPreprocessorSymbolDefined(conditionalSymbol)) { return true; } } return false; } internal bool IsPreprocessorSymbolDefined(string symbolName) { return IsPreprocessorSymbolDefined(GetDirectives(), symbolName); } private bool IsPreprocessorSymbolDefined(InternalSyntax.DirectiveStack directives, string symbolName) { switch (directives.IsDefined(symbolName)) { case InternalSyntax.DefineState.Defined: return true; case InternalSyntax.DefineState.Undefined: return false; default: return this.Options.PreprocessorSymbols.Contains(symbolName); } } /// <summary> /// Stores positions where preprocessor state changes. Sorted by position. /// The updated state can be found in <see cref="_preprocessorStates"/> array at the same index. /// </summary> private ImmutableArray<int> _preprocessorStateChangePositions; /// <summary> /// Preprocessor states corresponding to positions in <see cref="_preprocessorStateChangePositions"/>. /// </summary> private ImmutableArray<InternalSyntax.DirectiveStack> _preprocessorStates; internal bool IsPreprocessorSymbolDefined(string symbolName, int position) { if (_preprocessorStateChangePositions.IsDefault) { BuildPreprocessorStateChangeMap(); } int searchResult = _preprocessorStateChangePositions.BinarySearch(position); InternalSyntax.DirectiveStack directives; if (searchResult < 0) { searchResult = (~searchResult) - 1; if (searchResult >= 0) { directives = _preprocessorStates[searchResult]; } else { directives = InternalSyntax.DirectiveStack.Empty; } } else { directives = _preprocessorStates[searchResult]; } return IsPreprocessorSymbolDefined(directives, symbolName); } private void BuildPreprocessorStateChangeMap() { InternalSyntax.DirectiveStack currentState = InternalSyntax.DirectiveStack.Empty; var positions = ArrayBuilder<int>.GetInstance(); var states = ArrayBuilder<InternalSyntax.DirectiveStack>.GetInstance(); foreach (DirectiveTriviaSyntax directive in this.GetRoot().GetDirectives(d => { switch (d.Kind()) { case SyntaxKind.IfDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.EndIfDirectiveTrivia: case SyntaxKind.DefineDirectiveTrivia: case SyntaxKind.UndefDirectiveTrivia: return true; default: return false; } })) { currentState = directive.ApplyDirectives(currentState); switch (directive.Kind()) { case SyntaxKind.IfDirectiveTrivia: // #if directive doesn't affect the set of defined/undefined symbols break; case SyntaxKind.ElifDirectiveTrivia: states.Add(currentState); positions.Add(((ElifDirectiveTriviaSyntax)directive).ElifKeyword.SpanStart); break; case SyntaxKind.ElseDirectiveTrivia: states.Add(currentState); positions.Add(((ElseDirectiveTriviaSyntax)directive).ElseKeyword.SpanStart); break; case SyntaxKind.EndIfDirectiveTrivia: states.Add(currentState); positions.Add(((EndIfDirectiveTriviaSyntax)directive).EndIfKeyword.SpanStart); break; case SyntaxKind.DefineDirectiveTrivia: states.Add(currentState); positions.Add(((DefineDirectiveTriviaSyntax)directive).Name.SpanStart); break; case SyntaxKind.UndefDirectiveTrivia: states.Add(currentState); positions.Add(((UndefDirectiveTriviaSyntax)directive).Name.SpanStart); break; default: throw ExceptionUtilities.UnexpectedValue(directive.Kind()); } } #if DEBUG int currentPos = -1; foreach (int pos in positions) { Debug.Assert(currentPos < pos); currentPos = pos; } #endif ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStates, states.ToImmutableAndFree()); ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStateChangePositions, positions.ToImmutableAndFree()); } #endregion #region Factories // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return Create(root, options, path, encoding, diagnosticOptions: null); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, // obsolete parameter -- unused ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, // obsolete parameter -- unused bool? isGeneratedCode) { if (root == null) { throw new ArgumentNullException(nameof(root)); } var directives = root.Kind() == SyntaxKind.CompilationUnit ? ((CompilationUnitSyntax)root).GetConditionalDirectivesStack() : InternalSyntax.DirectiveStack.Empty; return new ParsedSyntaxTree( textOpt: null, encodingOpt: encoding, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: path, options: options ?? CSharpParseOptions.Default, root: root, directives: directives, diagnosticOptions, cloneRoot: true); } /// <summary> /// Creates a new syntax tree from a syntax node with text that should correspond to the syntax node. /// </summary> /// <remarks>This is used by the ExpressionEvaluator.</remarks> internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) { Debug.Assert(root != null); return new DebuggerSyntaxTree(root, text, options); } /// <summary> /// <para> /// Internal helper for <see cref="CSharpSyntaxNode"/> class to create a new syntax tree rooted at the given root node. /// This method does not create a clone of the given root, but instead preserves it's reference identity. /// </para> /// <para>NOTE: This method is only intended to be used from <see cref="CSharpSyntaxNode.SyntaxTree"/> property.</para> /// <para>NOTE: Do not use this method elsewhere, instead use <see cref="Create(CSharpSyntaxNode, CSharpParseOptions, string, Encoding)"/> method for creating a syntax tree.</para> /// </summary> internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) { Debug.Assert(root != null); return new ParsedSyntaxTree( textOpt: null, encodingOpt: null, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: "", options: CSharpParseOptions.Default, root: root, directives: InternalSyntax.DirectiveStack.Empty, diagnosticOptions: null, cloneRoot: false); } /// <summary> /// Produces a syntax tree by parsing the source text lazily. The syntax tree is realized when /// <see cref="CSharpSyntaxTree.GetRoot(CancellationToken)"/> is called. /// </summary> internal static SyntaxTree ParseTextLazy( SourceText text, CSharpParseOptions? options = null, string path = "") { return new LazySyntaxTree(text, options ?? CSharpParseOptions.Default, path, diagnosticOptions: null); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( string text, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, encoding, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseText(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { if (text == null) { throw new ArgumentNullException(nameof(text)); } options = options ?? CSharpParseOptions.Default; using var lexer = new InternalSyntax.Lexer(text, options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null, cancellationToken: cancellationToken); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( text, text.Encoding, text.ChecksumAlgorithm, path, options, compilationUnit, parser.Directives, diagnosticOptions: diagnosticOptions, cloneRoot: true); tree.VerifySource(); return tree; } #endregion #region Changes /// <summary> /// Creates a new syntax based off this tree using a new source text. /// </summary> /// <remarks> /// If the new source text is a minor change from the current source text an incremental parse will occur /// reusing most of the current syntax tree internal data. Otherwise, a full parse will occur using the new /// source text. /// </remarks> public override SyntaxTree WithChangedText(SourceText newText) { // try to find the changes between the old text and the new text. if (this.TryGetText(out SourceText? oldText)) { var changes = newText.GetChangeRanges(oldText); if (changes.Count == 0 && newText == oldText) { return this; } return this.WithChanges(newText, changes); } // if we do not easily know the old text, then specify entire text as changed so we do a full reparse. return this.WithChanges(newText, new[] { new TextChangeRange(new TextSpan(0, this.Length), newText.Length) }); } private SyntaxTree WithChanges(SourceText newText, IReadOnlyList<TextChangeRange> changes) { if (changes == null) { throw new ArgumentNullException(nameof(changes)); } IReadOnlyList<TextChangeRange>? workingChanges = changes; CSharpSyntaxTree? oldTree = this; // if changes is entire text do a full reparse if (workingChanges.Count == 1 && workingChanges[0].Span == new TextSpan(0, this.Length) && workingChanges[0].NewLength == newText.Length) { // parser will do a full parse if we give it no changes workingChanges = null; oldTree = null; } using var lexer = new InternalSyntax.Lexer(newText, this.Options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree?.GetRoot(), workingChanges); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( newText, newText.Encoding, newText.ChecksumAlgorithm, FilePath, Options, compilationUnit, parser.Directives, #pragma warning disable CS0618 DiagnosticOptions, #pragma warning restore CS0618 cloneRoot: true); tree.VerifySource(changes); return tree; } /// <summary> /// Produces a pessimistic list of spans that denote the regions of text in this tree that /// are changed from the text of the old tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list is pessimistic because it may claim more or larger regions than actually changed.</remarks> public override IList<TextSpan> GetChangedSpans(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetPossiblyDifferentTextSpans(oldTree, this); } /// <summary> /// Gets a list of text changes that when applied to the old tree produce this tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list of changes may be different than the original changes that produced this tree.</remarks> public override IList<TextChange> GetChanges(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetTextChanges(oldTree, this); } #endregion #region LinePositions and Locations private CSharpLineDirectiveMap GetDirectiveMap() { if (_lazyLineDirectiveMap == null) { // Create the line directive map on demand. Interlocked.CompareExchange(ref _lazyLineDirectiveMap, new CSharpLineDirectiveMap(this), null); } return _lazyLineDirectiveMap; } /// <summary> /// Gets the location in terms of path, line and column for a given span. /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <see cref="FileLinePositionSpan"/> that contains path, line and column information. /// </returns> /// <remarks>The values are not affected by line mapping directives (<c>#line</c>).</remarks> public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default) => new(FilePath, GetLinePosition(span.Start, cancellationToken), GetLinePosition(span.End, cancellationToken)); /// <summary> /// Gets the location in terms of path, line and column after applying source line mapping directives (<c>#line</c>). /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <para>A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.</para> /// <para> /// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>, /// otherwise it's <see cref="SyntaxTree.FilePath"/>. /// </para> /// <para> /// A location path is considered mapped if the first <c>#line</c> directive that precedes it and that /// either specifies an explicit file path or is <c>#line default</c> exists and specifies an explicit path. /// </para> /// </returns> public override FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default) => GetDirectiveMap().TranslateSpan(GetText(cancellationToken), this.FilePath, span); /// <inheritdoc/> public override LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default) => GetDirectiveMap().GetLineVisibility(GetText(cancellationToken), position); /// <inheritdoc/> public override IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default) { var map = GetDirectiveMap(); Debug.Assert(map.Entries.Length >= 1); return (map.Entries.Length == 1) ? Array.Empty<LineMapping>() : map.GetLineMappings(GetText(cancellationToken).Lines); } /// <summary> /// Gets a <see cref="FileLinePositionSpan"/> for a <see cref="TextSpan"/>. FileLinePositionSpans are used /// primarily for diagnostics and source locations. /// </summary> /// <param name="span">The source <see cref="TextSpan" /> to convert.</param> /// <param name="isHiddenPosition">When the method returns, contains a boolean value indicating whether this span is considered hidden or not.</param> /// <returns>A resulting <see cref="FileLinePositionSpan"/>.</returns> internal override FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) => GetDirectiveMap().TranslateSpanAndVisibility(GetText(), FilePath, span, out isHiddenPosition); /// <summary> /// Gets a boolean value indicating whether there are any hidden regions in the tree. /// </summary> /// <returns>True if there is at least one hidden region.</returns> public override bool HasHiddenRegions() => GetDirectiveMap().HasAnyHiddenRegions(); /// <summary> /// Given the error code and the source location, get the warning state based on <c>#pragma warning</c> directives. /// </summary> /// <param name="id">Error code.</param> /// <param name="position">Source location.</param> internal PragmaWarningState GetPragmaDirectiveWarningState(string id, int position) { if (_lazyPragmaWarningStateMap == null) { // Create the warning state map on demand. Interlocked.CompareExchange(ref _lazyPragmaWarningStateMap, new CSharpPragmaWarningStateMap(this), null); } return _lazyPragmaWarningStateMap.GetWarningState(id, position); } private NullableContextStateMap GetNullableContextStateMap() { if (_lazyNullableContextStateMap == null) { // Create the #nullable directive map on demand. Interlocked.CompareExchange( ref _lazyNullableContextStateMap, new StrongBox<NullableContextStateMap>(NullableContextStateMap.Create(this)), null); } return _lazyNullableContextStateMap.Value; } internal NullableContextState GetNullableContextState(int position) => GetNullableContextStateMap().GetContextState(position); internal bool? IsNullableAnalysisEnabled(TextSpan span) => GetNullableContextStateMap().IsNullableAnalysisEnabled(span); internal bool IsGeneratedCode(SyntaxTreeOptionsProvider? provider, CancellationToken cancellationToken) { return provider?.IsGenerated(this, cancellationToken) switch { null or GeneratedKind.Unknown => isGeneratedHeuristic(), GeneratedKind kind => kind != GeneratedKind.NotGenerated }; bool isGeneratedHeuristic() { if (_lazyIsGeneratedCode == GeneratedKind.Unknown) { // Create the generated code status on demand bool isGenerated = GeneratedCodeUtilities.IsGeneratedCode( this, isComment: trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia, cancellationToken: default); _lazyIsGeneratedCode = isGenerated ? GeneratedKind.MarkedGenerated : GeneratedKind.NotGenerated; } return _lazyIsGeneratedCode == GeneratedKind.MarkedGenerated; } } private CSharpLineDirectiveMap? _lazyLineDirectiveMap; private CSharpPragmaWarningStateMap? _lazyPragmaWarningStateMap; private StrongBox<NullableContextStateMap>? _lazyNullableContextStateMap; private GeneratedKind _lazyIsGeneratedCode = GeneratedKind.Unknown; private LinePosition GetLinePosition(int position, CancellationToken cancellationToken) => GetText(cancellationToken).Lines.GetLinePosition(position); /// <summary> /// Gets a <see cref="Location"/> for the specified text <paramref name="span"/>. /// </summary> public override Location GetLocation(TextSpan span) { return new SourceLocation(this, span); } #endregion #region Diagnostics /// <summary> /// Gets a list of all the diagnostics in the sub tree that has the specified node as its root. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return GetDiagnostics(node.Green, node.Position); } private IEnumerable<Diagnostic> GetDiagnostics(GreenNode greenNode, int position) { if (greenNode == null) { throw new InvalidOperationException(); } if (greenNode.ContainsDiagnostics) { return EnumerateDiagnostics(greenNode, position); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } private IEnumerable<Diagnostic> EnumerateDiagnostics(GreenNode node, int position) { var enumerator = new SyntaxTreeDiagnosticEnumerator(this, node, position); while (enumerator.MoveNext()) { yield return enumerator.Current; } } /// <summary> /// Gets a list of all the diagnostics associated with the token and any related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token) { if (token.Node == null) { throw new InvalidOperationException(); } return GetDiagnostics(token.Node, token.Position); } /// <summary> /// Gets a list of all the diagnostics associated with the trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia) { if (trivia.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(trivia.UnderlyingNode, trivia.Position); } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or /// associated with the token and its related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(nodeOrToken.UnderlyingNode, nodeOrToken.Position); } /// <summary> /// Gets a list of all the diagnostics in the syntax tree. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return this.GetDiagnostics(this.GetRoot(cancellationToken)); } #endregion #region SyntaxTree protected override SyntaxNode GetRootCore(CancellationToken cancellationToken) { return this.GetRoot(cancellationToken); } protected override async Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken) { return await this.GetRootAsync(cancellationToken).ConfigureAwait(false); } protected override bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root) { if (this.TryGetRoot(out CSharpSyntaxNode? node)) { root = node; return true; } else { root = null; return false; } } protected override ParseOptions OptionsCore { get { return this.Options; } } #endregion // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, encoding, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions) => Create(root, options, path, encoding, diagnosticOptions, isGeneratedCode: null); } }
// 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The parsed representation of a C# source document. /// </summary> public abstract partial class CSharpSyntaxTree : SyntaxTree { internal static readonly SyntaxTree Dummy = new DummySyntaxTree(); /// <summary> /// The options used by the parser to produce the syntax tree. /// </summary> public new abstract CSharpParseOptions Options { get; } // REVIEW: I would prefer to not expose CloneAsRoot and make the functionality // internal to CaaS layer, to ensure that for a given SyntaxTree there can not // be multiple trees claiming to be its children. // // However, as long as we provide GetRoot extensibility point on SyntaxTree // the guarantee above cannot be implemented and we have to provide some way for // creating root nodes. // // Therefore I place CloneAsRoot API on SyntaxTree and make it protected to // at least limit its visibility to SyntaxTree extenders. /// <summary> /// Produces a clone of a <see cref="CSharpSyntaxNode"/> which will have current syntax tree as its parent. /// /// Caller must guarantee that if the same instance of <see cref="CSharpSyntaxNode"/> makes multiple calls /// to this function, only one result is observable. /// </summary> /// <typeparam name="T">Type of the syntax node.</typeparam> /// <param name="node">The original syntax node.</param> /// <returns>A clone of the original syntax node that has current <see cref="CSharpSyntaxTree"/> as its parent.</returns> protected T CloneNodeAsRoot<T>(T node) where T : CSharpSyntaxNode { return CSharpSyntaxNode.CloneNodeAsRoot(node, this); } /// <summary> /// Gets the root node of the syntax tree. /// </summary> public new abstract CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default); /// <summary> /// Gets the root node of the syntax tree if it is already available. /// </summary> public abstract bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root); /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <remarks> /// By default, the work associated with this method will be executed immediately on the current thread. /// Implementations that wish to schedule this work differently should override <see cref="GetRootAsync(CancellationToken)"/>. /// </remarks> public new virtual Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken = default) { return Task.FromResult(this.TryGetRoot(out CSharpSyntaxNode? node) ? node : this.GetRoot(cancellationToken)); } /// <summary> /// Gets the root of the syntax tree statically typed as <see cref="CompilationUnitSyntax"/>. /// </summary> /// <remarks> /// Ensure that <see cref="SyntaxTree.HasCompilationUnitRoot"/> is true for this tree prior to invoking this method. /// </remarks> /// <exception cref="InvalidCastException">Throws this exception if <see cref="SyntaxTree.HasCompilationUnitRoot"/> is false.</exception> public CompilationUnitSyntax GetCompilationUnitRoot(CancellationToken cancellationToken = default) { return (CompilationUnitSyntax)this.GetRoot(cancellationToken); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="tree">The tree to compare against.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring metadata visible symbolic information are equivalent, /// ignoring any differences of nodes inside method bodies or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public override bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, tree, topLevel); } internal bool HasReferenceDirectives { get { Debug.Assert(HasCompilationUnitRoot); return Options.Kind == SourceCodeKind.Script && GetCompilationUnitRoot().GetReferenceDirectives().Count > 0; } } internal bool HasReferenceOrLoadDirectives { get { Debug.Assert(HasCompilationUnitRoot); if (Options.Kind == SourceCodeKind.Script) { var compilationUnitRoot = GetCompilationUnitRoot(); return compilationUnitRoot.GetReferenceDirectives().Count > 0 || compilationUnitRoot.GetLoadDirectives().Count > 0; } return false; } } #region Preprocessor Symbols private bool _hasDirectives; private InternalSyntax.DirectiveStack _directives; internal void SetDirectiveStack(InternalSyntax.DirectiveStack directives) { _directives = directives; _hasDirectives = true; } private InternalSyntax.DirectiveStack GetDirectives() { if (!_hasDirectives) { var stack = this.GetRoot().CsGreen.ApplyDirectives(default); SetDirectiveStack(stack); } return _directives; } internal bool IsAnyPreprocessorSymbolDefined(ImmutableArray<string> conditionalSymbols) { Debug.Assert(conditionalSymbols != null); foreach (string conditionalSymbol in conditionalSymbols) { if (IsPreprocessorSymbolDefined(conditionalSymbol)) { return true; } } return false; } internal bool IsPreprocessorSymbolDefined(string symbolName) { return IsPreprocessorSymbolDefined(GetDirectives(), symbolName); } private bool IsPreprocessorSymbolDefined(InternalSyntax.DirectiveStack directives, string symbolName) { switch (directives.IsDefined(symbolName)) { case InternalSyntax.DefineState.Defined: return true; case InternalSyntax.DefineState.Undefined: return false; default: return this.Options.PreprocessorSymbols.Contains(symbolName); } } /// <summary> /// Stores positions where preprocessor state changes. Sorted by position. /// The updated state can be found in <see cref="_preprocessorStates"/> array at the same index. /// </summary> private ImmutableArray<int> _preprocessorStateChangePositions; /// <summary> /// Preprocessor states corresponding to positions in <see cref="_preprocessorStateChangePositions"/>. /// </summary> private ImmutableArray<InternalSyntax.DirectiveStack> _preprocessorStates; internal bool IsPreprocessorSymbolDefined(string symbolName, int position) { if (_preprocessorStateChangePositions.IsDefault) { BuildPreprocessorStateChangeMap(); } int searchResult = _preprocessorStateChangePositions.BinarySearch(position); InternalSyntax.DirectiveStack directives; if (searchResult < 0) { searchResult = (~searchResult) - 1; if (searchResult >= 0) { directives = _preprocessorStates[searchResult]; } else { directives = InternalSyntax.DirectiveStack.Empty; } } else { directives = _preprocessorStates[searchResult]; } return IsPreprocessorSymbolDefined(directives, symbolName); } private void BuildPreprocessorStateChangeMap() { InternalSyntax.DirectiveStack currentState = InternalSyntax.DirectiveStack.Empty; var positions = ArrayBuilder<int>.GetInstance(); var states = ArrayBuilder<InternalSyntax.DirectiveStack>.GetInstance(); foreach (DirectiveTriviaSyntax directive in this.GetRoot().GetDirectives(d => { switch (d.Kind()) { case SyntaxKind.IfDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.EndIfDirectiveTrivia: case SyntaxKind.DefineDirectiveTrivia: case SyntaxKind.UndefDirectiveTrivia: return true; default: return false; } })) { currentState = directive.ApplyDirectives(currentState); switch (directive.Kind()) { case SyntaxKind.IfDirectiveTrivia: // #if directive doesn't affect the set of defined/undefined symbols break; case SyntaxKind.ElifDirectiveTrivia: states.Add(currentState); positions.Add(((ElifDirectiveTriviaSyntax)directive).ElifKeyword.SpanStart); break; case SyntaxKind.ElseDirectiveTrivia: states.Add(currentState); positions.Add(((ElseDirectiveTriviaSyntax)directive).ElseKeyword.SpanStart); break; case SyntaxKind.EndIfDirectiveTrivia: states.Add(currentState); positions.Add(((EndIfDirectiveTriviaSyntax)directive).EndIfKeyword.SpanStart); break; case SyntaxKind.DefineDirectiveTrivia: states.Add(currentState); positions.Add(((DefineDirectiveTriviaSyntax)directive).Name.SpanStart); break; case SyntaxKind.UndefDirectiveTrivia: states.Add(currentState); positions.Add(((UndefDirectiveTriviaSyntax)directive).Name.SpanStart); break; default: throw ExceptionUtilities.UnexpectedValue(directive.Kind()); } } #if DEBUG int currentPos = -1; foreach (int pos in positions) { Debug.Assert(currentPos < pos); currentPos = pos; } #endif ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStates, states.ToImmutableAndFree()); ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStateChangePositions, positions.ToImmutableAndFree()); } #endregion #region Factories // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return Create(root, options, path, encoding, diagnosticOptions: null); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, // obsolete parameter -- unused ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, // obsolete parameter -- unused bool? isGeneratedCode) { if (root == null) { throw new ArgumentNullException(nameof(root)); } var directives = root.Kind() == SyntaxKind.CompilationUnit ? ((CompilationUnitSyntax)root).GetConditionalDirectivesStack() : InternalSyntax.DirectiveStack.Empty; return new ParsedSyntaxTree( textOpt: null, encodingOpt: encoding, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: path, options: options ?? CSharpParseOptions.Default, root: root, directives: directives, diagnosticOptions, cloneRoot: true); } /// <summary> /// Creates a new syntax tree from a syntax node with text that should correspond to the syntax node. /// </summary> /// <remarks>This is used by the ExpressionEvaluator.</remarks> internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) { Debug.Assert(root != null); return new DebuggerSyntaxTree(root, text, options); } /// <summary> /// <para> /// Internal helper for <see cref="CSharpSyntaxNode"/> class to create a new syntax tree rooted at the given root node. /// This method does not create a clone of the given root, but instead preserves it's reference identity. /// </para> /// <para>NOTE: This method is only intended to be used from <see cref="CSharpSyntaxNode.SyntaxTree"/> property.</para> /// <para>NOTE: Do not use this method elsewhere, instead use <see cref="Create(CSharpSyntaxNode, CSharpParseOptions, string, Encoding)"/> method for creating a syntax tree.</para> /// </summary> internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) { Debug.Assert(root != null); return new ParsedSyntaxTree( textOpt: null, encodingOpt: null, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: "", options: CSharpParseOptions.Default, root: root, directives: InternalSyntax.DirectiveStack.Empty, diagnosticOptions: null, cloneRoot: false); } /// <summary> /// Produces a syntax tree by parsing the source text lazily. The syntax tree is realized when /// <see cref="CSharpSyntaxTree.GetRoot(CancellationToken)"/> is called. /// </summary> internal static SyntaxTree ParseTextLazy( SourceText text, CSharpParseOptions? options = null, string path = "") { return new LazySyntaxTree(text, options ?? CSharpParseOptions.Default, path, diagnosticOptions: null); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( string text, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, encoding, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseText(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { if (text == null) { throw new ArgumentNullException(nameof(text)); } options = options ?? CSharpParseOptions.Default; using var lexer = new InternalSyntax.Lexer(text, options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null, cancellationToken: cancellationToken); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( text, text.Encoding, text.ChecksumAlgorithm, path, options, compilationUnit, parser.Directives, diagnosticOptions: diagnosticOptions, cloneRoot: true); tree.VerifySource(); return tree; } #endregion #region Changes /// <summary> /// Creates a new syntax based off this tree using a new source text. /// </summary> /// <remarks> /// If the new source text is a minor change from the current source text an incremental parse will occur /// reusing most of the current syntax tree internal data. Otherwise, a full parse will occur using the new /// source text. /// </remarks> public override SyntaxTree WithChangedText(SourceText newText) { // try to find the changes between the old text and the new text. if (this.TryGetText(out SourceText? oldText)) { var changes = newText.GetChangeRanges(oldText); if (changes.Count == 0 && newText == oldText) { return this; } return this.WithChanges(newText, changes); } // if we do not easily know the old text, then specify entire text as changed so we do a full reparse. return this.WithChanges(newText, new[] { new TextChangeRange(new TextSpan(0, this.Length), newText.Length) }); } private SyntaxTree WithChanges(SourceText newText, IReadOnlyList<TextChangeRange> changes) { if (changes == null) { throw new ArgumentNullException(nameof(changes)); } IReadOnlyList<TextChangeRange>? workingChanges = changes; CSharpSyntaxTree? oldTree = this; // if changes is entire text do a full reparse if (workingChanges.Count == 1 && workingChanges[0].Span == new TextSpan(0, this.Length) && workingChanges[0].NewLength == newText.Length) { // parser will do a full parse if we give it no changes workingChanges = null; oldTree = null; } using var lexer = new InternalSyntax.Lexer(newText, this.Options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree?.GetRoot(), workingChanges); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( newText, newText.Encoding, newText.ChecksumAlgorithm, FilePath, Options, compilationUnit, parser.Directives, #pragma warning disable CS0618 DiagnosticOptions, #pragma warning restore CS0618 cloneRoot: true); tree.VerifySource(changes); return tree; } /// <summary> /// Produces a pessimistic list of spans that denote the regions of text in this tree that /// are changed from the text of the old tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list is pessimistic because it may claim more or larger regions than actually changed.</remarks> public override IList<TextSpan> GetChangedSpans(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetPossiblyDifferentTextSpans(oldTree, this); } /// <summary> /// Gets a list of text changes that when applied to the old tree produce this tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list of changes may be different than the original changes that produced this tree.</remarks> public override IList<TextChange> GetChanges(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetTextChanges(oldTree, this); } #endregion #region LinePositions and Locations private CSharpLineDirectiveMap GetDirectiveMap() { if (_lazyLineDirectiveMap == null) { // Create the line directive map on demand. Interlocked.CompareExchange(ref _lazyLineDirectiveMap, new CSharpLineDirectiveMap(this), null); } return _lazyLineDirectiveMap; } /// <summary> /// Gets the location in terms of path, line and column for a given span. /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <see cref="FileLinePositionSpan"/> that contains path, line and column information. /// </returns> /// <remarks>The values are not affected by line mapping directives (<c>#line</c>).</remarks> public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default) => new(FilePath, GetLinePosition(span.Start, cancellationToken), GetLinePosition(span.End, cancellationToken)); /// <summary> /// Gets the location in terms of path, line and column after applying source line mapping directives (<c>#line</c>). /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <para>A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.</para> /// <para> /// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>, /// otherwise it's <see cref="SyntaxTree.FilePath"/>. /// </para> /// <para> /// A location path is considered mapped if the first <c>#line</c> directive that precedes it and that /// either specifies an explicit file path or is <c>#line default</c> exists and specifies an explicit path. /// </para> /// </returns> public override FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default) => GetDirectiveMap().TranslateSpan(GetText(cancellationToken), this.FilePath, span); /// <inheritdoc/> public override LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default) => GetDirectiveMap().GetLineVisibility(GetText(cancellationToken), position); /// <inheritdoc/> public override IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default) { var map = GetDirectiveMap(); Debug.Assert(map.Entries.Length >= 1); return (map.Entries.Length == 1) ? Array.Empty<LineMapping>() : map.GetLineMappings(GetText(cancellationToken).Lines); } /// <summary> /// Gets a <see cref="FileLinePositionSpan"/> for a <see cref="TextSpan"/>. FileLinePositionSpans are used /// primarily for diagnostics and source locations. /// </summary> /// <param name="span">The source <see cref="TextSpan" /> to convert.</param> /// <param name="isHiddenPosition">When the method returns, contains a boolean value indicating whether this span is considered hidden or not.</param> /// <returns>A resulting <see cref="FileLinePositionSpan"/>.</returns> internal override FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) => GetDirectiveMap().TranslateSpanAndVisibility(GetText(), FilePath, span, out isHiddenPosition); /// <summary> /// Gets a boolean value indicating whether there are any hidden regions in the tree. /// </summary> /// <returns>True if there is at least one hidden region.</returns> public override bool HasHiddenRegions() => GetDirectiveMap().HasAnyHiddenRegions(); /// <summary> /// Given the error code and the source location, get the warning state based on <c>#pragma warning</c> directives. /// </summary> /// <param name="id">Error code.</param> /// <param name="position">Source location.</param> internal PragmaWarningState GetPragmaDirectiveWarningState(string id, int position) { if (_lazyPragmaWarningStateMap == null) { // Create the warning state map on demand. Interlocked.CompareExchange(ref _lazyPragmaWarningStateMap, new CSharpPragmaWarningStateMap(this), null); } return _lazyPragmaWarningStateMap.GetWarningState(id, position); } private NullableContextStateMap GetNullableContextStateMap() { if (_lazyNullableContextStateMap == null) { // Create the #nullable directive map on demand. Interlocked.CompareExchange( ref _lazyNullableContextStateMap, new StrongBox<NullableContextStateMap>(NullableContextStateMap.Create(this)), null); } return _lazyNullableContextStateMap.Value; } internal NullableContextState GetNullableContextState(int position) => GetNullableContextStateMap().GetContextState(position); internal bool? IsNullableAnalysisEnabled(TextSpan span) => GetNullableContextStateMap().IsNullableAnalysisEnabled(span); internal bool IsGeneratedCode(SyntaxTreeOptionsProvider? provider, CancellationToken cancellationToken) { return provider?.IsGenerated(this, cancellationToken) switch { null or GeneratedKind.Unknown => isGeneratedHeuristic(), GeneratedKind kind => kind != GeneratedKind.NotGenerated }; bool isGeneratedHeuristic() { if (_lazyIsGeneratedCode == GeneratedKind.Unknown) { // Create the generated code status on demand bool isGenerated = GeneratedCodeUtilities.IsGeneratedCode( this, isComment: trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia, cancellationToken: default); _lazyIsGeneratedCode = isGenerated ? GeneratedKind.MarkedGenerated : GeneratedKind.NotGenerated; } return _lazyIsGeneratedCode == GeneratedKind.MarkedGenerated; } } private CSharpLineDirectiveMap? _lazyLineDirectiveMap; private CSharpPragmaWarningStateMap? _lazyPragmaWarningStateMap; private StrongBox<NullableContextStateMap>? _lazyNullableContextStateMap; private GeneratedKind _lazyIsGeneratedCode = GeneratedKind.Unknown; private LinePosition GetLinePosition(int position, CancellationToken cancellationToken) => GetText(cancellationToken).Lines.GetLinePosition(position); /// <summary> /// Gets a <see cref="Location"/> for the specified text <paramref name="span"/>. /// </summary> public override Location GetLocation(TextSpan span) { return new SourceLocation(this, span); } #endregion #region Diagnostics /// <summary> /// Gets a list of all the diagnostics in the sub tree that has the specified node as its root. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return GetDiagnostics(node.Green, node.Position); } private IEnumerable<Diagnostic> GetDiagnostics(GreenNode greenNode, int position) { if (greenNode == null) { throw new InvalidOperationException(); } if (greenNode.ContainsDiagnostics) { return EnumerateDiagnostics(greenNode, position); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } private IEnumerable<Diagnostic> EnumerateDiagnostics(GreenNode node, int position) { var enumerator = new SyntaxTreeDiagnosticEnumerator(this, node, position); while (enumerator.MoveNext()) { yield return enumerator.Current; } } /// <summary> /// Gets a list of all the diagnostics associated with the token and any related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token) { if (token.Node == null) { throw new InvalidOperationException(); } return GetDiagnostics(token.Node, token.Position); } /// <summary> /// Gets a list of all the diagnostics associated with the trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia) { if (trivia.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(trivia.UnderlyingNode, trivia.Position); } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or /// associated with the token and its related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(nodeOrToken.UnderlyingNode, nodeOrToken.Position); } /// <summary> /// Gets a list of all the diagnostics in the syntax tree. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return this.GetDiagnostics(this.GetRoot(cancellationToken)); } #endregion #region SyntaxTree protected override SyntaxNode GetRootCore(CancellationToken cancellationToken) { return this.GetRoot(cancellationToken); } protected override async Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken) { return await this.GetRootAsync(cancellationToken).ConfigureAwait(false); } protected override bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root) { if (this.TryGetRoot(out CSharpSyntaxNode? node)) { root = node; return true; } else { root = null; return false; } } protected override ParseOptions OptionsCore { get { return this.Options; } } #endregion // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, encoding, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions) => Create(root, options, path, encoding, diagnosticOptions, isGeneratedCode: null); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionHandler.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSInternalCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSInternalCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSInternalCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
// 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSInternalCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSInternalCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSInternalCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveLanguageNames.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 namespace Microsoft.CodeAnalysis.Interactive { internal class InteractiveLanguageNames { public const string InteractiveCommand = "Interactive Command"; } }
// 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 namespace Microsoft.CodeAnalysis.Interactive { internal class InteractiveLanguageNames { public const string InteractiveCommand = "Interactive Command"; } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/MSBuildTest/TestFiles/Resources.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.IO; using System.Reflection; namespace Microsoft.CodeAnalysis.UnitTests.TestFiles { public static class Resources { private static Stream GetResourceStream(string name) { var resourceName = $"Microsoft.CodeAnalysis.MSBuild.UnitTests.Resources.{name}"; var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); if (resourceStream != null) { return resourceStream; } throw new InvalidOperationException($"Cannot find resource named: '{resourceName}'"); } private static byte[] LoadBytes(string name) { using (var resourceStream = GetResourceStream(name)) { var bytes = new byte[resourceStream.Length]; resourceStream.Read(bytes, 0, (int)resourceStream.Length); return bytes; } } private static string LoadText(string name) { using (var streamReader = new StreamReader(GetResourceStream(name))) { return streamReader.ReadToEnd(); } } private static readonly Func<string, byte[]> s_bytesLoader = LoadBytes; private static readonly Func<string, string> s_textLoader = LoadText; private static Dictionary<string, byte[]> s_bytesCache; private static Dictionary<string, string> s_textCache; private static TResult GetOrLoadValue<TResult>(string name, Func<string, TResult> loader, ref Dictionary<string, TResult> cache) { if (cache != null && cache.TryGetValue(name, out var result)) { return result; } result = loader(name); if (cache == null) { cache = new Dictionary<string, TResult>(); } cache[name] = result; return result; } public static byte[] GetBytes(string name) => GetOrLoadValue(name, s_bytesLoader, ref s_bytesCache); public static string GetText(string name) => GetOrLoadValue(name, s_textLoader, ref s_textCache); public static string Directory_Build_props => GetText("Directory.Build.props"); public static string Directory_Build_targets => GetText("Directory.Build.targets"); public static byte[] Key_snk => GetBytes("key.snk"); public static string NuGet_Config => GetText("NuGet.Config"); public static class SolutionFilters { public static string Invalid => GetText("SolutionFilters.InvalidSolutionFilter.slnf"); public static string CSharp => GetText("SolutionFilters.CSharpSolutionFilter.slnf"); } public static class SolutionFiles { public static string AnalyzerReference => GetText("SolutionFiles.AnalyzerReference.sln"); public static string CircularSolution => GetText("CircularProjectReferences.CircularSolution.sln"); public static string CSharp => GetText("SolutionFiles.CSharp.sln"); public static string CSharp_EmptyLines => GetText("SolutionFiles.CSharp_EmptyLines.sln"); public static string CSharp_ProjectReference => GetText("SolutionFiles.CSharp_ProjectReference.sln"); public static string CSharp_UnknownProjectExtension => GetText("SolutionFiles.CSharp_UnknownProjectExtension.sln"); public static string CSharp_UnknownProjectTypeGuid => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuid.sln"); public static string CSharp_UnknownProjectTypeGuidAndUnknownExtension => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension.sln"); public static string DuplicatedGuids => GetText("SolutionFiles.DuplicatedGuids.sln"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeSelfReferential.sln"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeCircularReferential.sln"); public static string EmptyLineBetweenProjectBlock => GetText("SolutionFiles.EmptyLineBetweenProjectBlock.sln"); public static string Issue29122_Solution => GetText("Issue29122.TestVB2.sln"); public static string Issue30174_Solution => GetText("Issue30174.Solution.sln"); public static string InvalidProjectPath => GetText("SolutionFiles.InvalidProjectPath.sln"); public static string MissingEndProject1 => GetText("SolutionFiles.MissingEndProject1.sln"); public static string MissingEndProject2 => GetText("SolutionFiles.MissingEndProject2.sln"); public static string MissingEndProject3 => GetText("SolutionFiles.MissingEndProject3.sln"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.Solution.sln"); public static string NonExistentProject => GetText("SolutionFiles.NonExistentProject.sln"); public static string ProjectLoadErrorOnMissingDebugType => GetText("SolutionFiles.ProjectLoadErrorOnMissingDebugType.sln"); public static string SolutionFolder => GetText("SolutionFiles.SolutionFolder.sln"); public static string VB_and_CSharp => GetText("SolutionFiles.VB_and_CSharp.sln"); } public static class ProjectFiles { public static class CSharp { public static string AnalyzerReference => GetText("ProjectFiles.CSharp.AnalyzerReference.csproj"); public static string AllOptions => GetText("ProjectFiles.CSharp.AllOptions.csproj"); public static string AssemblyNameIsPath => GetText("ProjectFiles.CSharp.AssemblyNameIsPath.csproj"); public static string AssemblyNameIsPath2 => GetText("ProjectFiles.CSharp.AssemblyNameIsPath2.csproj"); public static string BadHintPath => GetText("ProjectFiles.CSharp.BadHintPath.csproj"); public static string BadLink => GetText("ProjectFiles.CSharp.BadLink.csproj"); public static string BadElement => GetText("ProjectFiles.CSharp.BadElement.csproj"); public static string BadTasks => GetText("ProjectFiles.CSharp.BadTasks.csproj"); public static string CircularProjectReferences_CircularCSharpProject1 => GetText("CircularProjectReferences.CircularCSharpProject1.csproj"); public static string CircularProjectReferences_CircularCSharpProject2 => GetText("CircularProjectReferences.CircularCSharpProject2.csproj"); public static string CSharpProject => GetText("ProjectFiles.CSharp.CSharpProject.csproj"); public static string AdditionalFile => GetText("ProjectFiles.CSharp.AdditionalFile.csproj"); public static string DuplicateFile => GetText("ProjectFiles.CSharp.DuplicateFile.csproj"); public static string DuplicateReferences => GetText("ProjectFiles.CSharp.DuplicateReferences.csproj"); public static string DuplicatedGuidLibrary1 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary1.csproj"); public static string DuplicatedGuidLibrary2 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary2.csproj"); public static string DuplicatedGuidLibrary3 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary3.csproj"); public static string DuplicatedGuidLibrary4 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary4.csproj"); public static string DuplicatedGuidReferenceTest => GetText("ProjectFiles.CSharp.DuplicatedGuidReferenceTest.csproj"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential.csproj"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential.csproj"); public static string Encoding => GetText("ProjectFiles.CSharp.Encoding.csproj"); public static string ExternAlias => GetText("ProjectFiles.CSharp.ExternAlias.csproj"); public static string ExternAlias2 => GetText("ProjectFiles.CSharp.ExternAlias2.csproj"); public static string ForEmittedOutput => GetText("ProjectFiles.CSharp.ForEmittedOutput.csproj"); public static string Issue30174_InspectedLibrary => GetText("Issue30174.InspectedLibrary.InspectedLibrary.csproj"); public static string Issue30174_ReferencedLibrary => GetText("Issue30174.ReferencedLibrary.ReferencedLibrary.csproj"); public static string MsbuildError => GetText("ProjectFiles.CSharp.MsbuildError.csproj"); public static string MallformedAdditionalFilePath => GetText("ProjectFiles.CSharp.MallformedAdditionalFilePath.csproj"); public static string NetCoreApp2_Project => GetText("NetCoreApp2.Project.csproj"); public static string NetCoreApp2AndLibrary_Project => GetText("NetCoreApp2AndLibrary.Project.csproj"); public static string NetCoreApp2AndLibrary_Library => GetText("NetCoreApp2AndLibrary.Library.csproj"); public static string NetCoreApp2AndTwoLibraries_Project => GetText("NetCoreApp2AndTwoLibraries.Project.csproj"); public static string NetCoreApp2AndTwoLibraries_Library1 => GetText("NetCoreApp2AndTwoLibraries.Library1.csproj"); public static string NetCoreApp2AndTwoLibraries_Library2 => GetText("NetCoreApp2AndTwoLibraries.Library2.csproj"); public static string NetCoreMultiTFM_Project => GetText("NetCoreMultiTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_Project => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_ProjectTestProps => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj.test.props"); public static string NetCoreMultiTFM_ProjectReference_Library => GetText("NetCoreMultiTFM_ProjectReference.Library.csproj"); public static string NetCoreMultiTFM_ProjectReference_Project => GetText("NetCoreMultiTFM_ProjectReference.Project.csproj"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.csharplib.csproj"); public static string PortableProject => GetText("ProjectFiles.CSharp.PortableProject.csproj"); public static string ProjectLoadErrorOnMissingDebugType => GetText("ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType.csproj"); public static string ProjectReference => GetText("ProjectFiles.CSharp.ProjectReference.csproj"); public static string ReferencesPortableProject => GetText("ProjectFiles.CSharp.ReferencesPortableProject.csproj"); public static string ShouldUnsetParentConfigurationAndPlatform => GetText("ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform.csproj"); public static string Wildcards => GetText("ProjectFiles.CSharp.Wildcards.csproj"); public static string WithoutCSharpTargetsImported => GetText("ProjectFiles.CSharp.WithoutCSharpTargetsImported.csproj"); public static string WithDiscoverEditorConfigFiles => GetText("ProjectFiles.CSharp.WithDiscoverEditorConfigFiles.csproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.CSharp.WithPrefer32Bit.csproj"); public static string WithLink => GetText("ProjectFiles.CSharp.WithLink.csproj"); public static string WithSystemNumerics => GetText("ProjectFiles.CSharp.WithSystemNumerics.csproj"); public static string WithXaml => GetText("ProjectFiles.CSharp.WithXaml.csproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.CSharp.WithoutPrefer32Bit.csproj"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.fsharplib.fsproj"); } public static class VisualBasic { public static string AnalyzerReference => GetText("ProjectFiles.VisualBasic.AnalyzerReference.vbproj"); public static string Circular_Target => GetText("ProjectFiles.VisualBasic.Circular_Target.vbproj"); public static string Circular_Top => GetText("ProjectFiles.VisualBasic.Circular_Top.vbproj"); public static string Embed => GetText("ProjectFiles.VisualBasic.Embed.vbproj"); public static string Issue29122_ClassLibrary1 => GetText("Issue29122.Proj1.ClassLibrary1.vbproj"); public static string Issue29122_ClassLibrary2 => GetText("Issue29122.Proj2.ClassLibrary2.vbproj"); public static string InvalidProjectReference => GetText("ProjectFiles.VisualBasic.InvalidProjectReference.vbproj"); public static string NonExistentProjectReference => GetText("ProjectFiles.VisualBasic.NonExistentProjectReference.vbproj"); public static string UnknownProjectExtension => GetText("ProjectFiles.VisualBasic.UnknownProjectExtension.vbproj"); public static string VisualBasicProject => GetText("ProjectFiles.VisualBasic.VisualBasicProject.vbproj"); public static string VisualBasicProject_3_5 => GetText("ProjectFiles.VisualBasic.VisualBasicProject_3_5.vbproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithPrefer32Bit.vbproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithoutPrefer32Bit.vbproj"); public static string WithoutVBTargetsImported => GetText("ProjectFiles.VisualBasic.WithoutVBTargetsImported.vbproj"); } } public static class SourceFiles { public static class CSharp { public static string App => GetText("SourceFiles.CSharp.App.xaml.cs"); public static string AssemblyInfo => GetText("SourceFiles.CSharp.AssemblyInfo.cs"); public static string CSharpClass => GetText("SourceFiles.CSharp.CSharpClass.cs"); public static string CSharpClass_WithConditionalAttributes => GetText("SourceFiles.CSharp.CSharpClass_WithConditionalAttributes.cs"); public static string CSharpConsole => GetText("SourceFiles.CSharp.CSharpConsole.cs"); public static string CSharpExternAlias => GetText("SourceFiles.CSharp.CSharpExternAlias.cs"); public static string Issue30174_InspectedClass => GetText("Issue30174.InspectedLibrary.InspectedClass.cs"); public static string Issue30174_SomeMetadataAttribute => GetText("Issue30174.ReferencedLibrary.SomeMetadataAttribute.cs"); public static string NetCoreApp2_Program => GetText("NetCoreApp2.Program.cs"); public static string NetCoreApp2AndLibrary_Class1 => GetText("NetCoreApp2AndLibrary.Class1.cs"); public static string NetCoreApp2AndLibrary_Program => GetText("NetCoreApp2AndLibrary.Program.cs"); public static string NetCoreApp2AndTwoLibraries_Class1 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Class2 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Program => GetText("NetCoreApp2AndTwoLibraries.Program.cs"); public static string NetCoreMultiTFM_Program => GetText("NetCoreMultiTFM.Program.cs"); public static string NetCoreMultiTFM_ProjectReference_Class1 => GetText("NetCoreMultiTFM_ProjectReference.Class1.cs"); public static string NetCoreMultiTFM_ProjectReference_Program => GetText("NetCoreMultiTFM_ProjectReference.Program.cs"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib_Class1 = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.Class1.cs"); public static string MainWindow => GetText("SourceFiles.CSharp.MainWindow.xaml.cs"); public static string OtherStuff_Foo => GetText("SourceFiles.CSharp.OtherStuff_Foo.cs"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib_Library = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.Library.fs"); } public static class Text { public static string ValidAdditionalFile => GetText("SourceFiles.Text.ValidAdditionalFile.txt"); } public static class VisualBasic { public static string Application => GetText("SourceFiles.VisualBasic.Application.myapp"); public static string Application_Designer => GetText("SourceFiles.VisualBasic.Application.Designer.vb"); public static string AssemblyInfo => GetText("SourceFiles.VisualBasic.AssemblyInfo.vb"); public static string Resources => GetText("SourceFiles.VisualBasic.Resources.resx_"); public static string Resources_Designer => GetText("SourceFiles.VisualBasic.Resources.Designer.vb"); public static string Settings => GetText("SourceFiles.VisualBasic.Settings.settings"); public static string Settings_Designer => GetText("SourceFiles.VisualBasic.Settings.Designer.vb"); public static string VisualBasicClass => GetText("SourceFiles.VisualBasic.VisualBasicClass.vb"); public static string VisualBasicClass_WithConditionalAttributes => GetText("SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes.vb"); } public static class Xaml { public static string App => GetText("SourceFiles.Xaml.App.xaml"); public static string MainWindow => GetText("SourceFiles.Xaml.MainWindow.xaml"); } } public static class Dlls { public static byte[] CSharpProject => GetBytes("Dlls.CSharpProject.dll"); public static byte[] EmptyLibrary => GetBytes("Dlls.EmptyLibrary.dll"); } } }
// 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.IO; using System.Reflection; namespace Microsoft.CodeAnalysis.UnitTests.TestFiles { public static class Resources { private static Stream GetResourceStream(string name) { var resourceName = $"Microsoft.CodeAnalysis.MSBuild.UnitTests.Resources.{name}"; var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); if (resourceStream != null) { return resourceStream; } throw new InvalidOperationException($"Cannot find resource named: '{resourceName}'"); } private static byte[] LoadBytes(string name) { using (var resourceStream = GetResourceStream(name)) { var bytes = new byte[resourceStream.Length]; resourceStream.Read(bytes, 0, (int)resourceStream.Length); return bytes; } } private static string LoadText(string name) { using (var streamReader = new StreamReader(GetResourceStream(name))) { return streamReader.ReadToEnd(); } } private static readonly Func<string, byte[]> s_bytesLoader = LoadBytes; private static readonly Func<string, string> s_textLoader = LoadText; private static Dictionary<string, byte[]> s_bytesCache; private static Dictionary<string, string> s_textCache; private static TResult GetOrLoadValue<TResult>(string name, Func<string, TResult> loader, ref Dictionary<string, TResult> cache) { if (cache != null && cache.TryGetValue(name, out var result)) { return result; } result = loader(name); if (cache == null) { cache = new Dictionary<string, TResult>(); } cache[name] = result; return result; } public static byte[] GetBytes(string name) => GetOrLoadValue(name, s_bytesLoader, ref s_bytesCache); public static string GetText(string name) => GetOrLoadValue(name, s_textLoader, ref s_textCache); public static string Directory_Build_props => GetText("Directory.Build.props"); public static string Directory_Build_targets => GetText("Directory.Build.targets"); public static byte[] Key_snk => GetBytes("key.snk"); public static string NuGet_Config => GetText("NuGet.Config"); public static class SolutionFilters { public static string Invalid => GetText("SolutionFilters.InvalidSolutionFilter.slnf"); public static string CSharp => GetText("SolutionFilters.CSharpSolutionFilter.slnf"); } public static class SolutionFiles { public static string AnalyzerReference => GetText("SolutionFiles.AnalyzerReference.sln"); public static string CircularSolution => GetText("CircularProjectReferences.CircularSolution.sln"); public static string CSharp => GetText("SolutionFiles.CSharp.sln"); public static string CSharp_EmptyLines => GetText("SolutionFiles.CSharp_EmptyLines.sln"); public static string CSharp_ProjectReference => GetText("SolutionFiles.CSharp_ProjectReference.sln"); public static string CSharp_UnknownProjectExtension => GetText("SolutionFiles.CSharp_UnknownProjectExtension.sln"); public static string CSharp_UnknownProjectTypeGuid => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuid.sln"); public static string CSharp_UnknownProjectTypeGuidAndUnknownExtension => GetText("SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension.sln"); public static string DuplicatedGuids => GetText("SolutionFiles.DuplicatedGuids.sln"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeSelfReferential.sln"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("SolutionFiles.DuplicatedGuidsBecomeCircularReferential.sln"); public static string EmptyLineBetweenProjectBlock => GetText("SolutionFiles.EmptyLineBetweenProjectBlock.sln"); public static string Issue29122_Solution => GetText("Issue29122.TestVB2.sln"); public static string Issue30174_Solution => GetText("Issue30174.Solution.sln"); public static string InvalidProjectPath => GetText("SolutionFiles.InvalidProjectPath.sln"); public static string MissingEndProject1 => GetText("SolutionFiles.MissingEndProject1.sln"); public static string MissingEndProject2 => GetText("SolutionFiles.MissingEndProject2.sln"); public static string MissingEndProject3 => GetText("SolutionFiles.MissingEndProject3.sln"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.Solution.sln"); public static string NonExistentProject => GetText("SolutionFiles.NonExistentProject.sln"); public static string ProjectLoadErrorOnMissingDebugType => GetText("SolutionFiles.ProjectLoadErrorOnMissingDebugType.sln"); public static string SolutionFolder => GetText("SolutionFiles.SolutionFolder.sln"); public static string VB_and_CSharp => GetText("SolutionFiles.VB_and_CSharp.sln"); } public static class ProjectFiles { public static class CSharp { public static string AnalyzerReference => GetText("ProjectFiles.CSharp.AnalyzerReference.csproj"); public static string AllOptions => GetText("ProjectFiles.CSharp.AllOptions.csproj"); public static string AssemblyNameIsPath => GetText("ProjectFiles.CSharp.AssemblyNameIsPath.csproj"); public static string AssemblyNameIsPath2 => GetText("ProjectFiles.CSharp.AssemblyNameIsPath2.csproj"); public static string BadHintPath => GetText("ProjectFiles.CSharp.BadHintPath.csproj"); public static string BadLink => GetText("ProjectFiles.CSharp.BadLink.csproj"); public static string BadElement => GetText("ProjectFiles.CSharp.BadElement.csproj"); public static string BadTasks => GetText("ProjectFiles.CSharp.BadTasks.csproj"); public static string CircularProjectReferences_CircularCSharpProject1 => GetText("CircularProjectReferences.CircularCSharpProject1.csproj"); public static string CircularProjectReferences_CircularCSharpProject2 => GetText("CircularProjectReferences.CircularCSharpProject2.csproj"); public static string CSharpProject => GetText("ProjectFiles.CSharp.CSharpProject.csproj"); public static string AdditionalFile => GetText("ProjectFiles.CSharp.AdditionalFile.csproj"); public static string DuplicateFile => GetText("ProjectFiles.CSharp.DuplicateFile.csproj"); public static string DuplicateReferences => GetText("ProjectFiles.CSharp.DuplicateReferences.csproj"); public static string DuplicatedGuidLibrary1 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary1.csproj"); public static string DuplicatedGuidLibrary2 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary2.csproj"); public static string DuplicatedGuidLibrary3 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary3.csproj"); public static string DuplicatedGuidLibrary4 => GetText("ProjectFiles.CSharp.DuplicatedGuidLibrary4.csproj"); public static string DuplicatedGuidReferenceTest => GetText("ProjectFiles.CSharp.DuplicatedGuidReferenceTest.csproj"); public static string DuplicatedGuidsBecomeSelfReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential.csproj"); public static string DuplicatedGuidsBecomeCircularReferential => GetText("ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential.csproj"); public static string Encoding => GetText("ProjectFiles.CSharp.Encoding.csproj"); public static string ExternAlias => GetText("ProjectFiles.CSharp.ExternAlias.csproj"); public static string ExternAlias2 => GetText("ProjectFiles.CSharp.ExternAlias2.csproj"); public static string ForEmittedOutput => GetText("ProjectFiles.CSharp.ForEmittedOutput.csproj"); public static string Issue30174_InspectedLibrary => GetText("Issue30174.InspectedLibrary.InspectedLibrary.csproj"); public static string Issue30174_ReferencedLibrary => GetText("Issue30174.ReferencedLibrary.ReferencedLibrary.csproj"); public static string MsbuildError => GetText("ProjectFiles.CSharp.MsbuildError.csproj"); public static string MallformedAdditionalFilePath => GetText("ProjectFiles.CSharp.MallformedAdditionalFilePath.csproj"); public static string NetCoreApp2_Project => GetText("NetCoreApp2.Project.csproj"); public static string NetCoreApp2AndLibrary_Project => GetText("NetCoreApp2AndLibrary.Project.csproj"); public static string NetCoreApp2AndLibrary_Library => GetText("NetCoreApp2AndLibrary.Library.csproj"); public static string NetCoreApp2AndTwoLibraries_Project => GetText("NetCoreApp2AndTwoLibraries.Project.csproj"); public static string NetCoreApp2AndTwoLibraries_Library1 => GetText("NetCoreApp2AndTwoLibraries.Library1.csproj"); public static string NetCoreApp2AndTwoLibraries_Library2 => GetText("NetCoreApp2AndTwoLibraries.Library2.csproj"); public static string NetCoreMultiTFM_Project => GetText("NetCoreMultiTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_Project => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj"); public static string NetCoreMultiTFM_ExtensionWithConditionOnTFM_ProjectTestProps => GetText("NetCoreMultiTFM_ExtensionWithConditionOnTFM.Project.csproj.test.props"); public static string NetCoreMultiTFM_ProjectReference_Library => GetText("NetCoreMultiTFM_ProjectReference.Library.csproj"); public static string NetCoreMultiTFM_ProjectReference_Project => GetText("NetCoreMultiTFM_ProjectReference.Project.csproj"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.csharplib.csproj"); public static string PortableProject => GetText("ProjectFiles.CSharp.PortableProject.csproj"); public static string ProjectLoadErrorOnMissingDebugType => GetText("ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType.csproj"); public static string ProjectReference => GetText("ProjectFiles.CSharp.ProjectReference.csproj"); public static string ReferencesPortableProject => GetText("ProjectFiles.CSharp.ReferencesPortableProject.csproj"); public static string ShouldUnsetParentConfigurationAndPlatform => GetText("ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform.csproj"); public static string Wildcards => GetText("ProjectFiles.CSharp.Wildcards.csproj"); public static string WithoutCSharpTargetsImported => GetText("ProjectFiles.CSharp.WithoutCSharpTargetsImported.csproj"); public static string WithDiscoverEditorConfigFiles => GetText("ProjectFiles.CSharp.WithDiscoverEditorConfigFiles.csproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.CSharp.WithPrefer32Bit.csproj"); public static string WithLink => GetText("ProjectFiles.CSharp.WithLink.csproj"); public static string WithSystemNumerics => GetText("ProjectFiles.CSharp.WithSystemNumerics.csproj"); public static string WithXaml => GetText("ProjectFiles.CSharp.WithXaml.csproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.CSharp.WithoutPrefer32Bit.csproj"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.fsharplib.fsproj"); } public static class VisualBasic { public static string AnalyzerReference => GetText("ProjectFiles.VisualBasic.AnalyzerReference.vbproj"); public static string Circular_Target => GetText("ProjectFiles.VisualBasic.Circular_Target.vbproj"); public static string Circular_Top => GetText("ProjectFiles.VisualBasic.Circular_Top.vbproj"); public static string Embed => GetText("ProjectFiles.VisualBasic.Embed.vbproj"); public static string Issue29122_ClassLibrary1 => GetText("Issue29122.Proj1.ClassLibrary1.vbproj"); public static string Issue29122_ClassLibrary2 => GetText("Issue29122.Proj2.ClassLibrary2.vbproj"); public static string InvalidProjectReference => GetText("ProjectFiles.VisualBasic.InvalidProjectReference.vbproj"); public static string NonExistentProjectReference => GetText("ProjectFiles.VisualBasic.NonExistentProjectReference.vbproj"); public static string UnknownProjectExtension => GetText("ProjectFiles.VisualBasic.UnknownProjectExtension.vbproj"); public static string VisualBasicProject => GetText("ProjectFiles.VisualBasic.VisualBasicProject.vbproj"); public static string VisualBasicProject_3_5 => GetText("ProjectFiles.VisualBasic.VisualBasicProject_3_5.vbproj"); public static string WithPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithPrefer32Bit.vbproj"); public static string WithoutPrefer32Bit => GetText("ProjectFiles.VisualBasic.WithoutPrefer32Bit.vbproj"); public static string WithoutVBTargetsImported => GetText("ProjectFiles.VisualBasic.WithoutVBTargetsImported.vbproj"); } } public static class SourceFiles { public static class CSharp { public static string App => GetText("SourceFiles.CSharp.App.xaml.cs"); public static string AssemblyInfo => GetText("SourceFiles.CSharp.AssemblyInfo.cs"); public static string CSharpClass => GetText("SourceFiles.CSharp.CSharpClass.cs"); public static string CSharpClass_WithConditionalAttributes => GetText("SourceFiles.CSharp.CSharpClass_WithConditionalAttributes.cs"); public static string CSharpConsole => GetText("SourceFiles.CSharp.CSharpConsole.cs"); public static string CSharpExternAlias => GetText("SourceFiles.CSharp.CSharpExternAlias.cs"); public static string Issue30174_InspectedClass => GetText("Issue30174.InspectedLibrary.InspectedClass.cs"); public static string Issue30174_SomeMetadataAttribute => GetText("Issue30174.ReferencedLibrary.SomeMetadataAttribute.cs"); public static string NetCoreApp2_Program => GetText("NetCoreApp2.Program.cs"); public static string NetCoreApp2AndLibrary_Class1 => GetText("NetCoreApp2AndLibrary.Class1.cs"); public static string NetCoreApp2AndLibrary_Program => GetText("NetCoreApp2AndLibrary.Program.cs"); public static string NetCoreApp2AndTwoLibraries_Class1 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Class2 => GetText("NetCoreApp2AndTwoLibraries.Class1.cs"); public static string NetCoreApp2AndTwoLibraries_Program => GetText("NetCoreApp2AndTwoLibraries.Program.cs"); public static string NetCoreMultiTFM_Program => GetText("NetCoreMultiTFM.Program.cs"); public static string NetCoreMultiTFM_ProjectReference_Class1 => GetText("NetCoreMultiTFM_ProjectReference.Class1.cs"); public static string NetCoreMultiTFM_ProjectReference_Program => GetText("NetCoreMultiTFM_ProjectReference.Program.cs"); public static string NetCoreMultiTFM_ProjectReferenceToFSharp_CSharpLib_Class1 = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.csharplib.Class1.cs"); public static string MainWindow => GetText("SourceFiles.CSharp.MainWindow.xaml.cs"); public static string OtherStuff_Foo => GetText("SourceFiles.CSharp.OtherStuff_Foo.cs"); } public static class FSharp { public static string NetCoreMultiTFM_ProjectReferenceToFSharp_FSharpLib_Library = GetText("NetCoreMultiTFM_ProjectReferenceToFSharp.fsharplib.Library.fs"); } public static class Text { public static string ValidAdditionalFile => GetText("SourceFiles.Text.ValidAdditionalFile.txt"); } public static class VisualBasic { public static string Application => GetText("SourceFiles.VisualBasic.Application.myapp"); public static string Application_Designer => GetText("SourceFiles.VisualBasic.Application.Designer.vb"); public static string AssemblyInfo => GetText("SourceFiles.VisualBasic.AssemblyInfo.vb"); public static string Resources => GetText("SourceFiles.VisualBasic.Resources.resx_"); public static string Resources_Designer => GetText("SourceFiles.VisualBasic.Resources.Designer.vb"); public static string Settings => GetText("SourceFiles.VisualBasic.Settings.settings"); public static string Settings_Designer => GetText("SourceFiles.VisualBasic.Settings.Designer.vb"); public static string VisualBasicClass => GetText("SourceFiles.VisualBasic.VisualBasicClass.vb"); public static string VisualBasicClass_WithConditionalAttributes => GetText("SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes.vb"); } public static class Xaml { public static string App => GetText("SourceFiles.Xaml.App.xaml"); public static string MainWindow => GetText("SourceFiles.Xaml.MainWindow.xaml"); } } public static class Dlls { public static byte[] CSharpProject => GetBytes("Dlls.CSharpProject.dll"); public static byte[] EmptyLibrary => GetBytes("Dlls.EmptyLibrary.dll"); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/CSharp/Portable/Editing/CSharpImportAdder.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.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Editing { [ExportLanguageService(typeof(ImportAdderService), LanguageNames.CSharp), Shared] internal class CSharpImportAdder : ImportAdderService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpImportAdder() { } protected override INamespaceSymbol? GetExplicitNamespaceSymbol(SyntaxNode node, SemanticModel model) { switch (node) { case QualifiedNameSyntax name: return GetExplicitNamespaceSymbol(name, name.Left, model); case MemberAccessExpressionSyntax memberAccess: return GetExplicitNamespaceSymbol(memberAccess, memberAccess.Expression, model); } return null; } protected override void AddPotentiallyConflictingImports( SemanticModel model, SyntaxNode container, ImmutableArray<INamespaceSymbol> namespaceSymbols, HashSet<INamespaceSymbol> conflicts, CancellationToken cancellationToken) { var rewriter = new ConflictWalker(model, namespaceSymbols, conflicts, cancellationToken); rewriter.Visit(container); } private static INamespaceSymbol? GetExplicitNamespaceSymbol(ExpressionSyntax fullName, ExpressionSyntax namespacePart, SemanticModel model) { // name must refer to something that is not a namespace, but be qualified with a namespace. var symbol = model.GetSymbolInfo(fullName).Symbol; if (symbol != null && symbol.Kind != SymbolKind.Namespace && model.GetSymbolInfo(namespacePart).Symbol is INamespaceSymbol) { // use the symbols containing namespace, and not the potentially less than fully qualified namespace in the full name expression. var ns = symbol.ContainingNamespace; if (ns != null) { return model.Compilation.GetCompilationNamespace(ns); } } return null; } /// <summary> /// Walks the portion of the tree we're adding imports to looking to see if those imports could likely cause /// conflicts with existing code. Note: this is a best-effort basis, and the goal is to catch reasonable /// conflicts effectively. There may be cases that do slip through that we can adjust for in the future. Those /// cases should be assessed to see how reasonable/likely they are. I.e. if it's just a hypothetical case with /// no users being hit, then that's far less important than if we have a reasonable coding pattern that would be /// impacted by adding an import to a normal namespace. /// </summary> private class ConflictWalker : CSharpSyntaxWalker { private readonly SemanticModel _model; private readonly CancellationToken _cancellationToken; /// <summary> /// A mapping containing the simple names and arity of all imported types, mapped to the import that they're /// brought in by. /// </summary> private readonly MultiDictionary<(string name, int arity), INamespaceSymbol> _importedTypes = new(); /// <summary> /// A mapping containing the simple names of all imported extension methods, mapped to the import that /// they're brought in by. This doesn't keep track of arity because methods can be called with type /// arguments. /// </summary> /// <remarks> /// We could consider adding more information here (for example the min/max number of args that this can be /// called with). That could then be used to check if there could be a conflict. However, that's likely /// more complexity than we need currently. But it is always something we can do in the future. /// </remarks> private readonly MultiDictionary<string, INamespaceSymbol> _importedExtensionMethods = new(); private readonly HashSet<INamespaceSymbol> _conflictNamespaces; /// <summary> /// Track if we're in an anonymous method or not. If so, because of how the language binds lambdas and /// overloads, we'll assume any method access we see inside (instance or otherwise) could end up conflicting /// with an extension method we might pull in. /// </summary> private bool _inAnonymousMethod; public ConflictWalker( SemanticModel model, ImmutableArray<INamespaceSymbol> namespaceSymbols, HashSet<INamespaceSymbol> conflictNamespaces, CancellationToken cancellationToken) : base(SyntaxWalkerDepth.StructuredTrivia) { _model = model; _cancellationToken = cancellationToken; _conflictNamespaces = conflictNamespaces; AddImportedMembers(namespaceSymbols); } private void AddImportedMembers(ImmutableArray<INamespaceSymbol> namespaceSymbols) { foreach (var ns in namespaceSymbols) { foreach (var type in ns.GetTypeMembers()) { _importedTypes.Add((type.Name, type.Arity), ns); if (type.MightContainExtensionMethods) { foreach (var member in type.GetMembers()) { if (member is IMethodSymbol method && method.IsExtensionMethod) _importedExtensionMethods.Add(method.Name, ns); } } } } } public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { // lambdas are interesting. Say you have: // // Goo(x => x.M()); // // void Goo(Action<C> act) { } // void Goo(Action<int> act) { } // // class C { public void M() { } } // // This is legal code where the lambda body is calling the instance method. However, if we introduce a // using that brings in an extension method 'M' on 'int', then the above will become ambiguous. This is // because lambda binding will try each interpretation separately and eliminate the ones that fail. // Adding the import will make the int form succeed, causing ambiguity. // // To deal with that, we keep track of if we're in a lambda, and we conservatively assume that a method // access (even to a non-extension method) could conflict with an extension method brought in. var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitSimpleLambdaExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitParenthesizedLambdaExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) { var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitAnonymousMethodExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } private void CheckName(NameSyntax node) { // Check to see if we have an standalone identifier (or identifier on the left of a dot). If so, if that // identifier binds to a type, then we don't want to bring in any imports that would bring in the same // name and could then potentially conflict here. if (node.IsRightSideOfDotOrArrowOrColonColon()) return; var symbol = _model.GetSymbolInfo(node, _cancellationToken).GetAnySymbol(); if (symbol?.Kind == SymbolKind.NamedType) _conflictNamespaces.AddRange(_importedTypes[(symbol.Name, node.Arity)]); } public override void VisitIdentifierName(IdentifierNameSyntax node) { base.VisitIdentifierName(node); CheckName(node); } public override void VisitGenericName(GenericNameSyntax node) { base.VisitGenericName(node); CheckName(node); } public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { base.VisitMemberAccessExpression(node); // Check to see if we have a reference to an extension method. If so, then pulling in an import could // bring in an extension that conflicts with that. var symbol = _model.GetSymbolInfo(node.Name, _cancellationToken).GetAnySymbol(); if (symbol is IMethodSymbol method) { // see explanation in VisitSimpleLambdaExpression for the _inAnonymousMethod check if (method.IsReducedExtension() || _inAnonymousMethod) _conflictNamespaces.AddRange(_importedExtensionMethods[method.Name]); } } } } }
// 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.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Editing { [ExportLanguageService(typeof(ImportAdderService), LanguageNames.CSharp), Shared] internal class CSharpImportAdder : ImportAdderService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpImportAdder() { } protected override INamespaceSymbol? GetExplicitNamespaceSymbol(SyntaxNode node, SemanticModel model) { switch (node) { case QualifiedNameSyntax name: return GetExplicitNamespaceSymbol(name, name.Left, model); case MemberAccessExpressionSyntax memberAccess: return GetExplicitNamespaceSymbol(memberAccess, memberAccess.Expression, model); } return null; } protected override void AddPotentiallyConflictingImports( SemanticModel model, SyntaxNode container, ImmutableArray<INamespaceSymbol> namespaceSymbols, HashSet<INamespaceSymbol> conflicts, CancellationToken cancellationToken) { var rewriter = new ConflictWalker(model, namespaceSymbols, conflicts, cancellationToken); rewriter.Visit(container); } private static INamespaceSymbol? GetExplicitNamespaceSymbol(ExpressionSyntax fullName, ExpressionSyntax namespacePart, SemanticModel model) { // name must refer to something that is not a namespace, but be qualified with a namespace. var symbol = model.GetSymbolInfo(fullName).Symbol; if (symbol != null && symbol.Kind != SymbolKind.Namespace && model.GetSymbolInfo(namespacePart).Symbol is INamespaceSymbol) { // use the symbols containing namespace, and not the potentially less than fully qualified namespace in the full name expression. var ns = symbol.ContainingNamespace; if (ns != null) { return model.Compilation.GetCompilationNamespace(ns); } } return null; } /// <summary> /// Walks the portion of the tree we're adding imports to looking to see if those imports could likely cause /// conflicts with existing code. Note: this is a best-effort basis, and the goal is to catch reasonable /// conflicts effectively. There may be cases that do slip through that we can adjust for in the future. Those /// cases should be assessed to see how reasonable/likely they are. I.e. if it's just a hypothetical case with /// no users being hit, then that's far less important than if we have a reasonable coding pattern that would be /// impacted by adding an import to a normal namespace. /// </summary> private class ConflictWalker : CSharpSyntaxWalker { private readonly SemanticModel _model; private readonly CancellationToken _cancellationToken; /// <summary> /// A mapping containing the simple names and arity of all imported types, mapped to the import that they're /// brought in by. /// </summary> private readonly MultiDictionary<(string name, int arity), INamespaceSymbol> _importedTypes = new(); /// <summary> /// A mapping containing the simple names of all imported extension methods, mapped to the import that /// they're brought in by. This doesn't keep track of arity because methods can be called with type /// arguments. /// </summary> /// <remarks> /// We could consider adding more information here (for example the min/max number of args that this can be /// called with). That could then be used to check if there could be a conflict. However, that's likely /// more complexity than we need currently. But it is always something we can do in the future. /// </remarks> private readonly MultiDictionary<string, INamespaceSymbol> _importedExtensionMethods = new(); private readonly HashSet<INamespaceSymbol> _conflictNamespaces; /// <summary> /// Track if we're in an anonymous method or not. If so, because of how the language binds lambdas and /// overloads, we'll assume any method access we see inside (instance or otherwise) could end up conflicting /// with an extension method we might pull in. /// </summary> private bool _inAnonymousMethod; public ConflictWalker( SemanticModel model, ImmutableArray<INamespaceSymbol> namespaceSymbols, HashSet<INamespaceSymbol> conflictNamespaces, CancellationToken cancellationToken) : base(SyntaxWalkerDepth.StructuredTrivia) { _model = model; _cancellationToken = cancellationToken; _conflictNamespaces = conflictNamespaces; AddImportedMembers(namespaceSymbols); } private void AddImportedMembers(ImmutableArray<INamespaceSymbol> namespaceSymbols) { foreach (var ns in namespaceSymbols) { foreach (var type in ns.GetTypeMembers()) { _importedTypes.Add((type.Name, type.Arity), ns); if (type.MightContainExtensionMethods) { foreach (var member in type.GetMembers()) { if (member is IMethodSymbol method && method.IsExtensionMethod) _importedExtensionMethods.Add(method.Name, ns); } } } } } public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { // lambdas are interesting. Say you have: // // Goo(x => x.M()); // // void Goo(Action<C> act) { } // void Goo(Action<int> act) { } // // class C { public void M() { } } // // This is legal code where the lambda body is calling the instance method. However, if we introduce a // using that brings in an extension method 'M' on 'int', then the above will become ambiguous. This is // because lambda binding will try each interpretation separately and eliminate the ones that fail. // Adding the import will make the int form succeed, causing ambiguity. // // To deal with that, we keep track of if we're in a lambda, and we conservatively assume that a method // access (even to a non-extension method) could conflict with an extension method brought in. var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitSimpleLambdaExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitParenthesizedLambdaExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) { var previousInAnonymousMethod = _inAnonymousMethod; _inAnonymousMethod = true; base.VisitAnonymousMethodExpression(node); _inAnonymousMethod = previousInAnonymousMethod; } private void CheckName(NameSyntax node) { // Check to see if we have an standalone identifier (or identifier on the left of a dot). If so, if that // identifier binds to a type, then we don't want to bring in any imports that would bring in the same // name and could then potentially conflict here. if (node.IsRightSideOfDotOrArrowOrColonColon()) return; var symbol = _model.GetSymbolInfo(node, _cancellationToken).GetAnySymbol(); if (symbol?.Kind == SymbolKind.NamedType) _conflictNamespaces.AddRange(_importedTypes[(symbol.Name, node.Arity)]); } public override void VisitIdentifierName(IdentifierNameSyntax node) { base.VisitIdentifierName(node); CheckName(node); } public override void VisitGenericName(GenericNameSyntax node) { base.VisitGenericName(node); CheckName(node); } public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { base.VisitMemberAccessExpression(node); // Check to see if we have a reference to an extension method. If so, then pulling in an import could // bring in an extension that conflicts with that. var symbol = _model.GetSymbolInfo(node.Name, _cancellationToken).GetAnySymbol(); if (symbol is IMethodSymbol method) { // see explanation in VisitSimpleLambdaExpression for the _inAnonymousMethod check if (method.IsReducedExtension() || _inAnonymousMethod) _conflictNamespaces.AddRange(_importedExtensionMethods[method.Name]); } } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/StringExtensions.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.CSharp.Syntax; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class StringExtensions { public static string EscapeIdentifier( this string identifier, bool isQueryContext = false) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; // Check if we need to escape this contextual keyword needsEscaping = needsEscaping || (isQueryContext && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(identifier))); return needsEscaping ? "@" + identifier : identifier; } public static SyntaxToken ToIdentifierToken( this string identifier, bool isQueryContext = false) { var escaped = identifier.EscapeIdentifier(isQueryContext); if (escaped.Length == 0 || escaped[0] != '@') { return SyntaxFactory.Identifier(escaped); } var unescaped = identifier.StartsWith("@", StringComparison.Ordinal) ? identifier.Substring(1) : identifier; var token = SyntaxFactory.Identifier( default, SyntaxKind.None, "@" + unescaped, unescaped, default); if (!identifier.StartsWith("@", StringComparison.Ordinal)) { token = token.WithAdditionalAnnotations(Simplifier.Annotation); } return token; } public static IdentifierNameSyntax ToIdentifierName(this string identifier) => SyntaxFactory.IdentifierName(identifier.ToIdentifierToken()); } }
// 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class StringExtensions { public static string EscapeIdentifier( this string identifier, bool isQueryContext = false) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; // Check if we need to escape this contextual keyword needsEscaping = needsEscaping || (isQueryContext && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(identifier))); return needsEscaping ? "@" + identifier : identifier; } public static SyntaxToken ToIdentifierToken( this string identifier, bool isQueryContext = false) { var escaped = identifier.EscapeIdentifier(isQueryContext); if (escaped.Length == 0 || escaped[0] != '@') { return SyntaxFactory.Identifier(escaped); } var unescaped = identifier.StartsWith("@", StringComparison.Ordinal) ? identifier.Substring(1) : identifier; var token = SyntaxFactory.Identifier( default, SyntaxKind.None, "@" + unescaped, unescaped, default); if (!identifier.StartsWith("@", StringComparison.Ordinal)) { token = token.WithAdditionalAnnotations(Simplifier.Annotation); } return token; } public static IdentifierNameSyntax ToIdentifierName(this string identifier) => SyntaxFactory.IdentifierName(identifier.ToIdentifierToken()); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.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.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_OnMatchingFileName() { var code = @"[||]class test1 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_Nested_OnMatchingFileName_Simple() { var code = @"class outer { [||]class test1 { } }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMatchingFileName_CaseSensitive() { var code = @"[||]class Test1 { }"; await TestActionCountAsync(code, count: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans1() { var code = @"[|clas|]s Class1 { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans2() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")] public async Task TestMoveToNewFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { } class Class2 { } </Document> </Project> </Workspace>"; var codeAfterMove = @"class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B")); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans3() { var code = @"[|class Class1|] { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans4() { var code = @"class Class1[||] { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithNoContainerNamespace() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() { var code = @"// Banner Text using System; [||]class Class1 { } class Class2 { }"; var codeAfterMove = @"// Banner Text using System; class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { }"; var codeAfterMove = @"// Banner Text class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers2() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var codeAfterMove = @"// Banner Text using System; class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnInterface() { var code = @"[||]interface IMoveType { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "IMoveType.cs"; var destinationDocumentText = @"interface IMoveType { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAStruct() { var code = @"[||]struct MyStruct { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyStruct.cs"; var destinationDocumentText = @"struct MyStruct { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnEnum() { var code = @"[||]enum MyEnum { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyEnum.cs"; var destinationDocumentText = @"enum MyEnum { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithContainerNamespace() { var code = @"namespace N1 { [||]class Class1 { } class Class2 { } }"; var codeAfterMove = @"namespace N1 { class Class2 { } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1 { class Class1 { } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithFileScopedNamespace() { var code = @"namespace N1; [||]class Class1 { } class Class2 { } "; var codeAfterMove = @"namespace N1; class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1; class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypePreserveModifiers() { var code = @"namespace N1 { abstract class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { abstract partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { abstract partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")] public async Task MoveNestedTypeToNewFile_Attributes1() { var code = @"namespace N1 { [Outer] class Class1 { [Inner] [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { [Outer] partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { [Inner] class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")] public async Task MoveNestedTypeToNewFile_Comments1() { var code = @"namespace N1 { /// Outer doc comment. class Class1 { /// Inner doc comment [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { /// Outer doc comment. partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { /// Inner doc comment class Class2 { } } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple_DottedName() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class1.Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { private string _field1; public void InnerMethod() { } } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { private string _field1; public void InnerMethod() { } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")] public async Task MoveTypeInFileWithComplexHierarchy() { var code = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { class OuterClass2 { [||]class InnerClass2 { class InnerClass3 { } } class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var codeAfterMove = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var expectedDocumentName = "InnerClass2.cs"; var destinationDocumentText = @"namespace OuterN1.N1 { namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass2 { class InnerClass3 { } } } } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeUsings1() { var code = @" // Only used by inner type. using System; // Unused by both types. using System.Collections; class Outer { [||]class Inner { DateTime d; } }"; var codeAfterMove = @" // Only used by inner type. // Unused by both types. using System.Collections; partial class Outer { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" // Only used by inner type. using System; // Unused by both types. partial class Outer { class Inner { DateTime d; } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingTrivia1() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true))); }); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine2() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false))); }); } [WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeRemoveOuterInheritanceTypes() { var code = @" class Outer : IComparable { [||]class Inner : IWhatever { DateTime d; } }"; var codeAfterMove = @" partial class Outer : IComparable { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" partial class Outer { class Inner : IWhatever { DateTime d; } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives1() { var code = @"using System; namespace N { class Program { static void Main() { } } } #if true public class [||]Inner { } #endif"; var codeAfterMove = @"using System; namespace N { class Program { static void Main() { } } } #if true #endif"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" #if true public class Inner { } #endif"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives2() { var code = @"using System; namespace N { class Program { static void Main() { } #if true public class [||]Inner { } #endif } }"; var codeAfterMove = @"using System; namespace N { partial class Program { static void Main() { } #if true #endif } }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"namespace N { partial class Program { #if true public class Inner { } #endif } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines1() { var code = @"// Banner Text using System; [||]class Class1 { void Foo() { Console.WriteLine(); } } class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines2() { var code = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } [||]class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer() { var code = @"// Banner Text using System; class Class1 // Leading comment { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 // Leading comment { void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { // Leading comment class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { // Leading comment void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveRecordToNewFilePreserveUsings() { var code = @"using System; [||]record CacheContext(String Message); class Program { }"; var codeAfterMove = @"class Program { }"; var expectedDocumentName = "CacheContext.cs"; var destinationDocumentText = @"using System; record CacheContext(String Message); "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveClassInTopLevelStatements() { var code = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); class [||]C { public string Hello => ""Hello""; }"; var codeAfterMove = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); "; var expectedDocumentName = "C.cs"; var destinationDocumentText = @"class C { public string Hello => ""Hello""; }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MissingInTopLevelStatementsOnly() { var code = @" using ConsoleApp1; using System; var c = new object(); [||]Console.WriteLine(c.ToString()); "; await TestMissingAsync(code); } } }
// 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.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_OnMatchingFileName() { var code = @"[||]class test1 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_Nested_OnMatchingFileName_Simple() { var code = @"class outer { [||]class test1 { } }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMatchingFileName_CaseSensitive() { var code = @"[||]class Test1 { }"; await TestActionCountAsync(code, count: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans1() { var code = @"[|clas|]s Class1 { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans2() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")] public async Task TestMoveToNewFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { } class Class2 { } </Document> </Project> </Workspace>"; var codeAfterMove = @"class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B")); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans3() { var code = @"[|class Class1|] { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans4() { var code = @"class Class1[||] { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithNoContainerNamespace() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() { var code = @"// Banner Text using System; [||]class Class1 { } class Class2 { }"; var codeAfterMove = @"// Banner Text using System; class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { }"; var codeAfterMove = @"// Banner Text class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers2() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var codeAfterMove = @"// Banner Text using System; class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnInterface() { var code = @"[||]interface IMoveType { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "IMoveType.cs"; var destinationDocumentText = @"interface IMoveType { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAStruct() { var code = @"[||]struct MyStruct { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyStruct.cs"; var destinationDocumentText = @"struct MyStruct { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnEnum() { var code = @"[||]enum MyEnum { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyEnum.cs"; var destinationDocumentText = @"enum MyEnum { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithContainerNamespace() { var code = @"namespace N1 { [||]class Class1 { } class Class2 { } }"; var codeAfterMove = @"namespace N1 { class Class2 { } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1 { class Class1 { } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithFileScopedNamespace() { var code = @"namespace N1; [||]class Class1 { } class Class2 { } "; var codeAfterMove = @"namespace N1; class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1; class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypePreserveModifiers() { var code = @"namespace N1 { abstract class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { abstract partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { abstract partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")] public async Task MoveNestedTypeToNewFile_Attributes1() { var code = @"namespace N1 { [Outer] class Class1 { [Inner] [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { [Outer] partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { [Inner] class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")] public async Task MoveNestedTypeToNewFile_Comments1() { var code = @"namespace N1 { /// Outer doc comment. class Class1 { /// Inner doc comment [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { /// Outer doc comment. partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { /// Inner doc comment class Class2 { } } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple_DottedName() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class1.Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { private string _field1; public void InnerMethod() { } } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { private string _field1; public void InnerMethod() { } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")] public async Task MoveTypeInFileWithComplexHierarchy() { var code = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { class OuterClass2 { [||]class InnerClass2 { class InnerClass3 { } } class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var codeAfterMove = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var expectedDocumentName = "InnerClass2.cs"; var destinationDocumentText = @"namespace OuterN1.N1 { namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass2 { class InnerClass3 { } } } } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeUsings1() { var code = @" // Only used by inner type. using System; // Unused by both types. using System.Collections; class Outer { [||]class Inner { DateTime d; } }"; var codeAfterMove = @" // Only used by inner type. // Unused by both types. using System.Collections; partial class Outer { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" // Only used by inner type. using System; // Unused by both types. partial class Outer { class Inner { DateTime d; } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingTrivia1() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true))); }); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine2() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false))); }); } [WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeRemoveOuterInheritanceTypes() { var code = @" class Outer : IComparable { [||]class Inner : IWhatever { DateTime d; } }"; var codeAfterMove = @" partial class Outer : IComparable { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" partial class Outer { class Inner : IWhatever { DateTime d; } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives1() { var code = @"using System; namespace N { class Program { static void Main() { } } } #if true public class [||]Inner { } #endif"; var codeAfterMove = @"using System; namespace N { class Program { static void Main() { } } } #if true #endif"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" #if true public class Inner { } #endif"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives2() { var code = @"using System; namespace N { class Program { static void Main() { } #if true public class [||]Inner { } #endif } }"; var codeAfterMove = @"using System; namespace N { partial class Program { static void Main() { } #if true #endif } }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"namespace N { partial class Program { #if true public class Inner { } #endif } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines1() { var code = @"// Banner Text using System; [||]class Class1 { void Foo() { Console.WriteLine(); } } class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines2() { var code = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } [||]class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer() { var code = @"// Banner Text using System; class Class1 // Leading comment { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 // Leading comment { void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { // Leading comment class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { // Leading comment void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveRecordToNewFilePreserveUsings() { var code = @"using System; [||]record CacheContext(String Message); class Program { }"; var codeAfterMove = @"class Program { }"; var expectedDocumentName = "CacheContext.cs"; var destinationDocumentText = @"using System; record CacheContext(String Message); "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveClassInTopLevelStatements() { var code = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); class [||]C { public string Hello => ""Hello""; }"; var codeAfterMove = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); "; var expectedDocumentName = "C.cs"; var destinationDocumentText = @"class C { public string Hello => ""Hello""; }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MissingInTopLevelStatementsOnly() { var code = @" using ConsoleApp1; using System; var c = new object(); [||]Console.WriteLine(c.ToString()); "; await TestMissingAsync(code); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VenusMargin/ProjectionSpanTag.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.Tagging; namespace Roslyn.Hosting.Diagnostics.VenusMargin { internal class ProjectionSpanTag : TextMarkerTag { public const string TagId = "ProjectionTag"; public static readonly ProjectionSpanTag Instance = new ProjectionSpanTag(); public ProjectionSpanTag() : base(TagId) { } } }
// 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.Tagging; namespace Roslyn.Hosting.Diagnostics.VenusMargin { internal class ProjectionSpanTag : TextMarkerTag { public const string TagId = "ProjectionTag"; public static readonly ProjectionSpanTag Instance = new ProjectionSpanTag(); public ProjectionSpanTag() : base(TagId) { } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.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.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_AnonymousDelegateInference Inherits BasicTestBase <Fact> Public Sub Test1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x = Function(y) y System.Console.WriteLine(x.GetType()) x = Function(y) y ' No inference here, using delegate type from x. System.Console.WriteLine(x.GetType()) Dim x2 As Object = Function(y) y System.Console.WriteLine(x2.GetType()) Dim x3 = Function() Function() "a" System.Console.WriteLine(x3.GetType()) Dim x4 = Function() Return Function() 2.5 End Function System.Console.WriteLine(x4.GetType()) Dim x5 = DirectCast(Function() Date.Now, System.Delegate) System.Console.WriteLine(x5.GetType()) Dim x6 = TryCast(Function() Decimal.MaxValue, System.MulticastDelegate) System.Console.WriteLine(x6.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x = Function(y) y ~ BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x2 As Object = Function(y) y ~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x = Function(y) y ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x2 As Object = Function(y) y ~ </expected>) End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 = Function() Unknown 'BIND1:"x1" Dim x2 = Function() : 'BIND2:"x2" Dim x3 = Function() 'BIND3:"x3" Return Unknown '3 End Function Dim x4 = Function() 'BIND4:"x4" Unknown() End Function '4 Dim x5 = Function() AddressOf Main 'BIND5:"x5" Dim x6 = Function() 'BIND6:"x6" Return AddressOf Main '6 End Function End Sub Delegate Sub D1(x As System.ArgIterator) Sub Test(y As System.ArgIterator) Dim x7 = Function() y 'BIND7:"x7" Dim x8 = Function() 'BIND8:"x8" Return y '8 End Function Dim x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ' The following Dim shouldn't produce any errors. Dim x10 As D1 = Sub(x As System.ArgIterator) System.Console.WriteLine() Dim x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each strict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Dim x1 = Function() Unknown 'BIND1:"x1" ~~~~~~~ BC30201: Expression expected. Dim x2 = Function() : 'BIND2:"x2" ~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Return Unknown '3 ~~~~~~~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Unknown() ~~~~~~~ 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 '4 ~~~~~~~~~~~~ BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x5 = Function() AddressOf Main 'BIND5:"x5" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x6 = Function() 'BIND6:"x6" ~~~~~~~~~~ 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 x7 = Function() y 'BIND7:"x7" ~~~~~~~~~~ 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 x8 = Function() 'BIND8:"x8" ~~~~~~~~~~ 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 x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ 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 x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ ]]> </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), LocalSymbol) Assert.Equal("x1", x1.Name) Assert.Equal("Function <generated method>() As ?", x1.Type.ToTestDisplayString) Assert.True(x1.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x1.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), LocalSymbol) Assert.Equal("x2", x2.Name) Assert.Equal("Function <generated method>() As ?", x2.Type.ToTestDisplayString) Assert.True(x2.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x2.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node3), LocalSymbol) Assert.Equal("x3", x3.Name) Assert.Equal("Function <generated method>() As ?", x3.Type.ToTestDisplayString) Assert.True(x3.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x3.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node4), LocalSymbol) Assert.Equal("x4", x4.Name) Assert.Equal("Function <generated method>() As ?", x4.Type.ToTestDisplayString) Assert.True(x4.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x4.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x5 = DirectCast(semanticModel.GetDeclaredSymbol(node5), LocalSymbol) Assert.Equal("x5", x5.Name) Assert.Equal("Function <generated method>() As System.Object", x5.Type.ToTestDisplayString) Assert.True(x5.Type.IsAnonymousType) Assert.True(DirectCast(x5.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType.IsObjectType()) End If If True Then Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim x6 = DirectCast(semanticModel.GetDeclaredSymbol(node6), LocalSymbol) Assert.Equal("x6", x6.Name) Assert.Equal("Function <generated method>() As ?", x6.Type.ToTestDisplayString) Assert.True(x6.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x6.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim x7 = DirectCast(semanticModel.GetDeclaredSymbol(node7), LocalSymbol) Assert.Equal("x7", x7.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x7.Type.ToTestDisplayString) Assert.True(x7.Type.IsAnonymousType) End If If True Then Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim x8 = DirectCast(semanticModel.GetDeclaredSymbol(node8), LocalSymbol) Assert.Equal("x8", x8.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x8.Type.ToTestDisplayString) Assert.True(x8.Type.IsAnonymousType) End If Next End Sub <Fact> Public Sub Test3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Interface I1 End Interface Interface I2 End Interface Interface I3 Inherits I2, I1 End Interface Interface I4 Inherits I2, I1 End Interface Module Program Sub Main() Dim x1 = Function(y As Integer) If y > 0 Then Return New System.Collections.Generic.Dictionary(Of Integer, Integer) Else Return New System.Collections.Generic.Dictionary(Of Byte, Byte) End If End Function System.Console.WriteLine(x1.GetType()) Dim x2 = Function(y1 As I3, y2 As I4) If True Then Return y1 Else Return y2 End Function System.Console.WriteLine(x2.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42021: Cannot infer a return type; 'Object' assumed. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a return type because more than one type is possible; 'Object' assumed. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36916: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC36734: Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict ON Module Program Sub Main() End Sub Sub Test(y As System.ArgIterator) Dim x7 = Function(x) y Dim x8 = Function(x) Return y '8 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) 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. Dim x7 = Function(x) y ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x7 = Function(x) y ~ 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 x8 = Function(x) ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x8 = Function(x) ~ </expected>) End Sub <Fact()> Public Sub Test5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Call (Sub(x As Integer) System.Console.WriteLine(x))(1) 'BIND1:"Sub(x As Integer)" Call Sub(x As Integer) 'BIND2:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub(2) Dim x3 As Integer = Function() As Integer 'BIND3:"Function() As Integer" Return 3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Function <generated method>() As System.Int32", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine & "3") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 131 (0x83) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldc.i4.1 IL_0025: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002a: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_002f: brfalse.s IL_0038 IL_0031: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0036: br.s IL_004e IL_0038: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_003d: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0043: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_0048: dup IL_0049: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_004e: ldc.i4.2 IL_004f: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_0054: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0060: br.s IL_0078 IL_0062: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0067: ldftn "Function Program._Closure$__._Lambda$__0-2() As Integer" IL_006d: newobj "Sub VB$AnonymousDelegate_1(Of Integer)..ctor(Object, System.IntPtr)" IL_0072: dup IL_0073: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0078: callvirt "Function VB$AnonymousDelegate_1(Of Integer).Invoke() As Integer" IL_007d: call "Sub System.Console.WriteLine(Integer)" IL_0082: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub Test6() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim y1 as Integer = 2 Dim y2 as Integer = 3 Dim y3 as Integer = 4 Call (Sub(x As Integer) System.Console.WriteLine(x+y1))(1) Call Sub(x As Integer) System.Console.WriteLine(x+y2) End Sub(2) Dim x3 As Integer = Function() As Integer Return 3+y3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="3" & Environment.NewLine & "5" & Environment.NewLine & "7") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.2 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_y1 As Integer" IL_000c: dup IL_000d: ldc.i4.3 IL_000e: stfld "Program._Closure$__0-0.$VB$Local_y2 As Integer" IL_0013: dup IL_0014: ldc.i4.4 IL_0015: stfld "Program._Closure$__0-0.$VB$Local_y3 As Integer" IL_001a: dup IL_001b: ldc.i4.1 IL_001c: callvirt "Sub Program._Closure$__0-0._Lambda$__0(Integer)" IL_0021: dup IL_0022: ldc.i4.2 IL_0023: callvirt "Sub Program._Closure$__0-0._Lambda$__1(Integer)" IL_0028: callvirt "Function Program._Closure$__0-0._Lambda$__2() As Integer" IL_002d: call "Sub System.Console.WriteLine(Integer)" IL_0032: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact()> Public Sub AnonDelegateReturningLambdaWithGenericType() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of System.Func(Of T)) Dim x2 = Function() Return Function() As T Return Nothing End Function End Function Return x2 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="0") 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.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_AnonymousDelegateInference Inherits BasicTestBase <Fact> Public Sub Test1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x = Function(y) y System.Console.WriteLine(x.GetType()) x = Function(y) y ' No inference here, using delegate type from x. System.Console.WriteLine(x.GetType()) Dim x2 As Object = Function(y) y System.Console.WriteLine(x2.GetType()) Dim x3 = Function() Function() "a" System.Console.WriteLine(x3.GetType()) Dim x4 = Function() Return Function() 2.5 End Function System.Console.WriteLine(x4.GetType()) Dim x5 = DirectCast(Function() Date.Now, System.Delegate) System.Console.WriteLine(x5.GetType()) Dim x6 = TryCast(Function() Decimal.MaxValue, System.MulticastDelegate) System.Console.WriteLine(x6.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x = Function(y) y ~ BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x2 As Object = Function(y) y ~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x = Function(y) y ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x2 As Object = Function(y) y ~ </expected>) End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 = Function() Unknown 'BIND1:"x1" Dim x2 = Function() : 'BIND2:"x2" Dim x3 = Function() 'BIND3:"x3" Return Unknown '3 End Function Dim x4 = Function() 'BIND4:"x4" Unknown() End Function '4 Dim x5 = Function() AddressOf Main 'BIND5:"x5" Dim x6 = Function() 'BIND6:"x6" Return AddressOf Main '6 End Function End Sub Delegate Sub D1(x As System.ArgIterator) Sub Test(y As System.ArgIterator) Dim x7 = Function() y 'BIND7:"x7" Dim x8 = Function() 'BIND8:"x8" Return y '8 End Function Dim x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ' The following Dim shouldn't produce any errors. Dim x10 As D1 = Sub(x As System.ArgIterator) System.Console.WriteLine() Dim x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each strict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Dim x1 = Function() Unknown 'BIND1:"x1" ~~~~~~~ BC30201: Expression expected. Dim x2 = Function() : 'BIND2:"x2" ~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Return Unknown '3 ~~~~~~~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Unknown() ~~~~~~~ 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 '4 ~~~~~~~~~~~~ BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x5 = Function() AddressOf Main 'BIND5:"x5" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x6 = Function() 'BIND6:"x6" ~~~~~~~~~~ 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 x7 = Function() y 'BIND7:"x7" ~~~~~~~~~~ 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 x8 = Function() 'BIND8:"x8" ~~~~~~~~~~ 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 x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ 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 x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ ]]> </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), LocalSymbol) Assert.Equal("x1", x1.Name) Assert.Equal("Function <generated method>() As ?", x1.Type.ToTestDisplayString) Assert.True(x1.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x1.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), LocalSymbol) Assert.Equal("x2", x2.Name) Assert.Equal("Function <generated method>() As ?", x2.Type.ToTestDisplayString) Assert.True(x2.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x2.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node3), LocalSymbol) Assert.Equal("x3", x3.Name) Assert.Equal("Function <generated method>() As ?", x3.Type.ToTestDisplayString) Assert.True(x3.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x3.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node4), LocalSymbol) Assert.Equal("x4", x4.Name) Assert.Equal("Function <generated method>() As ?", x4.Type.ToTestDisplayString) Assert.True(x4.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x4.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x5 = DirectCast(semanticModel.GetDeclaredSymbol(node5), LocalSymbol) Assert.Equal("x5", x5.Name) Assert.Equal("Function <generated method>() As System.Object", x5.Type.ToTestDisplayString) Assert.True(x5.Type.IsAnonymousType) Assert.True(DirectCast(x5.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType.IsObjectType()) End If If True Then Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim x6 = DirectCast(semanticModel.GetDeclaredSymbol(node6), LocalSymbol) Assert.Equal("x6", x6.Name) Assert.Equal("Function <generated method>() As ?", x6.Type.ToTestDisplayString) Assert.True(x6.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x6.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim x7 = DirectCast(semanticModel.GetDeclaredSymbol(node7), LocalSymbol) Assert.Equal("x7", x7.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x7.Type.ToTestDisplayString) Assert.True(x7.Type.IsAnonymousType) End If If True Then Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim x8 = DirectCast(semanticModel.GetDeclaredSymbol(node8), LocalSymbol) Assert.Equal("x8", x8.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x8.Type.ToTestDisplayString) Assert.True(x8.Type.IsAnonymousType) End If Next End Sub <Fact> Public Sub Test3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Interface I1 End Interface Interface I2 End Interface Interface I3 Inherits I2, I1 End Interface Interface I4 Inherits I2, I1 End Interface Module Program Sub Main() Dim x1 = Function(y As Integer) If y > 0 Then Return New System.Collections.Generic.Dictionary(Of Integer, Integer) Else Return New System.Collections.Generic.Dictionary(Of Byte, Byte) End If End Function System.Console.WriteLine(x1.GetType()) Dim x2 = Function(y1 As I3, y2 As I4) If True Then Return y1 Else Return y2 End Function System.Console.WriteLine(x2.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42021: Cannot infer a return type; 'Object' assumed. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a return type because more than one type is possible; 'Object' assumed. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36916: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC36734: Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict ON Module Program Sub Main() End Sub Sub Test(y As System.ArgIterator) Dim x7 = Function(x) y Dim x8 = Function(x) Return y '8 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) 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. Dim x7 = Function(x) y ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x7 = Function(x) y ~ 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 x8 = Function(x) ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x8 = Function(x) ~ </expected>) End Sub <Fact()> Public Sub Test5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Call (Sub(x As Integer) System.Console.WriteLine(x))(1) 'BIND1:"Sub(x As Integer)" Call Sub(x As Integer) 'BIND2:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub(2) Dim x3 As Integer = Function() As Integer 'BIND3:"Function() As Integer" Return 3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Function <generated method>() As System.Int32", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & Environment.NewLine & "2" & Environment.NewLine & "3") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 131 (0x83) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldc.i4.1 IL_0025: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002a: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_002f: brfalse.s IL_0038 IL_0031: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0036: br.s IL_004e IL_0038: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_003d: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0043: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_0048: dup IL_0049: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_004e: ldc.i4.2 IL_004f: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_0054: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0060: br.s IL_0078 IL_0062: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0067: ldftn "Function Program._Closure$__._Lambda$__0-2() As Integer" IL_006d: newobj "Sub VB$AnonymousDelegate_1(Of Integer)..ctor(Object, System.IntPtr)" IL_0072: dup IL_0073: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0078: callvirt "Function VB$AnonymousDelegate_1(Of Integer).Invoke() As Integer" IL_007d: call "Sub System.Console.WriteLine(Integer)" IL_0082: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub Test6() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim y1 as Integer = 2 Dim y2 as Integer = 3 Dim y3 as Integer = 4 Call (Sub(x As Integer) System.Console.WriteLine(x+y1))(1) Call Sub(x As Integer) System.Console.WriteLine(x+y2) End Sub(2) Dim x3 As Integer = Function() As Integer Return 3+y3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="3" & Environment.NewLine & "5" & Environment.NewLine & "7") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.2 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_y1 As Integer" IL_000c: dup IL_000d: ldc.i4.3 IL_000e: stfld "Program._Closure$__0-0.$VB$Local_y2 As Integer" IL_0013: dup IL_0014: ldc.i4.4 IL_0015: stfld "Program._Closure$__0-0.$VB$Local_y3 As Integer" IL_001a: dup IL_001b: ldc.i4.1 IL_001c: callvirt "Sub Program._Closure$__0-0._Lambda$__0(Integer)" IL_0021: dup IL_0022: ldc.i4.2 IL_0023: callvirt "Sub Program._Closure$__0-0._Lambda$__1(Integer)" IL_0028: callvirt "Function Program._Closure$__0-0._Lambda$__2() As Integer" IL_002d: call "Sub System.Console.WriteLine(Integer)" IL_0032: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact()> Public Sub AnonDelegateReturningLambdaWithGenericType() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of System.Func(Of T)) Dim x2 = Function() Return Function() As T Return Nothing End Function End Function Return x2 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="0") End Sub End Class End Namespace
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Portable/Binder/LocalScopeBinder.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalScopeBinder : Binder { private ImmutableArray<LocalSymbol> _locals; private ImmutableArray<LocalFunctionSymbol> _localFunctions; private ImmutableArray<LabelSymbol> _labels; private readonly uint _localScopeDepth; internal LocalScopeBinder(Binder next) : this(next, next.Flags) { } internal LocalScopeBinder(Binder next, BinderFlags flags) : base(next, flags) { var parentDepth = next.LocalScopeDepth; if (parentDepth != Binder.TopLevelScope) { _localScopeDepth = parentDepth + 1; } else { //NOTE: TopLevel is special. //For our purpose parameters and top level locals are on that level. var parentScope = next; while (parentScope != null) { if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder) { _localScopeDepth = Binder.TopLevelScope; break; } if (parentScope is LocalScopeBinder) { _localScopeDepth = Binder.TopLevelScope + 1; break; } parentScope = parentScope.Next; Debug.Assert(parentScope != null); } } } internal sealed override ImmutableArray<LocalSymbol> Locals { get { if (_locals.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>)); } return _locals; } } protected virtual ImmutableArray<LocalSymbol> BuildLocals() { return ImmutableArray<LocalSymbol>.Empty; } internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { if (_localFunctions.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>)); } return _localFunctions; } } protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return ImmutableArray<LocalFunctionSymbol>.Empty; } internal sealed override ImmutableArray<LabelSymbol> Labels { get { if (_labels.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>)); } return _labels; } } protected virtual ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } private SmallDictionary<string, LocalSymbol> _lazyLocalsMap; private SmallDictionary<string, LocalSymbol> LocalsMap { get { if (_lazyLocalsMap == null && this.Locals.Length > 0) { _lazyLocalsMap = BuildMap(this.Locals); } return _lazyLocalsMap; } } private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap; private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap { get { if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0) { _lazyLocalFunctionsMap = BuildMap(this.LocalFunctions); } return _lazyLocalFunctionsMap; } } private SmallDictionary<string, LabelSymbol> _lazyLabelsMap; private SmallDictionary<string, LabelSymbol> LabelsMap { get { if (_lazyLabelsMap == null && this.Labels.Length > 0) { _lazyLabelsMap = BuildMap(this.Labels); } return _lazyLabelsMap; } } private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array) where TSymbol : Symbol { Debug.Assert(array.Length > 0); var map = new SmallDictionary<string, TSymbol>(); // NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins. for (int i = array.Length - 1; i >= 0; i--) { var symbol = array[i]; map[symbol.Name] = symbol; } return map; } protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder) { #if DEBUG Binder currentBinder = enclosingBinder; while (true) { if (this == currentBinder) { break; } currentBinder = currentBinder.Next; } #endif ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in statements) { BuildLocals(enclosingBinder, statement, locals); } return locals.ToImmutableAndFree(); } internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: { Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder; var decl = (LocalDeclarationStatementSyntax)innerStatement; decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var expression in rankSpecifier.Sizes) { if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder); } } }, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder)); LocalDeclarationKind kind; if (decl.IsConst) { kind = LocalDeclarationKind.Constant; } else if (decl.UsingKeyword != default(SyntaxToken)) { kind = LocalDeclarationKind.UsingVariable; } else { kind = LocalDeclarationKind.RegularVariable; } foreach (var vdecl in decl.Declaration.Variables) { var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder); } } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.GotoCaseStatement: ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder); break; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)innerStatement; ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder); break; case SyntaxKind.LockStatement: Binder statementBinder = enclosingBinder.GetBinder(innerStatement); Debug.Assert(statementBinder != null); // Lock always has a binder. ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder); break; default: // no other statement introduces local variables into the enclosing scope break; } } protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements) { ArrayBuilder<LocalFunctionSymbol> locals = null; foreach (var statement in statements) { BuildLocalFunctions(statement, ref locals); } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement) { var decl = (LocalFunctionStatementSyntax)innerStatement; if (locals == null) { locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); } var localSymbol = MakeLocalFunction(decl); locals.Add(localSymbol); } } protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null) { return SourceLocalSymbol.MakeLocal( this.ContainingMemberOrLambda, this, true, declaration.Type, declarator.Identifier, kind, declarator.Initializer, initializerBinderOpt); } protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration) { return new LocalFunctionSymbol( this, this.ContainingMemberOrLambda, declaration); } protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels) { var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda; foreach (var statement in statements) { BuildLabels(containingMethod, statement, ref labels); } } internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels) { while (statement.Kind() == SyntaxKind.LabeledStatement) { var labeledStatement = (LabeledStatementSyntax)statement; if (labels == null) { labels = ArrayBuilder<LabelSymbol>.GetInstance(); } var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier); labels.Add(labelSymbol); statement = labeledStatement.Statement; } } /// <summary> /// Call this when you are sure there is a local declaration on this token. Returns the local. /// </summary> protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { LocalSymbol result = null; if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.Locals) { if (local.IdentifierToken == nameToken) { return (SourceLocalSymbol)local; } } } return base.LookupLocal(nameToken); } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { LocalFunctionSymbol result = null; if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.NameToken == nameToken) return result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.LocalFunctions) { if (local.NameToken == nameToken) { return local; } } } return base.LookupLocalFunction(nameToken); } internal override uint LocalScopeDepth => _localScopeDepth; internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(options.AreValid()); Debug.Assert(result.IsClear); if ((options & LookupOptions.LabelsOnly) != 0) { var labelsMap = this.LabelsMap; if (labelsMap != null) { LabelSymbol labelSymbol; if (labelsMap.TryGetValue(name, out labelSymbol)) { result.MergeEqual(LookupResult.Good(labelSymbol)); } } return; } var localsMap = this.LocalsMap; if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0) { LocalSymbol localSymbol; if (localsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } var localFunctionsMap = this.LocalFunctionsMap; if (localFunctionsMap != null && options.CanConsiderLocals()) { LocalFunctionSymbol localSymbol; if (localFunctionsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { Debug.Assert(options.AreValid()); if ((options & LookupOptions.LabelsOnly) != 0) { if (this.LabelsMap != null) { foreach (var label in this.LabelsMap) { result.AddSymbol(label.Value, label.Key, 0); } } } if (options.CanConsiderLocals()) { if (this.LocalsMap != null) { foreach (var local in this.LocalsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } if (this.LocalFunctionsMap != null) { foreach (var local in this.LocalFunctionsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } } } private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) return true; var declaredInThisScope = false; declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol); declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol); if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start) { // A local variable or function named '{0}' is already defined in this scope diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name); return true; } switch (newSymbolKind) { case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Method: case SymbolKind.TypeParameter: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else can be declared inside a local scope?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { LocalSymbol existingLocal = null; LocalFunctionSymbol existingLocalFunction = null; var localsMap = this.LocalsMap; var localFunctionsMap = this.LocalFunctionsMap; // TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions. if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) || (localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction))) { var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction; if (symbol == existingSymbol) { // reference to same symbol, by far the most common case. return false; } return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics); } return 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalScopeBinder : Binder { private ImmutableArray<LocalSymbol> _locals; private ImmutableArray<LocalFunctionSymbol> _localFunctions; private ImmutableArray<LabelSymbol> _labels; private readonly uint _localScopeDepth; internal LocalScopeBinder(Binder next) : this(next, next.Flags) { } internal LocalScopeBinder(Binder next, BinderFlags flags) : base(next, flags) { var parentDepth = next.LocalScopeDepth; if (parentDepth != Binder.TopLevelScope) { _localScopeDepth = parentDepth + 1; } else { //NOTE: TopLevel is special. //For our purpose parameters and top level locals are on that level. var parentScope = next; while (parentScope != null) { if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder) { _localScopeDepth = Binder.TopLevelScope; break; } if (parentScope is LocalScopeBinder) { _localScopeDepth = Binder.TopLevelScope + 1; break; } parentScope = parentScope.Next; Debug.Assert(parentScope != null); } } } internal sealed override ImmutableArray<LocalSymbol> Locals { get { if (_locals.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>)); } return _locals; } } protected virtual ImmutableArray<LocalSymbol> BuildLocals() { return ImmutableArray<LocalSymbol>.Empty; } internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { if (_localFunctions.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>)); } return _localFunctions; } } protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return ImmutableArray<LocalFunctionSymbol>.Empty; } internal sealed override ImmutableArray<LabelSymbol> Labels { get { if (_labels.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>)); } return _labels; } } protected virtual ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } private SmallDictionary<string, LocalSymbol> _lazyLocalsMap; private SmallDictionary<string, LocalSymbol> LocalsMap { get { if (_lazyLocalsMap == null && this.Locals.Length > 0) { _lazyLocalsMap = BuildMap(this.Locals); } return _lazyLocalsMap; } } private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap; private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap { get { if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0) { _lazyLocalFunctionsMap = BuildMap(this.LocalFunctions); } return _lazyLocalFunctionsMap; } } private SmallDictionary<string, LabelSymbol> _lazyLabelsMap; private SmallDictionary<string, LabelSymbol> LabelsMap { get { if (_lazyLabelsMap == null && this.Labels.Length > 0) { _lazyLabelsMap = BuildMap(this.Labels); } return _lazyLabelsMap; } } private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array) where TSymbol : Symbol { Debug.Assert(array.Length > 0); var map = new SmallDictionary<string, TSymbol>(); // NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins. for (int i = array.Length - 1; i >= 0; i--) { var symbol = array[i]; map[symbol.Name] = symbol; } return map; } protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder) { #if DEBUG Binder currentBinder = enclosingBinder; while (true) { if (this == currentBinder) { break; } currentBinder = currentBinder.Next; } #endif ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in statements) { BuildLocals(enclosingBinder, statement, locals); } return locals.ToImmutableAndFree(); } internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: { Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder; var decl = (LocalDeclarationStatementSyntax)innerStatement; decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var expression in rankSpecifier.Sizes) { if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder); } } }, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder)); LocalDeclarationKind kind; if (decl.IsConst) { kind = LocalDeclarationKind.Constant; } else if (decl.UsingKeyword != default(SyntaxToken)) { kind = LocalDeclarationKind.UsingVariable; } else { kind = LocalDeclarationKind.RegularVariable; } foreach (var vdecl in decl.Declaration.Variables) { var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder); } } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.GotoCaseStatement: ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder); break; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)innerStatement; ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder); break; case SyntaxKind.LockStatement: Binder statementBinder = enclosingBinder.GetBinder(innerStatement); Debug.Assert(statementBinder != null); // Lock always has a binder. ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder); break; default: // no other statement introduces local variables into the enclosing scope break; } } protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements) { ArrayBuilder<LocalFunctionSymbol> locals = null; foreach (var statement in statements) { BuildLocalFunctions(statement, ref locals); } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement) { var decl = (LocalFunctionStatementSyntax)innerStatement; if (locals == null) { locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); } var localSymbol = MakeLocalFunction(decl); locals.Add(localSymbol); } } protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null) { return SourceLocalSymbol.MakeLocal( this.ContainingMemberOrLambda, this, true, declaration.Type, declarator.Identifier, kind, declarator.Initializer, initializerBinderOpt); } protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration) { return new LocalFunctionSymbol( this, this.ContainingMemberOrLambda, declaration); } protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels) { var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda; foreach (var statement in statements) { BuildLabels(containingMethod, statement, ref labels); } } internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels) { while (statement.Kind() == SyntaxKind.LabeledStatement) { var labeledStatement = (LabeledStatementSyntax)statement; if (labels == null) { labels = ArrayBuilder<LabelSymbol>.GetInstance(); } var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier); labels.Add(labelSymbol); statement = labeledStatement.Statement; } } /// <summary> /// Call this when you are sure there is a local declaration on this token. Returns the local. /// </summary> protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { LocalSymbol result = null; if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.Locals) { if (local.IdentifierToken == nameToken) { return (SourceLocalSymbol)local; } } } return base.LookupLocal(nameToken); } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { LocalFunctionSymbol result = null; if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.NameToken == nameToken) return result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.LocalFunctions) { if (local.NameToken == nameToken) { return local; } } } return base.LookupLocalFunction(nameToken); } internal override uint LocalScopeDepth => _localScopeDepth; internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(options.AreValid()); Debug.Assert(result.IsClear); if ((options & LookupOptions.LabelsOnly) != 0) { var labelsMap = this.LabelsMap; if (labelsMap != null) { LabelSymbol labelSymbol; if (labelsMap.TryGetValue(name, out labelSymbol)) { result.MergeEqual(LookupResult.Good(labelSymbol)); } } return; } var localsMap = this.LocalsMap; if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0) { LocalSymbol localSymbol; if (localsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } var localFunctionsMap = this.LocalFunctionsMap; if (localFunctionsMap != null && options.CanConsiderLocals()) { LocalFunctionSymbol localSymbol; if (localFunctionsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { Debug.Assert(options.AreValid()); if ((options & LookupOptions.LabelsOnly) != 0) { if (this.LabelsMap != null) { foreach (var label in this.LabelsMap) { result.AddSymbol(label.Value, label.Key, 0); } } } if (options.CanConsiderLocals()) { if (this.LocalsMap != null) { foreach (var local in this.LocalsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } if (this.LocalFunctionsMap != null) { foreach (var local in this.LocalFunctionsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } } } private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) return true; var declaredInThisScope = false; declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol); declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol); if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start) { // A local variable or function named '{0}' is already defined in this scope diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name); return true; } switch (newSymbolKind) { case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Method: case SymbolKind.TypeParameter: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else can be declared inside a local scope?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { LocalSymbol existingLocal = null; LocalFunctionSymbol existingLocalFunction = null; var localsMap = this.LocalsMap; var localFunctionsMap = this.LocalFunctionsMap; // TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions. if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) || (localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction))) { var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction; if (symbol == existingSymbol) { // reference to same symbol, by far the most common case. return false; } return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics); } return false; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/VisualBasic/Portable/Lowering/SynthesizedSubmissionFields.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.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Tracks synthesized fields that are needed in a submission being compiled. ''' </summary> ''' <remarks> ''' For every other submission referenced by this submission we add a field, so that we can access members of the target submission. ''' A field is also needed for the host object, if provided. ''' </remarks> Friend Class SynthesizedSubmissionFields Private ReadOnly _declaringSubmissionClass As NamedTypeSymbol Private ReadOnly _compilation As VisualBasicCompilation Private _hostObjectField As FieldSymbol Private _previousSubmissionFieldMap As Dictionary(Of ImplicitNamedTypeSymbol, FieldSymbol) Public Sub New(compilation As VisualBasicCompilation, submissionClass As NamedTypeSymbol) Debug.Assert(compilation IsNot Nothing) Debug.Assert(submissionClass.IsSubmissionClass) _declaringSubmissionClass = submissionClass _compilation = compilation End Sub Friend ReadOnly Property Count As Integer Get Return If(_previousSubmissionFieldMap Is Nothing, 0, _previousSubmissionFieldMap.Count) End Get End Property Friend ReadOnly Property FieldSymbols As IEnumerable(Of FieldSymbol) Get Return If(_previousSubmissionFieldMap Is Nothing, Array.Empty(Of FieldSymbol)(), DirectCast(_previousSubmissionFieldMap.Values, IEnumerable(Of FieldSymbol))) End Get End Property Friend Function GetHostObjectField() As FieldSymbol If _hostObjectField IsNot Nothing Then Return _hostObjectField End If ' TODO (tomat): Dim hostObjectTypeSymbol = compilation.GetHostObjectTypeSymbol() Dim hostObjectTypeSymbol As TypeSymbol = Nothing If hostObjectTypeSymbol IsNot Nothing AndAlso hostObjectTypeSymbol.Kind <> SymbolKind.ErrorType Then _hostObjectField = New SynthesizedFieldSymbol(_declaringSubmissionClass, _declaringSubmissionClass, hostObjectTypeSymbol, "<host-object>", accessibility:=Accessibility.Private, isReadOnly:=True, isShared:=False) Return _hostObjectField End If Return Nothing End Function Friend Function GetOrMakeField(previousSubmissionType As ImplicitNamedTypeSymbol) As FieldSymbol If _previousSubmissionFieldMap Is Nothing Then _previousSubmissionFieldMap = New Dictionary(Of ImplicitNamedTypeSymbol, FieldSymbol)() End If Dim previousSubmissionField As FieldSymbol = Nothing If Not _previousSubmissionFieldMap.TryGetValue(previousSubmissionType, previousSubmissionField) Then previousSubmissionField = New SynthesizedFieldSymbol( _declaringSubmissionClass, implicitlyDefinedBy:=_declaringSubmissionClass, Type:=previousSubmissionType, name:="<" + previousSubmissionType.Name + ">", isReadOnly:=True) _previousSubmissionFieldMap.Add(previousSubmissionType, previousSubmissionField) End If Return previousSubmissionField End Function Friend Sub AddToType(containingType As NamedTypeSymbol, moduleBeingBuilt As PEModuleBuilder) For Each field In FieldSymbols moduleBeingBuilt.AddSynthesizedDefinition(containingType, field.GetCciAdapter()) Next Dim hostObjectField As FieldSymbol = GetHostObjectField() If hostObjectField IsNot Nothing Then moduleBeingBuilt.AddSynthesizedDefinition(containingType, hostObjectField.GetCciAdapter()) End If 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.Generic Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Tracks synthesized fields that are needed in a submission being compiled. ''' </summary> ''' <remarks> ''' For every other submission referenced by this submission we add a field, so that we can access members of the target submission. ''' A field is also needed for the host object, if provided. ''' </remarks> Friend Class SynthesizedSubmissionFields Private ReadOnly _declaringSubmissionClass As NamedTypeSymbol Private ReadOnly _compilation As VisualBasicCompilation Private _hostObjectField As FieldSymbol Private _previousSubmissionFieldMap As Dictionary(Of ImplicitNamedTypeSymbol, FieldSymbol) Public Sub New(compilation As VisualBasicCompilation, submissionClass As NamedTypeSymbol) Debug.Assert(compilation IsNot Nothing) Debug.Assert(submissionClass.IsSubmissionClass) _declaringSubmissionClass = submissionClass _compilation = compilation End Sub Friend ReadOnly Property Count As Integer Get Return If(_previousSubmissionFieldMap Is Nothing, 0, _previousSubmissionFieldMap.Count) End Get End Property Friend ReadOnly Property FieldSymbols As IEnumerable(Of FieldSymbol) Get Return If(_previousSubmissionFieldMap Is Nothing, Array.Empty(Of FieldSymbol)(), DirectCast(_previousSubmissionFieldMap.Values, IEnumerable(Of FieldSymbol))) End Get End Property Friend Function GetHostObjectField() As FieldSymbol If _hostObjectField IsNot Nothing Then Return _hostObjectField End If ' TODO (tomat): Dim hostObjectTypeSymbol = compilation.GetHostObjectTypeSymbol() Dim hostObjectTypeSymbol As TypeSymbol = Nothing If hostObjectTypeSymbol IsNot Nothing AndAlso hostObjectTypeSymbol.Kind <> SymbolKind.ErrorType Then _hostObjectField = New SynthesizedFieldSymbol(_declaringSubmissionClass, _declaringSubmissionClass, hostObjectTypeSymbol, "<host-object>", accessibility:=Accessibility.Private, isReadOnly:=True, isShared:=False) Return _hostObjectField End If Return Nothing End Function Friend Function GetOrMakeField(previousSubmissionType As ImplicitNamedTypeSymbol) As FieldSymbol If _previousSubmissionFieldMap Is Nothing Then _previousSubmissionFieldMap = New Dictionary(Of ImplicitNamedTypeSymbol, FieldSymbol)() End If Dim previousSubmissionField As FieldSymbol = Nothing If Not _previousSubmissionFieldMap.TryGetValue(previousSubmissionType, previousSubmissionField) Then previousSubmissionField = New SynthesizedFieldSymbol( _declaringSubmissionClass, implicitlyDefinedBy:=_declaringSubmissionClass, Type:=previousSubmissionType, name:="<" + previousSubmissionType.Name + ">", isReadOnly:=True) _previousSubmissionFieldMap.Add(previousSubmissionType, previousSubmissionField) End If Return previousSubmissionField End Function Friend Sub AddToType(containingType As NamedTypeSymbol, moduleBeingBuilt As PEModuleBuilder) For Each field In FieldSymbols moduleBeingBuilt.AddSynthesizedDefinition(containingType, field.GetCciAdapter()) Next Dim hostObjectField As FieldSymbol = GetHostObjectField() If hostObjectField IsNot Nothing Then moduleBeingBuilt.AddSynthesizedDefinition(containingType, hostObjectField.GetCciAdapter()) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/EmbeddedLanguages/LanguageServices/FallbackSyntaxClassifier.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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices { internal class FallbackSyntaxClassifier : AbstractSyntaxClassifier { private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public FallbackSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create( info.CharLiteralTokenKind, info.StringLiteralTokenKind, info.InterpolatedTextTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.CharLiteralTokenKind != token.RawKind && _info.StringLiteralTokenKind != token.RawKind && _info.InterpolatedTextTokenKind != token.RawKind) { return; } var virtualChars = _info.VirtualCharService.TryConvertToVirtualChars(token); if (virtualChars.IsDefaultOrEmpty) { return; } foreach (var vc in virtualChars) { if (vc.Span.Length > 1) { result.Add(new ClassifiedSpan(ClassificationTypeNames.StringEscapeCharacter, vc.Span)); } } } } }
// 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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices { internal class FallbackSyntaxClassifier : AbstractSyntaxClassifier { private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public FallbackSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create( info.CharLiteralTokenKind, info.StringLiteralTokenKind, info.InterpolatedTextTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.CharLiteralTokenKind != token.RawKind && _info.StringLiteralTokenKind != token.RawKind && _info.InterpolatedTextTokenKind != token.RawKind) { return; } var virtualChars = _info.VirtualCharService.TryConvertToVirtualChars(token); if (virtualChars.IsDefaultOrEmpty) { return; } foreach (var vc in virtualChars) { if (vc.Span.Length > 1) { result.Add(new ClassifiedSpan(ClassificationTypeNames.StringEscapeCharacter, vc.Span)); } } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/CodeStyle/Core/CodeFixes/LanguageServices/SemanticModelWorkspaceService/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory { private sealed class SemanticModelReuseWorkspaceService : ISemanticModelReuseWorkspaceService { public SemanticModelReuseWorkspaceService(Workspace _) { } public ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { // TODO: port the GetSemanticModelForNodeAsync implementation from Workspaces layer, // which currently relies on a bunch of internal APIs. // For now, we fall back to the public API to fetch document's SemanticModel. return document.GetRequiredSemanticModelAsync(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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory { private sealed class SemanticModelReuseWorkspaceService : ISemanticModelReuseWorkspaceService { public SemanticModelReuseWorkspaceService(Workspace _) { } public ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { // TODO: port the GetSemanticModelForNodeAsync implementation from Workspaces layer, // which currently relies on a bunch of internal APIs. // For now, we fall back to the public API to fetch document's SemanticModel. return document.GetRequiredSemanticModelAsync(cancellationToken); } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/TypeKindTests.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.Linq; 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; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class TypeKindTests : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestTypeKindHelper(assembly); } private void TestTypeKindHelper(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var system = (from n in module0.GlobalNamespace.GetMembers() where n.Name.Equals("System") select n).Cast<NamespaceSymbol>().Single(); var obj = (from t in system.GetTypeMembers() where t.Name.Equals("Object") select t).Single(); Assert.Equal(TypeKind.Class, obj.TypeKind); var @enum = (from t in system.GetTypeMembers() where t.Name.Equals("Enum") select t).Single(); Assert.Equal(TypeKind.Class, @enum.TypeKind); var int32 = (from t in system.GetTypeMembers() where t.Name.Equals("Int32") select t).Single(); Assert.Equal(TypeKind.Struct, int32.TypeKind); var func = (from t in system.GetTypeMembers() where t.Name.Equals("Func") && t.Arity == 1 select t).Single(); Assert.Equal(TypeKind.Delegate, func.TypeKind); var collections = (from n in system.GetMembers() where n.Name.Equals("Collections") select n).Cast<NamespaceSymbol>().Single(); var ienumerable = (from t in collections.GetTypeMembers() where t.Name.Equals("IEnumerable") select t).Single(); Assert.Equal(TypeKind.Interface, ienumerable.TypeKind); Assert.Null(ienumerable.BaseType()); var typeCode = (from t in system.GetTypeMembers() where t.Name.Equals("TypeCode") select t).Single(); Assert.Equal(TypeKind.Enum, typeCode.TypeKind); Assert.False(obj.IsAbstract); Assert.False(obj.IsSealed); Assert.False(obj.IsStatic); Assert.True(@enum.IsAbstract); Assert.False(@enum.IsSealed); Assert.False(@enum.IsStatic); Assert.False(func.IsAbstract); Assert.True(func.IsSealed); Assert.False(func.IsStatic); var console = system.GetTypeMembers("Console").Single(); Assert.False(console.IsAbstract); Assert.False(console.IsSealed); Assert.True(console.IsStatic); } } }
// 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.Linq; 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; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class TypeKindTests : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestTypeKindHelper(assembly); } private void TestTypeKindHelper(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var system = (from n in module0.GlobalNamespace.GetMembers() where n.Name.Equals("System") select n).Cast<NamespaceSymbol>().Single(); var obj = (from t in system.GetTypeMembers() where t.Name.Equals("Object") select t).Single(); Assert.Equal(TypeKind.Class, obj.TypeKind); var @enum = (from t in system.GetTypeMembers() where t.Name.Equals("Enum") select t).Single(); Assert.Equal(TypeKind.Class, @enum.TypeKind); var int32 = (from t in system.GetTypeMembers() where t.Name.Equals("Int32") select t).Single(); Assert.Equal(TypeKind.Struct, int32.TypeKind); var func = (from t in system.GetTypeMembers() where t.Name.Equals("Func") && t.Arity == 1 select t).Single(); Assert.Equal(TypeKind.Delegate, func.TypeKind); var collections = (from n in system.GetMembers() where n.Name.Equals("Collections") select n).Cast<NamespaceSymbol>().Single(); var ienumerable = (from t in collections.GetTypeMembers() where t.Name.Equals("IEnumerable") select t).Single(); Assert.Equal(TypeKind.Interface, ienumerable.TypeKind); Assert.Null(ienumerable.BaseType()); var typeCode = (from t in system.GetTypeMembers() where t.Name.Equals("TypeCode") select t).Single(); Assert.Equal(TypeKind.Enum, typeCode.TypeKind); Assert.False(obj.IsAbstract); Assert.False(obj.IsSealed); Assert.False(obj.IsStatic); Assert.True(@enum.IsAbstract); Assert.False(@enum.IsSealed); Assert.False(@enum.IsStatic); Assert.False(func.IsAbstract); Assert.True(func.IsSealed); Assert.False(func.IsStatic); var console = system.GetTypeMembers("Console").Single(); Assert.False(console.IsAbstract); Assert.False(console.IsSealed); Assert.True(console.IsStatic); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/Signatures/TypeSpecInWrongPlace.exe
MZ@ !L!This program cannot be run in DOS mode. $PELՐV  " @@ `@"K@  H.text  `.reloc @@B"Hh H.s (*.rp( *BSJB v4.0.30319l#~L#Strings #US#GUID (#BlobG %3R% 92@2t} P \  ,H k<Module>System.Collections.GenericList`1.ctorSystemObjectConsoleWriteLineTypeSpecInWrongPlace.exemscorlibExtenderUserMainXA_0TypeSpecInWrongPlacegoodbye world,3HY&l  z\V4"" "_CorExeMainmscoree.dll% @ 3
MZ@ !L!This program cannot be run in DOS mode. $PELՐV  " @@ `@"K@  H.text  `.reloc @@B"Hh H.s (*.rp( *BSJB v4.0.30319l#~L#Strings #US#GUID (#BlobG %3R% 92@2t} P \  ,H k<Module>System.Collections.GenericList`1.ctorSystemObjectConsoleWriteLineTypeSpecInWrongPlace.exemscorlibExtenderUserMainXA_0TypeSpecInWrongPlacegoodbye world,3HY&l  z\V4"" "_CorExeMainmscoree.dll% @ 3
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractTypeImportCompletionProvider<AliasDeclarationTypeNode> : AbstractImportCompletionProvider where AliasDeclarationTypeNode : SyntaxNode { protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsTypeContext; protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfTypeImportCompletionItem(); protected abstract ImmutableArray<AliasDeclarationTypeNode> GetAliasDeclarationNodes(SyntaxNode node); protected override async Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespacesInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_TypeImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var telemetryCounter = new TelemetryCounter(); var typeImportCompletionService = completionContext.Document.GetRequiredLanguageService<ITypeImportCompletionService>(); var itemsFromAllAssemblies = await typeImportCompletionService.GetAllTopLevelTypesAsync( completionContext.Document.Project, syntaxContext, forceCacheCreation: isExpandedCompletion, cancellationToken).ConfigureAwait(false); if (itemsFromAllAssemblies == null) { telemetryCounter.CacheMiss = true; } else { var aliasTargetNamespaceToTypeNameMap = GetAliasTypeDictionary(completionContext.Document, syntaxContext, cancellationToken); foreach (var items in itemsFromAllAssemblies) { AddItems(items, completionContext, namespacesInScope, aliasTargetNamespaceToTypeNameMap, telemetryCounter); } } telemetryCounter.Report(); } } /// <summary> /// Get a multi-Dictionary stores the information about the target of all alias Symbol in the syntax tree. /// Multiple aliases might live under same namespace. /// Key is the namespace of the symbol, value is the name of the symbol. /// </summary> private MultiDictionary<string, string> GetAliasTypeDictionary( Document document, SyntaxContext syntaxContext, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var dictionary = new MultiDictionary<string, string>(syntaxFactsService.StringComparer); var nodeToCheck = syntaxContext.LeftToken.Parent; if (nodeToCheck == null) { return dictionary; } // In case the caret is at the beginning of the file, take the root node. var aliasDeclarations = GetAliasDeclarationNodes(nodeToCheck); foreach (var aliasNode in aliasDeclarations) { var symbol = syntaxContext.SemanticModel.GetDeclaredSymbol(aliasNode, cancellationToken); if (symbol is IAliasSymbol { Target: ITypeSymbol { TypeKind: not TypeKind.Error } target }) { // If the target type is a type constructs from generics type, e.g. // using AliasBar = Bar<int> // namespace Foo // { // public class Bar<T> // { // } // } // namespace Foo2 // { // public class Main // { // $$ // } // } // In such case, user might want to type Bar<string> and still want 'using Foo'. // We shouldn't try to filter the CompletionItem for Bar<T> later. // so just ignore the Bar<int> here. var typeParameter = target.GetTypeParameters(); if (typeParameter.IsEmpty) { var namespaceOfTarget = target.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.NameFormat); var typeNameOfTarget = target.Name; dictionary.Add(namespaceOfTarget, typeNameOfTarget); } } } return dictionary; } private static void AddItems( ImmutableArray<CompletionItem> items, CompletionContext completionContext, HashSet<string> namespacesInScope, MultiDictionary<string, string> aliasTargetNamespaceToTypeNameMap, TelemetryCounter counter) { counter.ReferenceCount++; foreach (var item in items) { if (ShouldAddItem(item, namespacesInScope, aliasTargetNamespaceToTypeNameMap)) { // We can return cached item directly, item's span will be fixed by completion service. // On the other hand, because of this (i.e. mutating the span of cached item for each run), // the provider can not be used as a service by components that might be run in parallel // with completion, which would be a race. completionContext.AddItem(item); counter.ItemsCount++; } } static bool ShouldAddItem( CompletionItem item, HashSet<string> namespacesInScope, MultiDictionary<string, string> aliasTargetNamespaceToTypeNameMap) { var containingNamespace = ImportCompletionItem.GetContainingNamespace(item); // 1. if the namespace of the item is in scoop. Don't add the item if (namespacesInScope.Contains(containingNamespace)) { return false; } // 2. If the item might be an alias target. First check if the target alias map has any value then // check if the type name is in the dictionary. // It is done in this way to avoid calling ImportCompletionItem.GetTypeName for all the CompletionItems if (!aliasTargetNamespaceToTypeNameMap.IsEmpty && aliasTargetNamespaceToTypeNameMap[containingNamespace].Contains(ImportCompletionItem.GetTypeName(item))) { return false; } return true; } } private class TelemetryCounter { protected int Tick { get; } public int ItemsCount { get; set; } public int ReferenceCount { get; set; } public bool CacheMiss { get; set; } public TelemetryCounter() => Tick = Environment.TickCount; public void Report() { if (CacheMiss) { CompletionProvidersLogger.LogTypeImportCompletionCacheMiss(); } else { var delta = Environment.TickCount - Tick; CompletionProvidersLogger.LogTypeImportCompletionTicksDataPoint(delta); CompletionProvidersLogger.LogTypeImportCompletionItemCountDataPoint(ItemsCount); CompletionProvidersLogger.LogTypeImportCompletionReferenceCountDataPoint(ReferenceCount); } } } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractTypeImportCompletionProvider<AliasDeclarationTypeNode> : AbstractImportCompletionProvider where AliasDeclarationTypeNode : SyntaxNode { protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsTypeContext; protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfTypeImportCompletionItem(); protected abstract ImmutableArray<AliasDeclarationTypeNode> GetAliasDeclarationNodes(SyntaxNode node); protected override async Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespacesInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_TypeImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var telemetryCounter = new TelemetryCounter(); var typeImportCompletionService = completionContext.Document.GetRequiredLanguageService<ITypeImportCompletionService>(); var itemsFromAllAssemblies = await typeImportCompletionService.GetAllTopLevelTypesAsync( completionContext.Document.Project, syntaxContext, forceCacheCreation: isExpandedCompletion, cancellationToken).ConfigureAwait(false); if (itemsFromAllAssemblies == null) { telemetryCounter.CacheMiss = true; } else { var aliasTargetNamespaceToTypeNameMap = GetAliasTypeDictionary(completionContext.Document, syntaxContext, cancellationToken); foreach (var items in itemsFromAllAssemblies) { AddItems(items, completionContext, namespacesInScope, aliasTargetNamespaceToTypeNameMap, telemetryCounter); } } telemetryCounter.Report(); } } /// <summary> /// Get a multi-Dictionary stores the information about the target of all alias Symbol in the syntax tree. /// Multiple aliases might live under same namespace. /// Key is the namespace of the symbol, value is the name of the symbol. /// </summary> private MultiDictionary<string, string> GetAliasTypeDictionary( Document document, SyntaxContext syntaxContext, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var dictionary = new MultiDictionary<string, string>(syntaxFactsService.StringComparer); var nodeToCheck = syntaxContext.LeftToken.Parent; if (nodeToCheck == null) { return dictionary; } // In case the caret is at the beginning of the file, take the root node. var aliasDeclarations = GetAliasDeclarationNodes(nodeToCheck); foreach (var aliasNode in aliasDeclarations) { var symbol = syntaxContext.SemanticModel.GetDeclaredSymbol(aliasNode, cancellationToken); if (symbol is IAliasSymbol { Target: ITypeSymbol { TypeKind: not TypeKind.Error } target }) { // If the target type is a type constructs from generics type, e.g. // using AliasBar = Bar<int> // namespace Foo // { // public class Bar<T> // { // } // } // namespace Foo2 // { // public class Main // { // $$ // } // } // In such case, user might want to type Bar<string> and still want 'using Foo'. // We shouldn't try to filter the CompletionItem for Bar<T> later. // so just ignore the Bar<int> here. var typeParameter = target.GetTypeParameters(); if (typeParameter.IsEmpty) { var namespaceOfTarget = target.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.NameFormat); var typeNameOfTarget = target.Name; dictionary.Add(namespaceOfTarget, typeNameOfTarget); } } } return dictionary; } private static void AddItems( ImmutableArray<CompletionItem> items, CompletionContext completionContext, HashSet<string> namespacesInScope, MultiDictionary<string, string> aliasTargetNamespaceToTypeNameMap, TelemetryCounter counter) { counter.ReferenceCount++; foreach (var item in items) { if (ShouldAddItem(item, namespacesInScope, aliasTargetNamespaceToTypeNameMap)) { // We can return cached item directly, item's span will be fixed by completion service. // On the other hand, because of this (i.e. mutating the span of cached item for each run), // the provider can not be used as a service by components that might be run in parallel // with completion, which would be a race. completionContext.AddItem(item); counter.ItemsCount++; } } static bool ShouldAddItem( CompletionItem item, HashSet<string> namespacesInScope, MultiDictionary<string, string> aliasTargetNamespaceToTypeNameMap) { var containingNamespace = ImportCompletionItem.GetContainingNamespace(item); // 1. if the namespace of the item is in scoop. Don't add the item if (namespacesInScope.Contains(containingNamespace)) { return false; } // 2. If the item might be an alias target. First check if the target alias map has any value then // check if the type name is in the dictionary. // It is done in this way to avoid calling ImportCompletionItem.GetTypeName for all the CompletionItems if (!aliasTargetNamespaceToTypeNameMap.IsEmpty && aliasTargetNamespaceToTypeNameMap[containingNamespace].Contains(ImportCompletionItem.GetTypeName(item))) { return false; } return true; } } private class TelemetryCounter { protected int Tick { get; } public int ItemsCount { get; set; } public int ReferenceCount { get; set; } public bool CacheMiss { get; set; } public TelemetryCounter() => Tick = Environment.TickCount; public void Report() { if (CacheMiss) { CompletionProvidersLogger.LogTypeImportCompletionCacheMiss(); } else { var delta = Environment.TickCount - Tick; CompletionProvidersLogger.LogTypeImportCompletionTicksDataPoint(delta); CompletionProvidersLogger.LogTypeImportCompletionItemCountDataPoint(ItemsCount); CompletionProvidersLogger.LogTypeImportCompletionReferenceCountDataPoint(ReferenceCount); } } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.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 System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.PdbUtilities; using static Roslyn.Test.Utilities.SigningTestHelpers; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ExpressionCompilerTests : ExpressionCompilerTestBase { /// <summary> /// Each assembly should have a unique MVID and assembly name. /// </summary> [WorkItem(1029280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029280")] [Fact] public void UniqueModuleVersionId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var appDomain = new AppDomain(); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader); var context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); string error; var result = context.CompileExpression("1", out error); var mvid1 = result.Assembly.GetModuleVersionId(); var name1 = result.Assembly.GetAssemblyName(); Assert.NotEqual(mvid1, Guid.Empty); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); }); } [Fact] public void ParseError() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var result = context.CompileExpression("M(", out error); Assert.Null(result); Assert.Equal("error CS1026: ) expected", error); }); } /// <summary> /// Diagnostics should be formatted with the CurrentUICulture. /// </summary> [WorkItem(941599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941599")] [Fact] public void FormatterCultureInfo() { var previousCulture = Thread.CurrentThread.CurrentCulture; var previousUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE"); try { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( "M(", DkmEvaluationFlags.TreatAsExpression, NoAliases, CustomDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, preferredUICulture: null, testData: null); Assert.Null(result); Assert.Equal("LCID=1031, Code=1026", error); Assert.Empty(missingAssemblyIdentities); }); } finally { Thread.CurrentThread.CurrentUICulture = previousUICulture; Thread.CurrentThread.CurrentCulture = previousCulture; } } /// <summary> /// Compile should succeed if there are /// parse warnings but no errors. /// </summary> [Fact] public void ParseWarning() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { // (1,2): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity const string expr = "0l"; var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression(expr, out error, testData); Assert.NotNull(result.Assembly); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: ret }"); }); } /// <summary> /// Reference to local in another scope. /// </summary> [Fact] public void BindingError() { var source = @"class C { static void M(object o) { var a = new object[0]; foreach (var x in a) { M(x); } foreach (var y in a) { #line 999 M(y); } } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "y ?? x", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); } [Fact] public void EmitError() { var longName = new string('P', 1100); var source = @"class C { static void M(object o) { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: string.Format("new {{ {0} = o }}", longName), resultProperties: out resultProperties, error: out error); Assert.Equal(error, string.Format("error CS7013: Name '<{0}>i__Field' exceeds the maximum length allowed in metadata.", longName)); } [Fact] public void NoSymbols() { var source = @"class C { static object F(object o) { return o; } static void M(int x) { int y = x + 1; } }"; var compilation0 = CSharpTestBase.CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0, debugFormat: 0); foreach (var module in runtime.Modules) { Assert.Null(module.SymReader); } var context = CreateMethodContext( runtime, methodName: "C.M"); // Local reference. string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F(y)", out error, testData); Assert.Equal("error CS0103: The name 'y' does not exist in the current context", error); // No local reference. testData = new CompilationTestData(); result = context.CompileExpression("F(x)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: box ""int"" IL_0006: call ""object C.F(object)"" IL_000b: ret }"); } /// <summary> /// Reuse Compilation if references match, and reuse entire /// EvaluationContext if references and local scopes match. /// </summary> [Fact] public void ReuseEvaluationContext() { var sourceA = @"public interface I { }"; var sourceB = @"class C { static void F(I o) { object x = 1; if (o == null) { object y = 2; y = x; } else { object z; } x = 3; } static void G() { } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll); var referenceA = compilationA.EmitToImageReference(); var compilationB = CreateCompilation( sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA }); const int methodVersion = 1; var referencesB = new[] { MscorlibRef, referenceA }; var moduleB = compilationB.ToModuleInstance(); var appDomain = new AppDomain(); int startOffset; int endOffset; var runtime = CreateRuntimeInstance(moduleB, referencesB); ImmutableArray<MetadataBlock> typeBlocks; ImmutableArray<MetadataBlock> methodBlocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); // Get non-empty scopes. var scopes = symReader.GetScopes(methodToken, methodVersion, EvaluationContext.IsLocalScopeEndInclusive).WhereAsArray(s => s.Locals.Length > 0); Assert.True(scopes.Length >= 3); var outerScope = scopes.First(s => s.Locals.Contains("x")); startOffset = outerScope.StartOffset; endOffset = outerScope.EndOffset - 1; // At start of outer scope. var context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)startOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); // At end of outer scope - not reused because of the nested scope. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); // Not required, just documentary. // At type context. previous = appDomain.GetMetadataContext(); context = CreateTypeContext(appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.Null(context.MethodContextReuseConstraints); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); // Step through entire method. var previousScope = (Scope)null; previous = appDomain.GetMetadataContext(); for (int offset = startOffset; offset <= endOffset; offset++) { var scope = scopes.GetInnermostScope(offset); var constraints = GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints; if (constraints.HasValue) { Assert.Equal(scope == previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset)); } context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)offset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); var previousEvaluationContext = GetMetadataContext(previous).EvaluationContext; if (scope == previousScope) { Assert.Equal(context, previousEvaluationContext); } else { // Different scope. Should reuse compilation. Assert.NotEqual(context, previousEvaluationContext); if (previousEvaluationContext != null) { Assert.NotEqual(context.MethodContextReuseConstraints, previousEvaluationContext.MethodContextReuseConstraints); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); } } previousScope = scope; previous = appDomain.GetMetadataContext(); } // With different references. var fewerReferences = new[] { MscorlibRef }; runtime = CreateRuntimeInstance(moduleB, fewerReferences); GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); // Different references. No reuse. context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, endOffset)); Assert.NotEqual(context.Compilation, GetMetadataContext(previous).Compilation); previous = appDomain.GetMetadataContext(); // Different method. Should reuse Compilation. GetContextState(runtime, "C.G", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, 0)); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); // No EvaluationContext. Should reuse Compilation appDomain.SetMetadataContext(SetMetadataContext(previous, default(Guid), new CSharpMetadataContext(GetMetadataContext(previous).Compilation))); previous = appDomain.GetMetadataContext(); Assert.Null(GetMetadataContext(previous).EvaluationContext); Assert.NotNull(GetMetadataContext(previous).Compilation); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.Null(GetMetadataContext(previous).EvaluationContext); Assert.NotNull(context); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); } /// <summary> /// Allow trailing semicolon after expression. This is to support /// copy/paste of (simple cases of) RHS of assignment in Watch window, /// not to allow arbitrary syntax after the semicolon, not even comments. /// </summary> [WorkItem(950242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/950242")] [Fact] public void TrailingSemicolon() { var source = @"class C { static object F(string x, string y) { return x; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F"); string error; var result = context.CompileExpression("x;", out error); Assert.Null(error); result = context.CompileExpression("x \t;\t ", out error); Assert.Null(error); // Multiple semicolons: not supported. result = context.CompileExpression("x;;", out error); Assert.Equal("error CS1073: Unexpected token ';'", error); // // comments. result = context.CompileExpression("x;//", out error); Assert.Equal("error CS0726: ';//' is not a valid format specifier", error); result = context.CompileExpression("x//;", out error); Assert.Null(error); // /*...*/ comments. result = context.CompileExpression("x/*...*/", out error); Assert.Null(error); result = context.CompileExpression("x/*;*/", out error); Assert.Null(error); result = context.CompileExpression("x;/*...*/", out error); Assert.Equal("error CS0726: ';/*...*/' is not a valid format specifier", error); result = context.CompileExpression("x/*...*/;", out error); Assert.Null(error); // Trailing semicolon, no expression. result = context.CompileExpression(" ; ", out error); Assert.Equal("error CS1733: Expected expression", error); }); } [Fact] public void FormatSpecifiers() { var source = @"class C { static object F(string x, string y) { return x; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F"); string error; // No format specifiers. var result = context.CompileExpression("x", out error); CheckFormatSpecifiers(result); // Format specifiers on expression. result = context.CompileExpression("x,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x y", out error); Assert.Equal("error CS0726: 'y' is not a valid format specifier", error); result = context.CompileExpression("x yy zz", out error); Assert.Equal("error CS0726: 'yy' is not a valid format specifier", error); result = context.CompileExpression("x,,y", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,yy,zz,ww", out error); CheckFormatSpecifiers(result, "yy", "zz", "ww"); result = context.CompileExpression("x, y z", out error); Assert.Equal("error CS0726: 'z' is not a valid format specifier", error); result = context.CompileExpression("x, y , z ", out error); CheckFormatSpecifiers(result, "y", "z"); result = context.CompileExpression("x, y, z,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,y,z;w", out error); Assert.Equal("error CS0726: 'z;w' is not a valid format specifier", error); result = context.CompileExpression("x, y;, z", out error); Assert.Equal("error CS0726: 'y;' is not a valid format specifier", error); // Format specifiers after // comment: ignored. result = context.CompileExpression("x // ,f", out error); CheckFormatSpecifiers(result); // Format specifiers after /*...*/ comment. result = context.CompileExpression("x /*,f*/, g, h", out error); CheckFormatSpecifiers(result, "g", "h"); // Format specifiers on assignment value. result = context.CompileAssignment("x", "null, y", out error); Assert.Null(result); Assert.Equal("error CS1073: Unexpected token ','", error); // Trailing semicolon, no format specifiers. result = context.CompileExpression("x; ", out error); CheckFormatSpecifiers(result); // Format specifiers, no expression. result = context.CompileExpression(",f", out error); Assert.Equal("error CS1525: Invalid expression term ','", error); // Format specifiers before semicolon: not supported. result = context.CompileExpression("x,f;\t", out error); Assert.Equal("error CS1073: Unexpected token ','", error); // Format specifiers after semicolon: not supported. result = context.CompileExpression("x;,f", out error); Assert.Equal("error CS0726: ';' is not a valid format specifier", error); result = context.CompileExpression("x; f, g", out error); Assert.Equal("error CS0726: ';' is not a valid format specifier", error); }); } private static void CheckFormatSpecifiers(CompileResult result, params string[] formatSpecifiers) { Assert.NotNull(result.Assembly); if (formatSpecifiers.Length == 0) { Assert.Null(result.FormatSpecifiers); } else { Assert.Equal(formatSpecifiers, result.FormatSpecifiers); } } /// <summary> /// Locals in generated method should account for /// temporary slots in the original method. Also, some /// temporaries may not be included in any scope. /// </summary> [Fact] public void IncludeTemporarySlots() { var source = @"class C { static string F(int[] a) { lock (new C()) { #line 999 string s = a[0].ToString(); return s; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("a[0]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (C V_0, bool V_1, string V_2, //s string V_3) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.i4 IL_0003: ret }"); }); } [Fact] public void EvaluateThis() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f) { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this.F() ?? this.G ?? this.P", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""object B.F()"" IL_0006: dup IL_0007: brtrue.s IL_001a IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""object B.G"" IL_0010: dup IL_0011: brtrue.s IL_001a IL_0013: pop IL_0014: ldarg.0 IL_0015: callvirt ""object B.P.get"" IL_001a: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(this.F)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldvirtftn ""object B.F()"" IL_0008: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000d: call ""object B.F(System.Func<object>)"" IL_0012: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(new System.Func<object>(this.F))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldvirtftn ""object B.F()"" IL_0008: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000d: call ""object B.F(System.Func<object>)"" IL_0012: ret }"); }); } [Fact] public void EvaluateBase() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f) { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("base.F() ?? base.G ?? base.P", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object A.F()"" IL_0006: dup IL_0007: brtrue.s IL_001a IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""object A.G"" IL_0010: dup IL_0011: brtrue.s IL_001a IL_0013: pop IL_0014: ldarg.0 IL_0015: call ""object A.P.get"" IL_001a: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(base.F)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""object A.F()"" IL_0007: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000c: call ""object B.F(System.Func<object>)"" IL_0011: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(new System.Func<object>(base.F))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""object A.F()"" IL_0007: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000c: call ""object B.F(System.Func<object>)"" IL_0011: ret }"); }); } /// <summary> /// If "this" is a struct, the generated parameter /// should be passed by reference. /// </summary> [Fact] public void EvaluateStructThis() { var source = @"struct S { static object F(object x, object y) { return null; } object x; void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "F(this, this.x)"); var methodData = testData.GetMethodData("<>x.<>m0(ref S)"); var parameter = ((MethodSymbol)methodData.Method).Parameters[0]; Assert.Equal(RefKind.Ref, parameter.RefKind); methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: ldarg.0 IL_000c: ldfld ""object S.x"" IL_0011: call ""object S.F(object, object)"" IL_0016: ret }"); } [Fact] public void EvaluateStaticMethodParameters() { var source = @"class C { static object F(int x, int y) { return x + y; } static void M(int x, int y) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(y, x)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""object C.F(int, int)"" IL_0007: ret }"); } [Fact] public void EvaluateInstanceMethodParametersAndLocals() { var source = @"class C { object F(int x) { return x; } void M(int x) { #line 999 int y = 1; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "F(x + y)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 3 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldloc.0 IL_0003: add IL_0004: callvirt ""object C.F(int)"" IL_0009: ret }"); } [Fact] public void EvaluateLocals() { var source = @"class C { static void M() { int x = 1; if (x < 0) { int y = 2; } else { #line 999 int z = 3; } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "x + z"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0, //x bool V_1, int V_2, int V_3) //z IL_0000: ldloc.0 IL_0001: ldloc.3 IL_0002: add IL_0003: ret }"); } [Fact] public void EvaluateForEachLocal() { var source = @"class C { static bool F(object[] args) { if (args == null) { return true; } foreach (var o in args) { #line 999 } return false; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.F", atLineNumber: 999, expr: "o"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (bool V_0, bool V_1, object[] V_2, int V_3, object V_4) //o IL_0000: ldloc.s V_4 IL_0002: ret }"); } /// <summary> /// Generated "this" parameter should not /// conflict with existing "@this" parameter. /// </summary> [Fact] public void ParameterNamedThis() { var source = @"class C { object M(C @this) { return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "@this.M(this)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object C.M(C)"" IL_0007: ret }"); } /// <summary> /// Generated "this" parameter should not /// conflict with existing "@this" local. /// </summary> [Fact] public void LocalNamedThis() { var source = @"class C { object M(object o) { var @this = this; return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "@this.M(this)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (C V_0, //this object V_1) IL_0000: ldloc.0 IL_0001: ldarg.0 IL_0002: callvirt ""object C.M(object)"" IL_0007: ret }"); } [Fact] public void ByRefParameter() { var source = @"class C { static object M(out object x) { object y; x = null; return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "M(out y)"); var methodData = testData.GetMethodData("<>x.<>m0(out object)"); var parameter = ((MethodSymbol)methodData.Method).Parameters[0]; Assert.Equal(RefKind.Out, parameter.RefKind); methodData.VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 .locals init (object V_0, //y object V_1) IL_0000: ldloca.s V_0 IL_0002: call ""object C.M(out object)"" IL_0007: ret }"); } /// <summary> /// Method defined in IL where PDB does not /// contain C# custom metadata. /// </summary> [Fact] public void LocalType_FromIL() { var source = @".class public C { .method public specialname rtspecialname instance void .ctor() { ret } .field public object F; .method public static void M() { .locals init ([0] class C c) ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.F", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (C V_0) //c IL_0000: ldloc.0 IL_0001: ldfld ""object C.F"" IL_0006: ret }"); } /// <summary> /// Allow locals with optional custom modifiers. /// </summary> /// <remarks> /// The custom modifiers are not copied to the corresponding /// local in the generated method since there is no need. /// </remarks> [WorkItem(884627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884627")] [Fact] public void LocalType_CustomModifiers() { var source = @".class public C { .method public specialname rtspecialname instance void .ctor() { ret } .field public object F; .method public static void M() { .locals init ([0] class C modopt(int32) modopt(object) c) ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.F", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); var local = locals[0]; Assert.Equal("C", local.Type.ToString()); Assert.Equal(0, local.CustomModifiers.Length); // Custom modifiers are not copied. methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (C V_0) //c IL_0000: ldloc.0 IL_0001: ldfld ""object C.F"" IL_0006: ret }"); } [WorkItem(1012956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1012956")] [Fact] public void LocalType_ByRefOrPinned() { var source = @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .method private hidebysig static void M(string s, int32[] a) cil managed { // Code size 73 (0x49) .maxstack 2 .locals init ([0] string pinned s, [1] int32& pinned f, [2] int32& i) ret } } "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("s", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 2 (0x2) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.0 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileAssignment("s", "\"hello\"", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ret }"); testData = new CompilationTestData(); context.CompileExpression("f", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 2 (0x2) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.1 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileAssignment("f", "1", out error, testData); Assert.Equal("error CS1656: Cannot assign to 'f' because it is a 'fixed variable'", error); testData = new CompilationTestData(); context.CompileExpression("i", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.2 IL_0001: ldind.i4 IL_0002: ret }"); testData = new CompilationTestData(); context.CompileAssignment("i", "1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.2 IL_0001: ldc.i4.1 IL_0002: stind.i4 IL_0003: ret }"); } [Fact] public void LocalType_FixedVariable() { var source = @"class C { static int x; static unsafe void M(string s, int[] a) { fixed (char* p1 = s) { fixed (int* p2 = &x) { fixed (void* p3 = a) { #line 999 int y = x + 1; } } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("(int)p1[0] + p2[0] + ((int*)p3)[0]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 2 .locals init (char* V_0, //p1 pinned string V_1, int* V_2, //p2 pinned int& V_3, void* V_4, //p3 pinned int[] V_5, int V_6) //y IL_0000: ldloc.0 IL_0001: ldind.u2 IL_0002: ldloc.2 IL_0003: ldind.i4 IL_0004: add IL_0005: ldloc.s V_4 IL_0007: ldind.i4 IL_0008: add IL_0009: ret }"); }); } [WorkItem(1034549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034549")] [Fact] public void AssignLocal() { var source = @"class C { static void M() { int x = 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "x", expr: "1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ret }"); // Assign to a local, as above, but in an expression. testData = new CompilationTestData(); context.CompileExpression( expr: "x = 1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: dup IL_0002: stloc.0 IL_0003: ret }"); }); } [Fact] public void AssignInstanceMethodParametersAndLocals() { var source = @"class C { object[] a; static int F(int x) { return x; } void M(int x) { int y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "this.a[F(x)]", expr: "this.a[y]", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldfld ""object[] C.a"" IL_0006: ldarg.1 IL_0007: call ""int C.F(int)"" IL_000c: ldarg.0 IL_000d: ldfld ""object[] C.a"" IL_0012: ldloc.0 IL_0013: ldelem.ref IL_0014: stelem.ref IL_0015: ret }"); }); } [Fact] public void EvaluateNull() { var source = @"class C { static void M() { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "null", resultProperties: out resultProperties, error: out error); Assert.Equal(DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); var methodData = testData.GetMethodData("<>x.<>m0"); var method = (MethodSymbol)methodData.Method; Assert.Equal(SpecialType.System_Object, method.ReturnType.SpecialType); Assert.False(method.ReturnsVoid); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void MayHaveSideEffects() { var source = @"using System; using System.Diagnostics.Contracts; class C { object F() { return 1; } [Pure] object G() { return 2; } object P { get; set; } static object H() { return 3; } static void M(C o, int i) { ((dynamic)o).G(); } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); CheckResultFlags(context, "o.F()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); // Calls to methods are reported as having side effects, even if // the method is marked [Pure]. This matches the native EE. CheckResultFlags(context, "o.G()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "o.P", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "o.P = 2", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "((dynamic)o).G()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "(Action)(() => { })", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "++i", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "--i", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i++", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i--", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i += 2", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i *= 3", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C() { P = 1 }", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C() { P = H() }", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); }); } [Fact] public void IsAssignable() { var source = @" using System; class C { int F; readonly int RF; const int CF = 1; event System.Action E; event System.Action CE { add { } remove { } } int RP { get { return 0; } } int WP { set { } } int RWP { get; set; } int this[int x] { get { return 0; } } int this[int x, int y] { set { } } int this[int x, int y, int z] { get { return 0; } set { } } int M() { return 0; } } "; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); CheckResultFlags(context, "F", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "RF", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "CF", DkmClrCompilationResultFlags.ReadOnlyResult); // Note: flags are always None in error cases. // CheckResultFlags(context, "E", DkmClrCompilationResultFlags.None); // TODO: DevDiv #1055825 CheckResultFlags(context, "CE", DkmClrCompilationResultFlags.None, "error CS0079: The event 'C.CE' can only appear on the left hand side of += or -="); CheckResultFlags(context, "RP", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "WP", DkmClrCompilationResultFlags.None, "error CS0154: The property or indexer 'C.WP' cannot be used in this context because it lacks the get accessor"); CheckResultFlags(context, "RWP", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "this[1]", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "this[1, 2]", DkmClrCompilationResultFlags.None, "error CS0154: The property or indexer 'C.this[int, int]' cannot be used in this context because it lacks the get accessor"); CheckResultFlags(context, "this[1, 2, 3]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "M()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "null", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "1", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "M", DkmClrCompilationResultFlags.None, "error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?"); CheckResultFlags(context, "typeof(C)", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C()", DkmClrCompilationResultFlags.ReadOnlyResult); }); } [Fact] public void IsAssignable_Array() { var source = @" using System; class C { readonly int[] RF = new int[1]; int[] rp = new int[2]; int[] RP { get { return rp; } } int[] m = new int[3]; int[] M() { return m; } } "; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); CheckResultFlags(context, "RF", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "RF[0]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "RP", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "RP[0]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "M()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "M()[0]", DkmClrCompilationResultFlags.PotentialSideEffect); }); } private static void CheckResultFlags(EvaluationContext context, string expr, DkmClrCompilationResultFlags expectedFlags, string expectedError = null) { ResultProperties resultProperties; string error; var testData = new CompilationTestData(); var result = context.CompileExpression(expr, out resultProperties, out error, testData); Assert.Equal(expectedError, error); Assert.NotEqual(expectedError == null, result == null); Assert.Equal(expectedFlags, resultProperties.Flags); } /// <summary> /// Set BooleanResult for bool expressions. /// </summary> [Fact] public void EvaluateBooleanExpression() { var source = @"class C { static bool F() { return false; } static void M(bool x, bool? y) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; context.CompileExpression("x", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.BoolResult, resultProperties.Flags); context.CompileExpression("y", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); context.CompileExpression("(bool)y", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult); context.CompileExpression("!y", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); context.CompileExpression("false", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult); context.CompileExpression("F()", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult | DkmClrCompilationResultFlags.PotentialSideEffect); }); } /// <summary> /// Expression that is not an rvalue. /// </summary> [Fact] public void EvaluateNonRValueExpression() { var source = @"class C { object P { set { } } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "P", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor", error); } /// <summary> /// Expression that does not return a value. /// </summary> [Fact] public void EvaluateVoidExpression() { var source = @"class C { void M() { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.M()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); var methodData = testData.GetMethodData("<>x.<>m0"); var method = (MethodSymbol)methodData.Method; Assert.Equal(SpecialType.System_Void, method.ReturnType.SpecialType); Assert.True(method.ReturnsVoid); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""void C.M()"" IL_0006: ret }"); } [Fact] public void EvaluateMethodGroup() { var source = @"class C { void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.M", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?", error); } [Fact] public void AssignMethodGroup() { var source = @"class C { static void M() { object o; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "M", error: out error, testData: testData); Assert.Equal("error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?", error); }); } [Fact] public void EvaluateConstant() { var source = @"class C { static void M() { const string x = ""str""; const int y = 2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("x[y]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 2 IL_0000: ldstr ""str"" IL_0005: ldc.i4.2 IL_0006: call ""char string.this[int].get"" IL_000b: ret }"); }); } [Fact] public void AssignToConstant() { var source = @"class C { static void M() { const int x = 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "x", expr: "2", error: out error, testData: testData); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [Fact] public void AssignOutParameter() { var source = @"class C { static void F<T>(System.Func<T> f) { } static void M1(out int x) { x = 1; } static void M2<T>(ref T y) { y = default(T); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M1"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "x", expr: "2", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: stind.i4 IL_0003: ret }"); context = CreateMethodContext( runtime, methodName: "C.M2"); testData = new CompilationTestData(); context.CompileAssignment( target: "y", expr: "default(T)", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: initobj ""T"" IL_0007: ret }"); testData = new CompilationTestData(); context.CompileExpression( expr: "F(() => y)", error: out error, testData: testData); Assert.Equal("error CS1628: Cannot use ref, out, or in parameter 'y' inside an anonymous method, lambda expression, query expression, or local function", error); }); } [Fact] public void EvaluateNamespace() { var source = @"namespace N { class C { static void M() { } } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.C.M", expr: "N", resultProperties: out resultProperties, error: out error); // Note: The native EE reports "CS0119: 'N' is a namespace, which is not valid in the given context" Assert.Equal("error CS0118: 'N' is a namespace but is used like a variable", error); } [Fact] public void EvaluateType() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "C", resultProperties: out resultProperties, error: out error); // The native EE returns a representation of the type (but not System.Type) // that the user can expand to see the base type. To enable similar // behavior, the expression compiler would probably return something // other than IL. Instead, we disallow this scenario. Assert.Equal("error CS0119: 'C' is a type, which is not valid in the given context", error); } [Fact] public void EvaluateObjectAddress() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( "@0x123 ?? @0xa1b2c3 ?? (object)$exception ?? @0XA1B2C3.GetHashCode()", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(ExceptionAlias()), out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 61 (0x3d) .maxstack 2 IL_0000: ldc.i4 0x123 IL_0005: conv.i8 IL_0006: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_000b: dup IL_000c: brtrue.s IL_003c IL_000e: pop IL_000f: ldc.i4 0xa1b2c3 IL_0014: conv.i8 IL_0015: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_001a: dup IL_001b: brtrue.s IL_003c IL_001d: pop IL_001e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0023: dup IL_0024: brtrue.s IL_003c IL_0026: pop IL_0027: ldc.i4 0xa1b2c3 IL_002c: conv.i8 IL_002d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_0032: callvirt ""int object.GetHashCode()"" IL_0037: box ""int"" IL_003c: ret }"); testData = new CompilationTestData(); // Report overflow, even though native EE does not. context.CompileExpression( "@0xffff0000ffff0000ffff0000", out error, testData); Assert.Equal("error CS1021: Integral constant is too large", error); }); } [WorkItem(986227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/986227")] [Fact] public void RewriteCatchLocal() { var source = @"using System; class E<T> : Exception { } class C<T> { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: @"((Func<E<T>>)(() => { E<T> e1 = null; try { string.Empty.ToString(); } catch (E<T> e2) { e1 = e2; } catch { } return e1; }))()", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x<T>.<>c.<<>m0>b__0_0"); var method = (MethodSymbol)methodData.Method; var containingType = method.ContainingType; var returnType = (NamedTypeSymbol)method.ReturnType; // Return type E<T> with type argument T from <>c<T>. Assert.Equal(returnType.TypeArguments()[0].ContainingSymbol, containingType.ContainingType); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); Assert.Equal(1, locals.Length); // All locals of type E<T> with type argument T from <>c<T>. foreach (var local in locals) { var localType = (NamedTypeSymbol)local.Type.GetInternalSymbol(); var typeArg = localType.TypeArguments()[0]; Assert.Equal(typeArg.ContainingSymbol, containingType.ContainingType); } methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 1 .locals init (E<T> V_0) //e1 IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldsfld ""string string.Empty"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: leave.s IL_0015 } catch E<T> { IL_000f: stloc.0 IL_0010: leave.s IL_0015 } catch object { IL_0012: pop IL_0013: leave.s IL_0015 } IL_0015: ldloc.0 IL_0016: ret }"); }); } [WorkItem(986227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/986227")] [Fact] public void RewriteSequenceTemps() { var source = @"class C { object F; static void M<T>() where T : C, new() { T t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: "new T() { F = 1 }", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x.<>m0<T>()"); var method = (MethodSymbol)methodData.Method; var returnType = method.ReturnTypeWithAnnotations; Assert.Equal(TypeKind.TypeParameter, returnType.TypeKind); Assert.Equal(returnType.Type.ContainingSymbol, method); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); // The original local of type T from <>m0<T>. Assert.Equal(1, locals.Length); foreach (var local in locals) { var localType = (TypeSymbol)local.Type.GetInternalSymbol(); Assert.Equal(localType.ContainingSymbol, method); } methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 3 .locals init (T V_0) //t IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: stfld ""object C.F"" IL_0016: ret }"); }); } [Fact] public void GenericWithInterfaceConstraint() { var source = @"public interface I { string Key { get; set; } } class C { public static void M<T>(T t) where T : I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: "t.Key", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x.<>m0<T>(T)"); var method = (MethodSymbol)methodData.Method; Assert.Equal(1, method.Parameters.Length); var eeTypeParameterSymbol = (EETypeParameterSymbol)method.Parameters[0].Type; Assert.Equal(1, eeTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics.Length); Assert.Equal("I", eeTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics[0].Name); methodData.VerifyIL( @"{ // Code size 14 (0xe) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: constrained. ""T"" IL_0008: callvirt ""string I.Key.get"" IL_000d: ret }"); }); } [Fact] public void AssignEmitError() { var longName = new string('P', 1100); var source = @"class C { static void M(object o) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: string.Format("new {{ {0} = 1 }}", longName), error: out error, testData: testData); Assert.Equal(error, string.Format("error CS7013: Name '<{0}>i__Field' exceeds the maximum length allowed in metadata.", longName)); }); } /// <summary> /// Attempt to assign where the rvalue is not an rvalue. /// </summary> [Fact] public void AssignVoidExpression() { var source = @"class C { static void M() { object o; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "M()", error: out error, testData: testData); Assert.Equal("error CS0029: Cannot implicitly convert type 'void' to 'object'", error); }); } [Fact] public void AssignUnsafeExpression() { var source = @"class C { static unsafe void M(int *p) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "p[1]", expr: "p[0] + 1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.4 IL_0002: add IL_0003: ldarg.0 IL_0004: ldind.i4 IL_0005: ldc.i4.1 IL_0006: add IL_0007: stind.i4 IL_0008: ret }"); }); } /// <remarks> /// This is interesting because we're always in an unsafe context in /// the expression compiler and so an await expression would not /// normally be allowed. /// </remarks> [WorkItem(1075258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075258")] [Fact] public void Await() { var source = @" using System; using System.Threading.Tasks; class C { static async Task<object> F() { return null; } static void G(Func<Task<object>> f) { } static void Main() { } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); context.CompileExpression("G(async() => await F())", out error, testData); Assert.Null(error); }); } /// <remarks> /// This would be illegal in any non-debugger context. /// </remarks> [WorkItem(1075258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075258")] [Fact] public void AwaitInUnsafeContext() { var source = @" using System; using System.Threading.Tasks; class C { static async Task<object> F() { return null; } static void G(Func<Task<object>> f) { } static void Main() { } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); context.CompileExpression(@"G(async() => { unsafe { return await F(); } })", out error, testData); Assert.Null(error); }); } /// <summary> /// Flow analysis should catch definite assignment errors /// for variables declared within the expression. /// </summary> [WorkItem(549, "https://github.com/dotnet/roslyn/issues/549")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/549")] public void FlowAnalysis() { var source = @"class C { static void M(bool b) { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object>)(() => { object o; if (b) o = 1; return o; }))()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0165: Use of unassigned local variable 'o'", error); } /// <summary> /// Should be possible to evaluate an expression /// of a type that the compiler does not normally /// support as a return value. /// </summary> [Fact] public void EvaluateRestrictedTypeExpression() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new System.RuntimeArgumentHandle()"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 1 .locals init (System.RuntimeArgumentHandle V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.RuntimeArgumentHandle"" IL_0008: ldloc.0 IL_0009: ret }"); } [Fact] public void NestedNamespacesAndTypes() { var source = @"namespace N { namespace M { class A { class B { static object F() { return null; } } } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.M.A.B.F", expr: "F()"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (object V_0) IL_0000: call ""object N.M.A.B.F()"" IL_0005: ret }"); } [Fact] public void GenericMethod() { var source = @"class A<T> { class B<U, V> where V : U { static void M1<W, X>() where X : A<W>.B<object, U[]> { var t = default(T); var w = default(W); } static void M2() { var t = default(T); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "A.B.M1"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("(object)t ?? (object)w ?? typeof(V) ?? typeof(X)", out error, testData); var methodData = testData.GetMethodData("<>x<T, U, V>.<>m0<W, X>"); methodData.VerifyIL( @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, //t W V_1) //w IL_0000: ldloc.0 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_002c IL_0009: pop IL_000a: ldloc.1 IL_000b: box ""W"" IL_0010: dup IL_0011: brtrue.s IL_002c IL_0013: pop IL_0014: ldtoken ""V"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: dup IL_001f: brtrue.s IL_002c IL_0021: pop IL_0022: ldtoken ""X"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ret }"); // Verify generated type and method are generic. Assert.Equal(Cci.CallingConvention.Generic, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly)); var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef(result.TypeName); reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U", "V"); var methodDef = reader.GetMethodDef(typeDef, result.MethodName); reader.CheckTypeParameters(methodDef.GetGenericParameters(), "W", "X"); context = CreateMethodContext( runtime, methodName: "A.B.M2"); testData = new CompilationTestData(); context.CompileExpression("(object)t ?? typeof(T) ?? typeof(U)", out error, testData); methodData = testData.GetMethodData("<>x<T, U, V>.<>m0"); Assert.Equal(Cci.CallingConvention.Default, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [Fact] public void GenericClosureClass() { var source = @"using System; class C<T> { static U F<U>(Func<U> f) { return f(); } U M<U>(U u) { return u; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => this.M(u))", out error, testData); var methodData = testData.GetMethodData("<>x<T>.<>m0<U>"); methodData.VerifyIL(@" { // Code size 36 (0x24) .maxstack 3 .locals init (U V_0) IL_0000: newobj ""<>x<T>.<>c__DisplayClass0_0<U>..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""C<T> <>x<T>.<>c__DisplayClass0_0<U>.<>4__this"" IL_000c: dup IL_000d: ldarg.1 IL_000e: stfld ""U <>x<T>.<>c__DisplayClass0_0<U>.u"" IL_0013: ldftn ""U <>x<T>.<>c__DisplayClass0_0<U>.<<>m0>b__0()"" IL_0019: newobj ""System.Func<U>..ctor(object, System.IntPtr)"" IL_001e: call ""U C<T>.F<U>(System.Func<U>)"" IL_0023: ret }"); Assert.Equal(Cci.CallingConvention.Generic, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [WorkItem(976847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976847")] [Fact] public void VarArgMethod() { var source = @"class C { static void M(object o, __arglist) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new System.ArgIterator(__arglist)", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: arglist IL_0002: newobj ""System.ArgIterator..ctor(System.RuntimeArgumentHandle)"" IL_0007: ret }"); Assert.Equal(Cci.CallingConvention.ExtraArguments, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [Fact] public void EvaluateLambdaWithParameters() { var source = @"class C { static void M(object x, object y) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "((System.Func<object, object, object>)((a, b) => a ?? b))(x, y)"); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 39 (0x27) .maxstack 3 IL_0000: ldsfld ""System.Func<object, object, object> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""object <>x.<>c.<<>m0>b__0_0(object, object)"" IL_0014: newobj ""System.Func<object, object, object>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<object, object, object> <>x.<>c.<>9__0_0"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: callvirt ""object System.Func<object, object, object>.Invoke(object, object)"" IL_0026: ret }"); } [Fact] public void EvaluateLambdaWithLocals() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object>)(() => { int x = 1; if (x < 0) { int y = 2; return y; } else { int z = 3; return z; } }))()"); } /// <summary> /// Lambda expression containing names /// that shadow names outside expression. /// </summary> [Fact] public void EvaluateLambdaWithNameShadowing() { var source = @"class C { static void M(object x) { object y; } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object, object>)(y => { object x = y; return y; }))(x, y)", resultProperties: out resultProperties, error: out error); // Currently generating errors but this seems unnecessary and // an extra burden for the user. Consider allowing names // inside the expression that shadow names outside. Assert.Equal("error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter", error); } [Fact] public void EvaluateNestedLambdaClosedOverLocal() { var source = @"delegate object D(C c); class C { object F(D d) { return d(this); } static void Main(string[] args) { int x = 1; C y = new C(); } }"; var testData = Evaluate( source, OutputKind.ConsoleApplication, methodName: "C.Main", expr: "y.F(a => y.F(b => x))"); // Verify display class was included. testData.GetMethodData("<>x.<>c__DisplayClass0_0..ctor").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 3 .locals init (int V_0, //x C V_1, //y <>x.<>c__DisplayClass0_0 V_2) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: ldloc.1 IL_0008: stfld ""C <>x.<>c__DisplayClass0_0.y"" IL_000d: ldloc.2 IL_000e: ldloc.0 IL_000f: stfld ""int <>x.<>c__DisplayClass0_0.x"" IL_0014: ldloc.2 IL_0015: ldfld ""C <>x.<>c__DisplayClass0_0.y"" IL_001a: ldloc.2 IL_001b: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0(C)"" IL_0021: newobj ""D..ctor(object, System.IntPtr)"" IL_0026: callvirt ""object C.F(D)"" IL_002b: ret }"); } [Fact] public void EvaluateLambdaClosedOverThis() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f1, System.Func<object> f2, object g) { return null; } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => this.G))()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: ldfld ""object B.G"" IL_000b: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => this.F() ?? this.P))()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: callvirt ""object B.F()"" IL_000b: dup IL_000c: brtrue.s IL_001a IL_000e: pop IL_000f: ldarg.0 IL_0010: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0015: callvirt ""object B.P.get"" IL_001a: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => F(new System.Func<object>(this.F), this.F, this.G)))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: dup IL_0007: ldvirtftn ""object B.F()"" IL_000d: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0012: ldarg.0 IL_0013: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0018: dup IL_0019: ldvirtftn ""object B.F()"" IL_001f: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0024: ldarg.0 IL_0025: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_002a: ldfld ""object B.G"" IL_002f: call ""object B.F(System.Func<object>, System.Func<object>, object)"" IL_0034: ret }"); } [WorkItem(905986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/905986")] [Fact] public void EvaluateLambdaClosedOverBase() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f1, System.Func<object> f2, object g) { return null; } void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => base.F() ?? base.P))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: call ""object A.F()"" IL_000b: dup IL_000c: brtrue.s IL_001a IL_000e: pop IL_000f: ldarg.0 IL_0010: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0015: call ""object A.P.get"" IL_001a: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => F(new System.Func<object>(base.F), base.F, base.G)))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 51 (0x33) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: ldftn ""object A.F()"" IL_000c: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0017: ldftn ""object A.F()"" IL_001d: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0022: ldarg.0 IL_0023: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0028: ldfld ""object A.G"" IL_002d: call ""object B.F(System.Func<object>, System.Func<object>, object)"" IL_0032: ret }"); } [Fact] public void EvaluateCapturedLocalsAlreadyCaptured() { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M(object x) { object y = 1; F(() => this.F(x)); F(() => base.F(y)); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "B.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => this.F(x))", out error, testData); // Note there are duplicate local names (one from the original // display class, the other from the new display class in each case). // That is expected since we do not rename old locals nor do we // offset numbering of new locals. Having duplicate local names // in the PDB should be harmless though. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 3 .locals init (B.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0017: call ""void B.F(System.Func<object>)"" IL_001c: ret }"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0006: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" IL_000b: ldarg.0 IL_000c: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0011: ldfld ""object B.<>c__DisplayClass2_0.x"" IL_0016: callvirt ""object B.F(object)"" IL_001b: ret }"); testData = new CompilationTestData(); context.CompileExpression("F(() => base.F(y))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 3 .locals init (B.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0017: call ""void B.F(System.Func<object>)"" IL_001c: ret }"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0006: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" IL_000b: ldarg.0 IL_000c: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0011: ldfld ""object B.<>c__DisplayClass2_0.y"" IL_0016: call ""object A.F(object)"" IL_001b: ret }"); }); } [WorkItem(994485, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994485")] [Fact] public void Repro994485() { var source = @" using System; enum E { A } class C { Action M(E? e) { Action a = () => e.ToString(); E ee = e.Value; return a; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("e.HasValue", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Action V_1, //a E V_2, //ee System.Action V_3) IL_0000: ldloc.0 IL_0001: ldflda ""E? C.<>c__DisplayClass0_0.e"" IL_0006: call ""bool E?.HasValue.get"" IL_000b: ret }"); }); } [Theory] [MemberData(nameof(NonNullTypesTrueAndFalseDebugDll))] public void EvaluateCapturedLocalsOutsideLambda(CSharpCompilationOptions options) { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M<T>(object x) where T : A, new() { F(() => this.F(x)); if (x != null) { #line 999 var y = new T(); var z = 1; F(() => base.F(y)); } else { var w = 2; F(() => w); } } }"; var compilation0 = CreateCompilation(source, options: options); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "B.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("this.F(y)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 23 (0x17) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.2 IL_0007: ldfld ""T B.<>c__DisplayClass2_1<T>.y"" IL_000c: box ""T"" IL_0011: callvirt ""object B.F(object)"" IL_0016: ret }"); testData = new CompilationTestData(); context.CompileExpression("base.F(x)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.0 IL_0007: ldfld ""object B.<>c__DisplayClass2_0<T>.x"" IL_000c: call ""object A.F(object)"" IL_0011: ret }"); }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30767")] [WorkItem(30767, "https://github.com/dotnet/roslyn/issues/30767")] public void EvaluateCapturedLocalsOutsideLambda_PlusNullable() { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M<T>(object x) where T : A, new() { F(() => this.F(x)); if (x != null) { #line 999 var y = new T(); var z = 1; F(() => base.F(y)); } else { var w = 2; F(() => w); } } }"; var compilation0 = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugDll)); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "B.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("this.F(y)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 23 (0x17) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.2 IL_0007: ldfld ""T B.<>c__DisplayClass2_1<T>.y"" IL_000c: box ""T"" IL_0011: callvirt ""object B.F(object)"" IL_0016: ret }"); testData = new CompilationTestData(); context.CompileExpression("base.F(x)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.0 IL_0007: ldfld ""object B.<>c__DisplayClass2_0<T>.x"" IL_000c: call ""object A.F(object)"" IL_0011: ret }"); }); } [Fact] public void EvaluateCapturedLocalsInsideLambda() { var source = @"class C { static void F(System.Func<object> f) { f(); } void M(C x) { F(() => x ?? this); if (x != null) { var y = new C(); F(() => { var z = 1; return y ?? this; }); } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.<>c__DisplayClass1_1.<M>b__1", expr: "y ?? this ?? (object)z"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 32 (0x20) .maxstack 2 .locals init (int V_0, //z object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_1.y"" IL_0006: dup IL_0007: brtrue.s IL_001f IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""C.<>c__DisplayClass1_0 C.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_0010: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0015: dup IL_0016: brtrue.s IL_001f IL_0018: pop IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ret }"); } /// <summary> /// Values of existing locals must be copied to new display /// classes generated in the compiled expression. /// </summary> [Fact] public void CopyLocalsToDisplayClass() { var source = @"class C { static void F(System.Func<object> f) { f(); } void M(int p, int q) { int x = 1; if (p > 0) { #line 999 int y = 2; F(() => x + q); } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "F(() => x + y + p + q)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 43 (0x2b) .maxstack 3 .locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 bool V_1, int V_2) //y IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""C.<>c__DisplayClass1_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: dup IL_000d: ldloc.2 IL_000e: stfld ""int <>x.<>c__DisplayClass0_0.y"" IL_0013: dup IL_0014: ldarg.1 IL_0015: stfld ""int <>x.<>c__DisplayClass0_0.p"" IL_001a: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0020: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0025: call ""void C.F(System.Func<object>)"" IL_002a: ret }"); } [Fact] public void EvaluateNewAnonymousType() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new { A = 1, B = 2 }"); // Verify anonymous type was generated (find an // accessor of one of the generated properties). testData.GetMethodData("<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>.A.get").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""<A>j__TPar <>f__AnonymousType0<<A>j__TPar, <B>j__TPar>.<A>i__Field"" IL_0006: ret }"); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0007: ret }"); } [Fact] public void EvaluateExistingAnonymousType() { var source = @"class C { static object F() { return new { A = new { }, B = 2 }; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.F", expr: "new { A = 1, B = new { } }"); // Verify anonymous types were generated. (There // shouldn't be any reuse of existing anonymous types // since the existing types were from metadata.) var methods = testData.GetMethodsByName(); Assert.True(methods.ContainsKey("<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>..ctor(<A>j__TPar, <B>j__TPar)")); Assert.True(methods.ContainsKey("<>f__AnonymousType1..ctor()")); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 2 .locals init (object V_0) IL_0000: ldc.i4.1 IL_0001: newobj ""<>f__AnonymousType1..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<int, <empty anonymous type>>..ctor(int, <empty anonymous type>)"" IL_000b: ret }"); } /// <summary> /// Should re-use anonymous types from the module /// containing the current frame, so new instances can /// be used interchangeably with existing instances. /// </summary> [WorkItem(3188, "https://github.com/dotnet/roslyn/issues/3188")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/3188")] public void EvaluateExistingAnonymousType_2() { var source = @"class C { static void M() { var o = new { P = 1 }; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "o == new { P = 2 }"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ ... }"); } /// <summary> /// Generate PrivateImplementationDetails class /// for initializer expressions. /// </summary> [Fact] public void EvaluateInitializerExpression() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll.WithModuleName("MODULE")); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("new [] { 1, 2, 3, 4, 5 }", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int[]", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 3 IL_0000: ldc.i4.5 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=20 <PrivateImplementationDetails>.4F6ADDC9659D6FB90FE94B6688A79F2A1FA8D36EC43F8F3E1D9B6528C448A384"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: ret }"); }); } // Scenario from the lambda / anonymous type milestone. [Fact] public void EvaluateLINQExpression() { var source = @"using System.Collections.Generic; using System.Linq; class Employee { internal string Name; internal int Salary; internal List<Employee> Reports; } class Program { static void F(Employee mgr) { var o = mgr.Reports.Where(e => e.Salary < 100).Select(e => new { e.Name, e.Salary }).First(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "Program.F"); string error; var testData = new CompilationTestData(); context.CompileExpression("mgr.Reports.Where(e => e.Salary < 100).Select(e => new { e.Name, e.Salary }).First()", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 84 (0x54) .maxstack 3 .locals init (<>f__AnonymousType0<string, int> V_0) //o IL_0000: ldarg.0 IL_0001: ldfld ""System.Collections.Generic.List<Employee> Employee.Reports"" IL_0006: ldsfld ""System.Func<Employee, bool> <>x.<>c.<>9__0_0"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0014: ldftn ""bool <>x.<>c.<<>m0>b__0_0(Employee)"" IL_001a: newobj ""System.Func<Employee, bool>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<Employee, bool> <>x.<>c.<>9__0_0"" IL_0025: call ""System.Collections.Generic.IEnumerable<Employee> System.Linq.Enumerable.Where<Employee>(System.Collections.Generic.IEnumerable<Employee>, System.Func<Employee, bool>)"" IL_002a: ldsfld ""System.Func<Employee, <anonymous type: string Name, int Salary>> <>x.<>c.<>9__0_1"" IL_002f: dup IL_0030: brtrue.s IL_0049 IL_0032: pop IL_0033: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0038: ldftn ""<anonymous type: string Name, int Salary> <>x.<>c.<<>m0>b__0_1(Employee)"" IL_003e: newobj ""System.Func<Employee, <anonymous type: string Name, int Salary>>..ctor(object, System.IntPtr)"" IL_0043: dup IL_0044: stsfld ""System.Func<Employee, <anonymous type: string Name, int Salary>> <>x.<>c.<>9__0_1"" IL_0049: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Name, int Salary>> System.Linq.Enumerable.Select<Employee, <anonymous type: string Name, int Salary>>(System.Collections.Generic.IEnumerable<Employee>, System.Func<Employee, <anonymous type: string Name, int Salary>>)"" IL_004e: call ""<anonymous type: string Name, int Salary> System.Linq.Enumerable.First<<anonymous type: string Name, int Salary>>(System.Collections.Generic.IEnumerable<<anonymous type: string Name, int Salary>>)"" IL_0053: ret }"); }); } [Fact] public void ExpressionTree() { var source = @"using System; using System.Linq.Expressions; class C { static object F(Expression<Func<object>> e) { var f = e.Compile(); return f(); } static void M(int o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => o + 1)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 100 (0x64) .maxstack 3 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""int <>x.<>c__DisplayClass0_0.o"" IL_000c: ldtoken ""<>x.<>c__DisplayClass0_0"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001b: ldtoken ""int <>x.<>c__DisplayClass0_0.o"" IL_0020: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0025: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002a: ldc.i4.1 IL_002b: box ""int"" IL_0030: ldtoken ""int"" IL_0035: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_003f: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0044: ldtoken ""object"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0053: ldc.i4.0 IL_0054: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0059: call ""System.Linq.Expressions.Expression<System.Func<object>> System.Linq.Expressions.Expression.Lambda<System.Func<object>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_005e: call ""object C.F(System.Linq.Expressions.Expression<System.Func<object>>)"" IL_0063: ret }"); }); } /// <summary> /// DiagnosticsPass must be run on evaluation method. /// </summary> [WorkItem(530404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530404")] [Fact] public void DiagnosticsPass() { var source = @"using System; using System.Linq.Expressions; class C { static object F(Expression<Func<object>> e) { var f = e.Compile(); return f(); } static void M() { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => null ?? new object())", out error, testData); Assert.Equal("error CS0845: An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side", error); }); } [WorkItem(935651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/935651")] [Fact] public void EvaluatePropertySet() { var source = @"class C { object P { get; set; } void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.P = null"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 3 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: dup IL_0003: stloc.0 IL_0004: callvirt ""void C.P.set"" IL_0009: ldloc.0 IL_000a: ret }"); } /// <summary> /// Evaluating an expression where the imported namespace /// is valid but the required reference is missing. /// </summary> [Fact] public void EvaluateExpression_MissingReferenceImportedNamespace() { // System.Linq namespace is available but System.Core is // missing since the reference was not needed in compilation. var source = @"using System.Linq; class C { static void M(object []o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( "o.First()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal("error CS1061: 'object[]' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'object[]' could be found (are you missing a using directive or an assembly reference?)", error); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); }); } [Fact] public void EvaluateExpression_UnusedImportedType() { var source = @"using E=System.Linq.Enumerable; class C { static void M(object []o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("E.First(o)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object System.Linq.Enumerable.First<object>(System.Collections.Generic.IEnumerable<object>)"" IL_0006: ret }"); }); } [Fact] public void NetModuleReference() { var sourceNetModule = @"class A { }"; var source1 = @"class B : A { void M() { } }"; var netModuleRef = CreateCompilation(sourceNetModule, options: TestOptions.DebugModule).EmitToImageReference(); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { netModuleRef }); WithRuntimeInstance(compilation1, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); }); } /// <summary> /// Netmodules with same name. /// </summary> [Fact] [WorkItem(30031, "https://github.com/dotnet/roslyn/issues/30031")] public void NetModuleDuplicateReferences() { // Netmodule 0 var sourceN0 = @"public class A0 { public int F0; }"; // Netmodule 1 var sourceN1 = @"public class A1 { public int F1; }"; // Netmodule 2 var sourceN2 = @"public class A2 { public int F2; }"; // DLL 0 + netmodule 0 var sourceD0 = @"public class B0 : A0 { }"; // DLL 1 + netmodule 0 var sourceD1 = @"public class B1 : A0 { }"; // DLL 2 + netmodule 1 + netmodule 2 var source = @"class C { static B0 x; static B1 y; static A1 z; static A2 w; static void M() { } }"; var assemblyName = ExpressionCompilerUtilities.GenerateUniqueName(); var compilationN0 = CreateCompilation( sourceN0, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N0"); var referenceN0 = ModuleMetadata.CreateFromImage(compilationN0.EmitToArray()).GetReference(display: assemblyName + "_N0"); var compilationN1 = CreateCompilation( sourceN1, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N0"); // Note: "_N0" not "_N1" var referenceN1 = ModuleMetadata.CreateFromImage(compilationN1.EmitToArray()).GetReference(display: assemblyName + "_N0"); var compilationN2 = CreateCompilation( sourceN2, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N2"); var referenceN2 = ModuleMetadata.CreateFromImage(compilationN2.EmitToArray()).GetReference(display: assemblyName + "_N2"); var compilationD0 = CreateCompilation( sourceD0, options: TestOptions.DebugDll, assemblyName: assemblyName + "_D0", references: new MetadataReference[] { referenceN0 }); var referenceD0 = AssemblyMetadata.CreateFromImage(compilationD0.EmitToArray()).GetReference(display: assemblyName + "_D0"); var compilationD1 = CreateCompilation( sourceD1, options: TestOptions.DebugDll, assemblyName: assemblyName + "_D1", references: new MetadataReference[] { referenceN0 }); var referenceD1 = AssemblyMetadata.CreateFromImage(compilationD1.EmitToArray()).GetReference(display: assemblyName + "_D1"); var compilation = CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: assemblyName, references: new MetadataReference[] { referenceN1, referenceN2, referenceD0, referenceD1 }); Assert.Equal(((ModuleMetadata)referenceN0.GetMetadataNoCopy()).Name, ((ModuleMetadata)referenceN1.GetMetadataNoCopy()).Name); // different netmodule, same name var references = new[] { MscorlibRef, referenceD0, referenceN0, // From D0 referenceD1, referenceN0, // From D1 referenceN1, // From D2 referenceN2, // From D2 }; WithRuntimeInstance(compilation, references, runtime => { var context = CreateMethodContext(runtime, "C.M"); // Expression references ambiguous modules. ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F0 + y.F0", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS7079: The type 'A0' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); context.CompileExpression( "y.F0", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS7079: The type 'A0' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); context.CompileExpression( "z.F1", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Empty(missingAssemblyIdentities); Assert.Equal("error CS7079: The type 'A1' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); // Expression does not reference ambiguous modules. var testData = new CompilationTestData(); context.CompileExpression("w.F2", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldsfld ""A2 C.w"" IL_0005: ldfld ""int A2.F2"" IL_000a: ret }"); }); } [Fact] public void SizeOfReferenceType() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "sizeof(C)", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')", error); } [Fact] public void SizeOfValueType() { var source = @"struct S { } class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "sizeof(S)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: sizeof ""S"" IL_0006: ret }"); } /// <summary> /// Unnamed temporaries at the end of the local /// signature should be preserved. /// </summary> [Fact] public void TrailingUnnamedTemporaries() { var source = @"class C { object F; static bool M(object[] c) { foreach (var o in c) { if (o != null) return true; } return false; } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new C() { F = 1 }", resultProperties: out resultProperties, error: out error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 3 .locals init (object[] V_0, int V_1, object V_2, bool V_3, bool V_4) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: box ""int"" IL_000c: stfld ""object C.F"" IL_0011: ret }"); } [WorkItem(958448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958448")] [Fact] public void ConditionalAttribute() { var source = @"using System.Diagnostics; class C { static void M(int x) { } [Conditional(""D"")] static void F(object o) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(x + 1)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: add IL_0003: box ""int"" IL_0008: call ""void C.F(object)"" IL_000d: ret }"); } [WorkItem(958448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958448")] [Fact] public void ConditionalAttribute_CollectionInitializer() { var source = @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C : IEnumerable { private List<object> c = new List<object>(); [Conditional(""D"")] void Add(object o) { this.c.Add(o); } IEnumerator IEnumerable.GetEnumerator() { return this.c.GetEnumerator(); } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new C() { 1, 2 }"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: box ""int"" IL_000c: callvirt ""void C.Add(object)"" IL_0011: dup IL_0012: ldc.i4.2 IL_0013: box ""int"" IL_0018: callvirt ""void C.Add(object)"" IL_001d: ret }"); } [Fact] public void ConditionalAttribute_Delegate() { var source = @"using System.Diagnostics; delegate void D(); class C { [Conditional(""D"")] static void F() { } static void G(D d) { } static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "G(F)", resultProperties: out resultProperties, error: out error); // Should delegates to [Conditional] methods be supported? Assert.Equal("error CS1618: Cannot create delegate with 'C.F()' because it or a method it overrides has a Conditional attribute", error); } [Fact] public void StaticDelegate() { var source = @"delegate void D(); class C { static void F() { } static void G(D d) { } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "G(F)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void C.F()"" IL_0007: newobj ""D..ctor(object, System.IntPtr)"" IL_000c: call ""void C.G(D)"" IL_0011: ret }"); } [Fact] public void StaticLambda() { var source = @" delegate int D(int x); class C { void M() { } } "; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "((D)(x => x + x))(1)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldsfld ""D <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""int <>x.<>c.<<>m0>b__0_0(int)"" IL_0014: newobj ""D..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D <>x.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: callvirt ""int D.Invoke(int)"" IL_0025: ret }"); } [WorkItem(984509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984509")] [Fact] public void LambdaContainingIncrementOperator() { var source = @"class C { static void M(int i) { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "(System.Action)(() => i++)", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.i"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld ""int <>x.<>c__DisplayClass0_0.i"" IL_0010: ret }"); } [Fact] public void NestedGenericTypes() { var source = @" class C<T> { class D<U> { void M(U u, T t, System.Type type1, System.Type type2) { } } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.D.M", expr: "M(u, t, typeof(U), typeof(T))", resultProperties: out resultProperties, error: out error); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 5 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldtoken ""U"" IL_0008: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000d: ldtoken ""T"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: callvirt ""void C<T>.D<U>.M(U, T, System.Type, System.Type)"" IL_001c: ret }"); } [Fact] public void NestedGenericTypes_GenericMethod() { var source = @" class C<T> { class D<U> { void M<V>(V v, U u, T t, System.Type type1, System.Type type2, System.Type type3) { } } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.D.M", expr: "M(v, u, t, typeof(V), typeof(U), typeof(T))", resultProperties: out resultProperties, error: out error); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x<T, U>.<>m0<V>").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 7 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: ldtoken ""V"" IL_0009: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000e: ldtoken ""U"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldtoken ""T"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: callvirt ""void C<T>.D<U>.M<V>(V, U, T, System.Type, System.Type, System.Type)"" IL_0027: ret }"); } [WorkItem(1000946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1000946")] [Fact] public void BaseExpression() { var source = @" class Base { } class Derived : Base { void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "Derived.M", expr: "base", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0175: Use of keyword 'base' is not valid in this context", error); } [Fact] public void StructBaseCall() { var source = @" struct S { public void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "base.ToString()", resultProperties: out resultProperties, error: out error); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""string System.ValueType.ToString()"" IL_0010: ret }"); } [WorkItem(1010922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010922")] [Fact] public void IntOverflow() { var source = @" class C { public void M() { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("checked(2147483647 + 1)", out error, testData); Assert.Equal("error CS0220: The operation overflows at compile time in checked mode", error); testData = new CompilationTestData(); context.CompileExpression("unchecked(2147483647 + 1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: ret }"); testData = new CompilationTestData(); context.CompileExpression("2147483647 + 1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: ret }"); }); } [WorkItem(1012956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1012956")] [Fact] public void AssignmentConversion() { var source = @" class C { public void M(uint u) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("u = 2147483647 + 1", out error, testData); Assert.Equal("error CS0031: Constant value '-2147483648' cannot be converted to a 'uint'", error); testData = new CompilationTestData(); context.CompileAssignment("u", "2147483647 + 1", out error, testData); Assert.Equal("error CS0031: Constant value '-2147483648' cannot be converted to a 'uint'", error); testData = new CompilationTestData(); context.CompileExpression("u = 2147483647 + 1u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldc.i4 0x80000000 IL_0005: dup IL_0006: starg.s V_1 IL_0008: ret }"); testData = new CompilationTestData(); context.CompileAssignment("u", "2147483647 + 1u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: starg.s V_1 IL_0007: ret }"); }); } [WorkItem(1016530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016530")] [Fact] public void EvaluateStatement() { var source = @" class C { void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "throw new System.Exception()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS8115: A throw expression is not allowed in this context.", error); } [WorkItem(1016555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016555")] [Fact] public void UnmatchedCloseAndOpenParens() { var source = @"class C { static void M() { object o = 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "(System.Func<object>)(() => 2))(", error: out error, testData: testData); Assert.Equal("error CS1073: Unexpected token ')'", error); }); } [WorkItem(1015887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015887")] [Fact] public void DateTimeFieldConstant() { var source = @".class public C { .field public static initonly valuetype [mscorlib]System.DateTime D .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = {int64(633979872000000000)} .method public specialname rtspecialname instance void .ctor() { ret } .method public static void M() { ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("D", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""System.DateTime C.D"" IL_0005: ret }"); } [WorkItem(1015887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015887")] [Fact] public void DecimalFieldConstant() { var source = @" struct S { public const decimal D = 3.14M; public void M() { System.Console.WriteLine(); } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "D", resultProperties: out resultProperties, error: out error); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 15 (0xf) .maxstack 5 IL_0000: ldc.i4 0x13a IL_0005: ldc.i4.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldc.i4.2 IL_0009: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000e: ret }"); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void IteratorParameter() { var source = @"class C { System.Collections.IEnumerable F(int x) { yield return x; yield return this; // Until iterators always capture 'this', do it explicitly. } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((MethodSymbol)methodData.Method).ReturnType.SpecialType); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.x"" IL_0006: ret } "); }); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void IteratorGenericLocal() { var source = @"class C<T> { System.Collections.IEnumerable F(int x) { T t = default(T); yield return t; t.ToString(); yield return this; // Until iterators always capture 'this', do it explicitly. } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); var methodData = testData.GetMethodData("<>x<T>.<>m0"); Assert.Equal("T", ((MethodSymbol)methodData.Method).ReturnType.Name); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""T C<T>.<F>d__0.<t>5__1"" IL_0006: ret } "); }); } [WorkItem(1028808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028808")] [Fact] public void StaticLambdaInDisplayClass() { var source = @".class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public class C c .field private static class [mscorlib]System.Action`1<int32> 'CS$<>9__CachedAnonymousMethodDelegate4' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method private hidebysig static void '<Test>b__1'(int32 x) cil managed { ret } } // Need some static method 'Test' with 'x' in scope. .method private hidebysig static void Test(int32 x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.<>c__DisplayClass2.<Test>b__1"); string error; var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void ConditionalAccessExpressionType() { var source = @"class C { int F() { return 0; } C G() { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this?.F()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int?", ((MethodSymbol)methodData.Method).ReturnTypeWithAnnotations.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 1 .locals init (int? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""int?"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: call ""int C.F()"" IL_0013: newobj ""int?..ctor(int)"" IL_0018: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("(new C())?.G()?.F()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int?", ((MethodSymbol)methodData.Method).ReturnTypeWithAnnotations.ToDisplayString()); testData = new CompilationTestData(); result = context.CompileExpression("G()?.M()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""C C.G()"" IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ret IL_000b: call ""void C.M()"" IL_0010: ret }"); }); } [Fact] public void CallerInfoAttributes() { var source = @"using System.Runtime.CompilerServices; class C { static object F( [CallerFilePath]string path = null, [CallerMemberName]string member = null, [CallerLineNumber]int line = 0) { return string.Format(""[{0}] [{1}] [{2}]"", path, member, line); } static void Main() { } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F()", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldstr ""Main"" IL_000a: ldc.i4.1 IL_000b: call ""object C.F(string, string, int)"" IL_0010: ret }"); }); } [Fact] public void ExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml.Linq; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0, System.Xml.Linq.LoadOptions V_1) IL_0000: ldc.i4.0 IL_0001: stloc.1 IL_0002: ldloca.s V_1 IL_0004: constrained. ""System.Xml.Linq.LoadOptions"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ret } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("SXL.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("LO.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("X.System.Xml.Linq.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("X::System.Xml.Linq.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); }); } [Fact] public void ExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0, System.Xml.Linq.LoadOptions V_1) IL_0000: ldc.i4.0 IL_0001: stloc.1 IL_0002: ldloca.s V_1 IL_0004: constrained. ""System.Xml.Linq.LoadOptions"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ret } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("A.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("B.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); }); } [Fact] public void ExternAliasForMultipleAssemblies() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); var d = new X::System.Xml.XmlDocument(); return 1; } } "; var comp = CreateCompilation( source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")), SystemXmlRef.WithAliases(ImmutableArray.Create("X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new X::System.Xml.XmlDocument()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 6 (0x6) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0) IL_0000: newobj ""System.Xml.XmlDocument..ctor()"" IL_0005: ret } "); testData = new CompilationTestData(); result = context.CompileExpression("X::System.Xml.Linq.LoadOptions.None", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0) IL_0000: ldc.i4.0 IL_0001: ret } "); }); } [Fact] [WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")] public void FieldLikeEvent() { var source = @" class C { event System.Action E; void M() { } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var actionType = context.Compilation.GetWellKnownType(WellKnownType.System_Action); ResultProperties resultProperties; string error; CompilationTestData testData; CompileResult result; CompilationTestData.MethodData methodData; // Inspect the value. testData = new CompilationTestData(); result = context.CompileExpression("E", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""System.Action C.E"" IL_0006: ret } "); // Invoke the delegate. testData = new CompilationTestData(); result = context.CompileExpression("E()", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""System.Action C.E"" IL_0006: callvirt ""void System.Action.Invoke()"" IL_000b: ret } "); // Assign to the event. testData = new CompilationTestData(); result = context.CompileExpression("E = null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 11 (0xb) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: dup IL_0003: stloc.0 IL_0004: stfld ""System.Action C.E"" IL_0009: ldloc.0 IL_000a: ret } "); // Event (compound) assignment. testData = new CompilationTestData(); result = context.CompileExpression("E += null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: callvirt ""void C.E.add"" IL_0007: ret } "); }); } [Fact] [WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")] public void FieldLikeEvent_WinRT() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .field private class [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1<class [mscorlib]System.Action> E .method public hidebysig specialname instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_E(class [mscorlib]System.Action 'value') cil managed { ldnull throw } .method public hidebysig specialname instance void remove_E(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .event [mscorlib]System.Action E { .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C::add_E(class [mscorlib]System.Action) .removeon instance void C::remove_E(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } // end of event C::E .method public hidebysig instance void M() cil managed { ret } } // end of class C "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource); var runtime = CreateRuntimeInstance(module, WinRtRefs); var context = CreateMethodContext(runtime, "C.M"); var actionType = context.Compilation.GetWellKnownType(WellKnownType.System_Action); ResultProperties resultProperties; string error; CompilationTestData testData; CompileResult result; CompilationTestData.MethodData methodData; // Inspect the value. testData = new CompilationTestData(); result = context.CompileExpression("E", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> C.E"" IL_0006: call ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.GetOrCreateEventRegistrationTokenTable(ref System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>)"" IL_000b: callvirt ""System.Action System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.InvocationList.get"" IL_0010: ret } "); // Invoke the delegate. testData = new CompilationTestData(); result = context.CompileExpression("E()", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 22 (0x16) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> C.E"" IL_0006: call ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.GetOrCreateEventRegistrationTokenTable(ref System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>)"" IL_000b: callvirt ""System.Action System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.InvocationList.get"" IL_0010: callvirt ""void System.Action.Invoke()"" IL_0015: ret } "); // Assign to the event. testData = new CompilationTestData(); result = context.CompileExpression("E = null", out resultProperties, out error, testData); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 48 (0x30) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldftn ""void C.E.remove"" IL_0007: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_000c: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveAllEventHandlers(System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>)"" IL_0011: ldarg.0 IL_0012: ldftn ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C.E.add"" IL_0018: newobj ""System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_001d: ldarg.0 IL_001e: ldftn ""void C.E.remove"" IL_0024: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_0029: ldnull IL_002a: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler<System.Action>(System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action)"" IL_002f: ret } "); // Event (compound) assignment. testData = new CompilationTestData(); result = context.CompileExpression("E += null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldftn ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C.E.add"" IL_0007: newobj ""System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_000c: ldarg.0 IL_000d: ldftn ""void C.E.remove"" IL_0013: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_0018: ldnull IL_0019: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler<System.Action>(System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action)"" IL_001e: ret } "); } [WorkItem(1079749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079749")] [Fact] public void RangeVariableError() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "from c in \"ABC\" select c", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Equal(new AssemblyIdentity("System.Core"), missingAssemblyIdentities.Single()); Assert.Equal("error CS1935: Could not find an implementation of the query pattern for source type 'string'. 'Select' not found. Are you missing required assembly references or a using directive for 'System.Linq'?", error); }); } [WorkItem(1079762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079762")] [Fact] public void Bug1079762() { var source = @"class C { static void F(System.Func<object, bool> f, object o) { f(o); } static void M(object x, object y) { F(z => z != null && x != null, 3); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<>c__DisplayClass1_0.<M>b__0"); string error; var testData = new CompilationTestData(); context.CompileExpression("z", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileExpression("y", out error, testData); Assert.Equal("error CS0103: The name 'y' does not exist in the current context", error); }); } [WorkItem(1079762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079762")] [Fact] public void LambdaParameter() { var source = @"class C { static void M() { System.Func<object, bool> f = z => z != null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<>c.<M>b__0_0"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("z", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret }"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void StaticTypeImport() { var source = @" using static System.Math; class C { static void M() { Max(1, 2); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("Min(1, 2)", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: call ""int System.Math.Min(int, int)"" IL_0007: ret }"); }); } [WorkItem(1014763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1014763")] [Fact] public void NonStateMachineTypeParameter() { var source = @" using System.Collections.Generic; class C { static IEnumerable<T> I<T>(T[] tt) { return tt; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.I"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(T)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (System.Collections.Generic.IEnumerable<T> V_0) IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); }); } [WorkItem(1014763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1014763")] [Fact] public void StateMachineTypeParameter() { var source = @" using System.Collections.Generic; class C { static IEnumerable<T> I<T>(T[] tt) { foreach (T t in tt) { yield return t; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<I>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(T)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (int V_0) IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); }); } [WorkItem(1085642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085642")] [Fact] public void ModuleWithBadImageFormat() { var source = @" class C { int F = 1; static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); using (var pinnedMetadata = new PinnedBlob(TestResources.ExpressionCompiler.NoValidTables)) { var corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, default(Guid)); var runtime = RuntimeInstance.Create(new[] { corruptMetadata, comp.ToModuleInstance(), MscorlibRef.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); // Verify that we can still evaluate expressions for modules that are not corrupt. context.CompileExpression("(new C()).F", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: ldfld ""int C.F"" IL_000a: ret }"); } } [WorkItem(1089688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089688")] [Fact] public void MissingType() { var libSource = @" public class Missing { } "; var source = @" public class C { Missing field; public void M(Missing parameter) { Missing local; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateCompilation(source, new[] { libRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; void verify(string expr) { context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } verify("M(null)"); verify("field"); verify("field.Method"); verify("parameter"); verify("parameter.Method"); verify("local"); verify("local.Method"); // Note that even expressions that don't require the missing type will fail because // the method we synthesize refers to the original locals and parameters. verify("0"); }); } [WorkItem(1089688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089688")] [Fact] public void UseSiteWarning() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1Ref = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: signedDllOptions).EmitToImageReference(); var libBv2Ref = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: signedDllOptions).EmitToImageReference(); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A : B { } "; var libAv1Ref = CreateCompilation(libASource, new[] { libBv1Ref }, assemblyName: "A", options: signedDllOptions).EmitToImageReference(); var source = @" public class Source { public void Test() { object o = new A(); } } "; var comp = CreateCompilation(source, new[] { libAv1Ref, libBv2Ref }, TestOptions.DebugDll); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); WithRuntimeInstance(comp, new[] { MscorlibRef, libAv1Ref, libBv2Ref }, runtime => { var context = CreateMethodContext(runtime, "Source.Test"); string error; var testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); // Even though the method's return type has a use-site warning, we are able to evaluate the expression. Assert.Equal(ErrorCode.WRN_UnifyReferenceMajMin, (ErrorCode)((MethodSymbol)methodData.Method).ReturnType.GetUseSiteDiagnostic().Code); methodData.VerifyIL(@" { // Code size 6 (0x6) .maxstack 1 .locals init (object V_0) //o IL_0000: newobj ""A..ctor()"" IL_0005: ret }"); }); } [WorkItem(1090458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090458")] [Fact] public void ObsoleteAttribute() { var source = @" using System; using System.Diagnostics;   class C { static void Main() { C c = new C(); } [Obsolete(""Hello"", true)] int P { get; set; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); ResultProperties resultProperties; string error; context.CompileExpression("c.P", out resultProperties, out error); Assert.Null(error); }); } [WorkItem(1090458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090458")] [Fact] public void DeprecatedAttribute() { var source = @" using System; using Windows.Foundation.Metadata;   class C { static void Main() { C c = new C(); } [Deprecated(""Hello"", DeprecationType.Remove, 1)] int P { get; set; } } namespace Windows.Foundation.Metadata { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)] public sealed class DeprecatedAttribute : Attribute { public DeprecatedAttribute(string message, DeprecationType type, uint version) { } public DeprecatedAttribute(string message, DeprecationType type, uint version, Type contract) { } } public enum DeprecationType { Deprecate = 0, Remove = 1 } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); ResultProperties resultProperties; string error; context.CompileExpression("c.P", out resultProperties, out error); Assert.Null(error); }); } [WorkItem(1089591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089591")] [Fact] public void BadPdb_MissingMethod() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = new MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes>.Empty); var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); evalContext.CompileExpression("1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [WorkItem(1108133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108133")] [Fact] public void SymUnmanagedReaderNotImplemented() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var module = ModuleInstance.Create(peImage, NotImplementedSymUnmanagedReader.Instance); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); evalContext.CompileExpression("1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [WorkItem(1115543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115543")] [Fact] public void MethodTypeParameterInLambda() { var source = @" using System; public class C<T> { public void M<U>() { Func<U, int> getInt = u => { return u.GetHashCode(); }; var result = getInt(default(U)); } } "; var comp = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.<>c__0.<M>b__0_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(U)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""U"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); }); } [WorkItem(1136085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1136085")] [Fact] public void TypeofOpenGenericType() { var source = @" using System; public class C { public void M() { } }"; var compilation = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(compilation, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var expectedIL = @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""System.Action<T>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"; var testData = new CompilationTestData(); context.CompileExpression("typeof(Action<>)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); context.CompileExpression("typeof(Action<> )", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); context.CompileExpression("typeof(Action<Action<>>)", out error, testData); Assert.Equal("error CS7003: Unexpected use of an unbound generic name", error); context.CompileExpression("typeof(Action<Action< > > )", out error); Assert.Equal("error CS7003: Unexpected use of an unbound generic name", error); context.CompileExpression("typeof(Action<>a)", out error); Assert.Equal("error CS1026: ) expected", error); }); } [WorkItem(1068138, "DevDiv")] [Fact] public void GetSymAttributeByVersion() { var source1 = @" public class C { public static void M() { int x = 1; } }"; var source2 = @" public class C { public static void M() { int x = 1; string y = ""a""; } }"; var comp1 = CreateCompilation(source1, options: TestOptions.DebugDll); var comp2 = CreateCompilation(source2, options: TestOptions.DebugDll); using (MemoryStream peStream1Unused = new MemoryStream(), peStream2 = new MemoryStream(), pdbStream1 = new MemoryStream(), pdbStream2 = new MemoryStream()) { Assert.True(comp1.Emit(peStream1Unused, pdbStream1).Success); Assert.True(comp2.Emit(peStream2, pdbStream2).Success); pdbStream1.Position = 0; pdbStream2.Position = 0; peStream2.Position = 0; var symReader = SymReaderFactory.CreateReader(pdbStream1); symReader.UpdateSymbolStore(pdbStream2); var module = ModuleInstance.Create(peStream2.ToImmutable(), symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader2; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader2, out methodToken, out localSignatureToken); Assert.Same(symReader, symReader2); AssertEx.SetEqual(symReader.GetLocalNames(methodToken, methodVersion: 1), "x"); AssertEx.SetEqual(symReader.GetLocalNames(methodToken, methodVersion: 2), "x", "y"); var context1 = CreateMethodContext( new AppDomain(), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context1.CompileGetLocals( locals, argumentsOnly: false, typeName: out typeName, testData: null); AssertEx.SetEqual(locals.Select(l => l.LocalName), "x"); var context2 = CreateMethodContext( new AppDomain(), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 2, ilOffset: 0, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); locals.Clear(); context2.CompileGetLocals( locals, argumentsOnly: false, typeName: out typeName, testData: null); AssertEx.SetEqual(locals.Select(l => l.LocalName), "x", "y"); } } /// <summary> /// Ignore accessibility in lambda rewriter. /// </summary> [WorkItem(1618, "https://github.com/dotnet/roslyn/issues/1618")] [Fact] public void LambdaRewriterIgnoreAccessibility() { var source = @"using System.Linq; class C { static void M() { var q = new[] { new C() }.AsQueryable(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); string error; context.CompileExpression("q.Where(c => true)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 64 (0x40) .maxstack 6 .locals init (System.Linq.IQueryable<C> V_0, //q System.Linq.Expressions.ParameterExpression V_1) IL_0000: ldloc.0 IL_0001: ldtoken ""C"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""c"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.1 IL_0016: ldc.i4.1 IL_0017: box ""bool"" IL_001c: ldtoken ""bool"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002b: ldc.i4.1 IL_002c: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0031: dup IL_0032: ldc.i4.0 IL_0033: ldloc.1 IL_0034: stelem.ref IL_0035: call ""System.Linq.Expressions.Expression<System.Func<C, bool>> System.Linq.Expressions.Expression.Lambda<System.Func<C, bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_003a: call ""System.Linq.IQueryable<C> System.Linq.Queryable.Where<C>(System.Linq.IQueryable<C>, System.Linq.Expressions.Expression<System.Func<C, bool>>)"" IL_003f: ret }"); }); } /// <summary> /// Ignore accessibility in async rewriter. /// </summary> [Fact] public void AsyncRewriterIgnoreAccessibility() { var source = @"using System; using System.Threading.Tasks; class C { static void F<T>(Func<Task<T>> f) { } static void M() { } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); string error; context.CompileExpression("F(async () => new C())", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 37 (0x25) .maxstack 2 IL_0000: ldsfld ""System.Func<System.Threading.Tasks.Task<C>> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""System.Threading.Tasks.Task<C> <>x.<>c.<<>m0>b__0_0()"" IL_0014: newobj ""System.Func<System.Threading.Tasks.Task<C>>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<System.Threading.Tasks.Task<C>> <>x.<>c.<>9__0_0"" IL_001f: call ""void C.F<C>(System.Func<System.Threading.Tasks.Task<C>>)"" IL_0024: ret }"); }); } [Fact] public void CapturedLocalInLambda() { var source = @" using System; class C { void M(Func<int> f) { int x = 42; M(() => x); } }"; var comp = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("M(() => x)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 32 (0x20) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 <>x.<>c__DisplayClass0_0 V_1) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: ldloc.0 IL_0008: stfld ""C.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000d: ldarg.0 IL_000e: ldloc.1 IL_000f: ldftn ""int <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0015: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001a: callvirt ""void C.M(System.Func<int>)"" IL_001f: ret }"); }); } [WorkItem(3309, "https://github.com/dotnet/roslyn/issues/3309")] [Fact] public void NullAnonymousTypeInstance() { var source = @"class C { static void Main() { } }"; var testData = Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "false ? new { P = 1 } : null"); var methodData = testData.GetMethodData("<>x.<>m0"); var returnType = (NamedTypeSymbol)((MethodSymbol)methodData.Method).ReturnType; Assert.True(returnType.IsAnonymousType); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } /// <summary> /// DkmClrInstructionAddress.ILOffset is set to uint.MaxValue /// if the instruction does not map to an IL offset. /// </summary> [WorkItem(1185315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185315")] [Fact] public void NoILOffset() { var source = @"class C { static void M(int x) { int y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var appDomain = new AppDomain(); var context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ExpressionCompilerTestHelpers.NoILOffset, localSignatureToken: localSignatureToken); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("x + y", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldloc.0 IL_0002: add IL_0003: ret }"); // Verify the context is re-used for ILOffset == 0. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); Assert.Same(GetMetadataContext(previous).EvaluationContext, context); // Verify the context is re-used for NoILOffset. previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ExpressionCompilerTestHelpers.NoILOffset, localSignatureToken: localSignatureToken); Assert.Same(GetMetadataContext(previous).EvaluationContext, context); }); } [WorkItem(4098, "https://github.com/dotnet/roslyn/issues/4098")] [Fact] public void SelectAnonymousType() { var source = @"using System.Collections.Generic; using System.Linq; class C { static void M(List<int> list) { var useLinq = list.Last(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("from x in list from y in list where x > 0 select new { x, y };", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 140 (0x8c) .maxstack 4 .locals init (int V_0, //useLinq <>x.<>c__DisplayClass0_0 V_1) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: ldarg.0 IL_0008: stfld ""System.Collections.Generic.List<int> <>x.<>c__DisplayClass0_0.list"" IL_000d: ldloc.1 IL_000e: ldfld ""System.Collections.Generic.List<int> <>x.<>c__DisplayClass0_0.list"" IL_0013: ldloc.1 IL_0014: ldftn ""System.Collections.Generic.IEnumerable<int> <>x.<>c__DisplayClass0_0.<<>m0>b__0(int)"" IL_001a: newobj ""System.Func<int, System.Collections.Generic.IEnumerable<int>>..ctor(object, System.IntPtr)"" IL_001f: ldsfld ""System.Func<int, int, <anonymous type: int x, int y>> <>x.<>c.<>9__0_1"" IL_0024: dup IL_0025: brtrue.s IL_003e IL_0027: pop IL_0028: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_002d: ldftn ""<anonymous type: int x, int y> <>x.<>c.<<>m0>b__0_1(int, int)"" IL_0033: newobj ""System.Func<int, int, <anonymous type: int x, int y>>..ctor(object, System.IntPtr)"" IL_0038: dup IL_0039: stsfld ""System.Func<int, int, <anonymous type: int x, int y>> <>x.<>c.<>9__0_1"" IL_003e: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.SelectMany<int, int, <anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<int>, System.Func<int, System.Collections.Generic.IEnumerable<int>>, System.Func<int, int, <anonymous type: int x, int y>>)"" IL_0043: ldsfld ""System.Func<<anonymous type: int x, int y>, bool> <>x.<>c.<>9__0_2"" IL_0048: dup IL_0049: brtrue.s IL_0062 IL_004b: pop IL_004c: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0051: ldftn ""bool <>x.<>c.<<>m0>b__0_2(<anonymous type: int x, int y>)"" IL_0057: newobj ""System.Func<<anonymous type: int x, int y>, bool>..ctor(object, System.IntPtr)"" IL_005c: dup IL_005d: stsfld ""System.Func<<anonymous type: int x, int y>, bool> <>x.<>c.<>9__0_2"" IL_0062: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.Where<<anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>>, System.Func<<anonymous type: int x, int y>, bool>)"" IL_0067: ldsfld ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>> <>x.<>c.<>9__0_3"" IL_006c: dup IL_006d: brtrue.s IL_0086 IL_006f: pop IL_0070: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0075: ldftn ""<anonymous type: int x, int y> <>x.<>c.<<>m0>b__0_3(<anonymous type: int x, int y>)"" IL_007b: newobj ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>>..ctor(object, System.IntPtr)"" IL_0080: dup IL_0081: stsfld ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>> <>x.<>c.<>9__0_3"" IL_0086: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.Select<<anonymous type: int x, int y>, <anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>>, System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>>)"" IL_008b: ret }"); }); } [WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")] [Fact] public void ImportsInAsyncLambda() { var source = @"namespace N { using System.Linq; class C { static void M() { System.Action f = async () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; } } }"; var compilation0 = CreateCompilationWithMscorlib45( source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "N.C.<>c.<<M>b__0_0>d.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.Where(n => n > 0)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 43 (0x2b) .maxstack 3 .locals init (int V_0, System.Exception V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int[] N.C.<>c.<<M>b__0_0>d.<c>5__1"" IL_0006: ldsfld ""System.Func<int, bool> <>x.<>c.<>9__0_0"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0014: ldftn ""bool <>x.<>c.<<>m0>b__0_0(int)"" IL_001a: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<int, bool> <>x.<>c.<>9__0_0"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_002a: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void AssignDefaultToLocal() { var source = @" class C { void Test() { int a = 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.Test"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileAssignment("a", "default", NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); Assert.Empty(missingAssemblyIdentities); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 3 (0x3) .maxstack 1 .locals init (int V_0) //a IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ret }"); testData = new CompilationTestData(); context.CompileExpression("a = default;", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //a IL_0000: ldc.i4.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ret }"); testData = new CompilationTestData(); context.CompileExpression("int b = default;", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, //a System.Guid V_1) IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""b"" IL_000f: ldloca.s V_1 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.1 IL_0018: ldnull IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_001e: ldstr ""b"" IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_0028: ldc.i4.0 IL_0029: stind.i4 IL_002a: ret }"); testData = new CompilationTestData(); context.CompileExpression("default", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Equal("error CS8716: There is no target type for the default literal.", error); testData = new CompilationTestData(); context.CompileExpression("null", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (int V_0) //a IL_0000: ldnull IL_0001: ret }"); }); } [Fact] public void InLambdasEvaluationWillSynthesizeRequiredAttributes_Parameters() { var reference = CreateCompilation(@" public delegate void D(in int p);"); CompileAndVerify(reference, symbolValidator: module => { Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var comp = CreateCompilation(@" public class Test { void M(D lambda) { } }", references: new[] { reference.EmitToImageReference() }); CompileAndVerify(comp, symbolValidator: module => { Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var testData = Evaluate( comp, methodName: "Test.M", expr: "M((in int p) => {})"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.IsReadOnlyAttribute.FullName + "..ctor()", methodsGenerated); } [Fact] public void RefReadOnlyLambdasEvaluationWillSynthesizeRequiredAttributes_ReturnTypes() { var reference = CreateCompilation(@" public delegate ref readonly int D();"); CompileAndVerify(reference, symbolValidator: module => { Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var comp = CreateCompilation(@" public class Test { private int x = 0; void M(D lambda) { } }", references: new[] { reference.EmitToImageReference() }); CompileAndVerify(comp, symbolValidator: module => { Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var testData = Evaluate( comp, methodName: "Test.M", expr: "M(() => ref x)"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.IsReadOnlyAttribute.FullName + "..ctor()", methodsGenerated); } // https://github.com/dotnet/roslyn/issues/30033: EnsureNullableAttributeExists is not called. [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30033")] [WorkItem(30033, "https://github.com/dotnet/roslyn/issues/30033")] public void EmitNullableAttribute_ExpressionType() { var source = @"class C { static void Main() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new object?[0]", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr ""object"" IL_0006: ret }"); // Verify NullableAttribute is emitted. using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef(result.TypeName); var methodHandle = reader.GetMethodDefHandle(typeDef, result.MethodName); var attributeHandle = reader.GetCustomAttributes(methodHandle).Single(); var attribute = reader.GetCustomAttribute(attributeHandle); var attributeConstructor = reader.GetMethodDefinition((System.Reflection.Metadata.MethodDefinitionHandle)attribute.Constructor); var attributeTypeName = reader.GetString(reader.GetName(attributeConstructor.GetDeclaringType())); Assert.Equal("NullableAttribute", attributeTypeName); } }); } // https://github.com/dotnet/roslyn/issues/30034: Expression below currently reports // "CS0453: The type 'object' must be a non-nullable value type ... 'Nullable<T>'" // because CSharpCompilationExtensions.IsFeatureEnabled() fails when there // the Compilation contains no syntax trees. [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30034")] [WorkItem(30034, "https://github.com/dotnet/roslyn/issues/30034")] public void EmitNullableAttribute_LambdaParameters() { var source = @"delegate T D<T>(T t); class C { static T F<T>(D<T> d, T t) => d(t); static void G() { } }"; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.G"); string error; var testData = new CompilationTestData(); context.CompileExpression("F((object? o) => o, null)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 38 (0x26) .maxstack 2 IL_0000: ldsfld ""D<object?> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""object? <>x.<>c.<<>m0>b__0_0(object?)"" IL_0014: newobj ""D<object?>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D<object?> <>x.<>c.<>9__0_0"" IL_001f: ldnull IL_0020: call ""object? C.F<object?>(D<object?>, object?)"" IL_0025: ret }"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.NullableAttribute.FullName + "..ctor()", methodsGenerated); }); } [Fact] [WorkItem(22206, "https://github.com/dotnet/roslyn/issues/22206")] public void RefReturnNonRefLocal() { var source = @" delegate ref int D(); class C { static void Main() { int local = 0; } static ref int M(D d) { return ref d(); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); context.CompileExpression("M(() => ref local)", out var error); Assert.Equal("error CS8168: Cannot return local 'local' by reference because it is not a ref local", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void OutVarInExpression() { var source = @"class C { static void Main() { } static object Test(out int x) { x = 1; return x; } }"; var testData = Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "Test(out var z)"); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 46 (0x2e) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""z"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_001e: ldstr ""z"" IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_0028: call ""object C.Test(out int)"" IL_002d: ret }"); } [Fact] public void IndexExpression() { var source = TestSources.Index + @" class C { static void Main() { var x = ^1; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Index V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 .locals init (System.Index V_0) //x IL_0000: ldloca.s V_0 IL_0002: call ""int System.Index.Value.get"" IL_0007: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "^2").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (System.Index V_0) //x IL_0000: ldc.i4.2 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: ret }"); } [Fact] public void RangeExpression_None() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = ..; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "..").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: call ""System.Range System.Range.All.get"" IL_0005: ret }"); } [Fact] public void RangeExpression_Left() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = 1..; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "2..").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldc.i4.2 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: call ""System.Range System.Range.StartAt(System.Index)"" IL_000b: ret }"); } [Fact] public void RangeExpression_Right() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = ..1; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "..2").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldc.i4.2 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: call ""System.Range System.Range.EndAt(System.Index)"" IL_000b: ret }"); } [Fact] public void RangeExpression_Both() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = 1..2; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "3..4").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.Range V_0) //x IL_0000: ldc.i4.3 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: ldc.i4.4 IL_0007: call ""System.Index System.Index.op_Implicit(int)"" IL_000c: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0011: 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 System; using System.Collections.Immutable; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.PdbUtilities; using static Roslyn.Test.Utilities.SigningTestHelpers; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ExpressionCompilerTests : ExpressionCompilerTestBase { /// <summary> /// Each assembly should have a unique MVID and assembly name. /// </summary> [WorkItem(1029280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029280")] [Fact] public void UniqueModuleVersionId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var appDomain = new AppDomain(); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader); var context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); string error; var result = context.CompileExpression("1", out error); var mvid1 = result.Assembly.GetModuleVersionId(); var name1 = result.Assembly.GetAssemblyName(); Assert.NotEqual(mvid1, Guid.Empty); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); }); } [Fact] public void ParseError() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var result = context.CompileExpression("M(", out error); Assert.Null(result); Assert.Equal("error CS1026: ) expected", error); }); } /// <summary> /// Diagnostics should be formatted with the CurrentUICulture. /// </summary> [WorkItem(941599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941599")] [Fact] public void FormatterCultureInfo() { var previousCulture = Thread.CurrentThread.CurrentCulture; var previousUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE"); try { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( "M(", DkmEvaluationFlags.TreatAsExpression, NoAliases, CustomDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, preferredUICulture: null, testData: null); Assert.Null(result); Assert.Equal("LCID=1031, Code=1026", error); Assert.Empty(missingAssemblyIdentities); }); } finally { Thread.CurrentThread.CurrentUICulture = previousUICulture; Thread.CurrentThread.CurrentCulture = previousCulture; } } /// <summary> /// Compile should succeed if there are /// parse warnings but no errors. /// </summary> [Fact] public void ParseWarning() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { // (1,2): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity const string expr = "0l"; var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression(expr, out error, testData); Assert.NotNull(result.Assembly); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: ret }"); }); } /// <summary> /// Reference to local in another scope. /// </summary> [Fact] public void BindingError() { var source = @"class C { static void M(object o) { var a = new object[0]; foreach (var x in a) { M(x); } foreach (var y in a) { #line 999 M(y); } } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "y ?? x", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); } [Fact] public void EmitError() { var longName = new string('P', 1100); var source = @"class C { static void M(object o) { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: string.Format("new {{ {0} = o }}", longName), resultProperties: out resultProperties, error: out error); Assert.Equal(error, string.Format("error CS7013: Name '<{0}>i__Field' exceeds the maximum length allowed in metadata.", longName)); } [Fact] public void NoSymbols() { var source = @"class C { static object F(object o) { return o; } static void M(int x) { int y = x + 1; } }"; var compilation0 = CSharpTestBase.CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0, debugFormat: 0); foreach (var module in runtime.Modules) { Assert.Null(module.SymReader); } var context = CreateMethodContext( runtime, methodName: "C.M"); // Local reference. string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F(y)", out error, testData); Assert.Equal("error CS0103: The name 'y' does not exist in the current context", error); // No local reference. testData = new CompilationTestData(); result = context.CompileExpression("F(x)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: box ""int"" IL_0006: call ""object C.F(object)"" IL_000b: ret }"); } /// <summary> /// Reuse Compilation if references match, and reuse entire /// EvaluationContext if references and local scopes match. /// </summary> [Fact] public void ReuseEvaluationContext() { var sourceA = @"public interface I { }"; var sourceB = @"class C { static void F(I o) { object x = 1; if (o == null) { object y = 2; y = x; } else { object z; } x = 3; } static void G() { } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll); var referenceA = compilationA.EmitToImageReference(); var compilationB = CreateCompilation( sourceB, options: TestOptions.DebugDll, references: new MetadataReference[] { referenceA }); const int methodVersion = 1; var referencesB = new[] { MscorlibRef, referenceA }; var moduleB = compilationB.ToModuleInstance(); var appDomain = new AppDomain(); int startOffset; int endOffset; var runtime = CreateRuntimeInstance(moduleB, referencesB); ImmutableArray<MetadataBlock> typeBlocks; ImmutableArray<MetadataBlock> methodBlocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); // Get non-empty scopes. var scopes = symReader.GetScopes(methodToken, methodVersion, EvaluationContext.IsLocalScopeEndInclusive).WhereAsArray(s => s.Locals.Length > 0); Assert.True(scopes.Length >= 3); var outerScope = scopes.First(s => s.Locals.Contains("x")); startOffset = outerScope.StartOffset; endOffset = outerScope.EndOffset - 1; // At start of outer scope. var context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)startOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); // At end of outer scope - not reused because of the nested scope. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); // Not required, just documentary. // At type context. previous = appDomain.GetMetadataContext(); context = CreateTypeContext(appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.Null(context.MethodContextReuseConstraints); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); // Step through entire method. var previousScope = (Scope)null; previous = appDomain.GetMetadataContext(); for (int offset = startOffset; offset <= endOffset; offset++) { var scope = scopes.GetInnermostScope(offset); var constraints = GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints; if (constraints.HasValue) { Assert.Equal(scope == previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset)); } context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)offset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); var previousEvaluationContext = GetMetadataContext(previous).EvaluationContext; if (scope == previousScope) { Assert.Equal(context, previousEvaluationContext); } else { // Different scope. Should reuse compilation. Assert.NotEqual(context, previousEvaluationContext); if (previousEvaluationContext != null) { Assert.NotEqual(context.MethodContextReuseConstraints, previousEvaluationContext.MethodContextReuseConstraints); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); } } previousScope = scope; previous = appDomain.GetMetadataContext(); } // With different references. var fewerReferences = new[] { MscorlibRef }; runtime = CreateRuntimeInstance(moduleB, fewerReferences); GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); // Different references. No reuse. context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, endOffset)); Assert.NotEqual(context.Compilation, GetMetadataContext(previous).Compilation); previous = appDomain.GetMetadataContext(); // Different method. Should reuse Compilation. GetContextState(runtime, "C.G", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, 0)); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); // No EvaluationContext. Should reuse Compilation appDomain.SetMetadataContext(SetMetadataContext(previous, default(Guid), new CSharpMetadataContext(GetMetadataContext(previous).Compilation))); previous = appDomain.GetMetadataContext(); Assert.Null(GetMetadataContext(previous).EvaluationContext); Assert.NotNull(GetMetadataContext(previous).Compilation); context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.Null(GetMetadataContext(previous).EvaluationContext); Assert.NotNull(context); Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation); } /// <summary> /// Allow trailing semicolon after expression. This is to support /// copy/paste of (simple cases of) RHS of assignment in Watch window, /// not to allow arbitrary syntax after the semicolon, not even comments. /// </summary> [WorkItem(950242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/950242")] [Fact] public void TrailingSemicolon() { var source = @"class C { static object F(string x, string y) { return x; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F"); string error; var result = context.CompileExpression("x;", out error); Assert.Null(error); result = context.CompileExpression("x \t;\t ", out error); Assert.Null(error); // Multiple semicolons: not supported. result = context.CompileExpression("x;;", out error); Assert.Equal("error CS1073: Unexpected token ';'", error); // // comments. result = context.CompileExpression("x;//", out error); Assert.Equal("error CS0726: ';//' is not a valid format specifier", error); result = context.CompileExpression("x//;", out error); Assert.Null(error); // /*...*/ comments. result = context.CompileExpression("x/*...*/", out error); Assert.Null(error); result = context.CompileExpression("x/*;*/", out error); Assert.Null(error); result = context.CompileExpression("x;/*...*/", out error); Assert.Equal("error CS0726: ';/*...*/' is not a valid format specifier", error); result = context.CompileExpression("x/*...*/;", out error); Assert.Null(error); // Trailing semicolon, no expression. result = context.CompileExpression(" ; ", out error); Assert.Equal("error CS1733: Expected expression", error); }); } [Fact] public void FormatSpecifiers() { var source = @"class C { static object F(string x, string y) { return x; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F"); string error; // No format specifiers. var result = context.CompileExpression("x", out error); CheckFormatSpecifiers(result); // Format specifiers on expression. result = context.CompileExpression("x,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x y", out error); Assert.Equal("error CS0726: 'y' is not a valid format specifier", error); result = context.CompileExpression("x yy zz", out error); Assert.Equal("error CS0726: 'yy' is not a valid format specifier", error); result = context.CompileExpression("x,,y", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,yy,zz,ww", out error); CheckFormatSpecifiers(result, "yy", "zz", "ww"); result = context.CompileExpression("x, y z", out error); Assert.Equal("error CS0726: 'z' is not a valid format specifier", error); result = context.CompileExpression("x, y , z ", out error); CheckFormatSpecifiers(result, "y", "z"); result = context.CompileExpression("x, y, z,", out error); Assert.Equal("error CS0726: ',' is not a valid format specifier", error); result = context.CompileExpression("x,y,z;w", out error); Assert.Equal("error CS0726: 'z;w' is not a valid format specifier", error); result = context.CompileExpression("x, y;, z", out error); Assert.Equal("error CS0726: 'y;' is not a valid format specifier", error); // Format specifiers after // comment: ignored. result = context.CompileExpression("x // ,f", out error); CheckFormatSpecifiers(result); // Format specifiers after /*...*/ comment. result = context.CompileExpression("x /*,f*/, g, h", out error); CheckFormatSpecifiers(result, "g", "h"); // Format specifiers on assignment value. result = context.CompileAssignment("x", "null, y", out error); Assert.Null(result); Assert.Equal("error CS1073: Unexpected token ','", error); // Trailing semicolon, no format specifiers. result = context.CompileExpression("x; ", out error); CheckFormatSpecifiers(result); // Format specifiers, no expression. result = context.CompileExpression(",f", out error); Assert.Equal("error CS1525: Invalid expression term ','", error); // Format specifiers before semicolon: not supported. result = context.CompileExpression("x,f;\t", out error); Assert.Equal("error CS1073: Unexpected token ','", error); // Format specifiers after semicolon: not supported. result = context.CompileExpression("x;,f", out error); Assert.Equal("error CS0726: ';' is not a valid format specifier", error); result = context.CompileExpression("x; f, g", out error); Assert.Equal("error CS0726: ';' is not a valid format specifier", error); }); } private static void CheckFormatSpecifiers(CompileResult result, params string[] formatSpecifiers) { Assert.NotNull(result.Assembly); if (formatSpecifiers.Length == 0) { Assert.Null(result.FormatSpecifiers); } else { Assert.Equal(formatSpecifiers, result.FormatSpecifiers); } } /// <summary> /// Locals in generated method should account for /// temporary slots in the original method. Also, some /// temporaries may not be included in any scope. /// </summary> [Fact] public void IncludeTemporarySlots() { var source = @"class C { static string F(int[] a) { lock (new C()) { #line 999 string s = a[0].ToString(); return s; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.F", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("a[0]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (C V_0, bool V_1, string V_2, //s string V_3) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem.i4 IL_0003: ret }"); }); } [Fact] public void EvaluateThis() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f) { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this.F() ?? this.G ?? this.P", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""object B.F()"" IL_0006: dup IL_0007: brtrue.s IL_001a IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""object B.G"" IL_0010: dup IL_0011: brtrue.s IL_001a IL_0013: pop IL_0014: ldarg.0 IL_0015: callvirt ""object B.P.get"" IL_001a: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(this.F)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldvirtftn ""object B.F()"" IL_0008: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000d: call ""object B.F(System.Func<object>)"" IL_0012: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(new System.Func<object>(this.F))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldvirtftn ""object B.F()"" IL_0008: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000d: call ""object B.F(System.Func<object>)"" IL_0012: ret }"); }); } [Fact] public void EvaluateBase() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f) { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("base.F() ?? base.G ?? base.P", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object A.F()"" IL_0006: dup IL_0007: brtrue.s IL_001a IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""object A.G"" IL_0010: dup IL_0011: brtrue.s IL_001a IL_0013: pop IL_0014: ldarg.0 IL_0015: call ""object A.P.get"" IL_001a: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(base.F)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""object A.F()"" IL_0007: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000c: call ""object B.F(System.Func<object>)"" IL_0011: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("F(new System.Func<object>(base.F))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""object A.F()"" IL_0007: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_000c: call ""object B.F(System.Func<object>)"" IL_0011: ret }"); }); } /// <summary> /// If "this" is a struct, the generated parameter /// should be passed by reference. /// </summary> [Fact] public void EvaluateStructThis() { var source = @"struct S { static object F(object x, object y) { return null; } object x; void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "F(this, this.x)"); var methodData = testData.GetMethodData("<>x.<>m0(ref S)"); var parameter = ((MethodSymbol)methodData.Method).Parameters[0]; Assert.Equal(RefKind.Ref, parameter.RefKind); methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: ldarg.0 IL_000c: ldfld ""object S.x"" IL_0011: call ""object S.F(object, object)"" IL_0016: ret }"); } [Fact] public void EvaluateStaticMethodParameters() { var source = @"class C { static object F(int x, int y) { return x + y; } static void M(int x, int y) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(y, x)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""object C.F(int, int)"" IL_0007: ret }"); } [Fact] public void EvaluateInstanceMethodParametersAndLocals() { var source = @"class C { object F(int x) { return x; } void M(int x) { #line 999 int y = 1; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "F(x + y)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 3 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldloc.0 IL_0003: add IL_0004: callvirt ""object C.F(int)"" IL_0009: ret }"); } [Fact] public void EvaluateLocals() { var source = @"class C { static void M() { int x = 1; if (x < 0) { int y = 2; } else { #line 999 int z = 3; } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "x + z"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0, //x bool V_1, int V_2, int V_3) //z IL_0000: ldloc.0 IL_0001: ldloc.3 IL_0002: add IL_0003: ret }"); } [Fact] public void EvaluateForEachLocal() { var source = @"class C { static bool F(object[] args) { if (args == null) { return true; } foreach (var o in args) { #line 999 } return false; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.F", atLineNumber: 999, expr: "o"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (bool V_0, bool V_1, object[] V_2, int V_3, object V_4) //o IL_0000: ldloc.s V_4 IL_0002: ret }"); } /// <summary> /// Generated "this" parameter should not /// conflict with existing "@this" parameter. /// </summary> [Fact] public void ParameterNamedThis() { var source = @"class C { object M(C @this) { return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "@this.M(this)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object C.M(C)"" IL_0007: ret }"); } /// <summary> /// Generated "this" parameter should not /// conflict with existing "@this" local. /// </summary> [Fact] public void LocalNamedThis() { var source = @"class C { object M(object o) { var @this = this; return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "@this.M(this)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (C V_0, //this object V_1) IL_0000: ldloc.0 IL_0001: ldarg.0 IL_0002: callvirt ""object C.M(object)"" IL_0007: ret }"); } [Fact] public void ByRefParameter() { var source = @"class C { static object M(out object x) { object y; x = null; return null; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "M(out y)"); var methodData = testData.GetMethodData("<>x.<>m0(out object)"); var parameter = ((MethodSymbol)methodData.Method).Parameters[0]; Assert.Equal(RefKind.Out, parameter.RefKind); methodData.VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 .locals init (object V_0, //y object V_1) IL_0000: ldloca.s V_0 IL_0002: call ""object C.M(out object)"" IL_0007: ret }"); } /// <summary> /// Method defined in IL where PDB does not /// contain C# custom metadata. /// </summary> [Fact] public void LocalType_FromIL() { var source = @".class public C { .method public specialname rtspecialname instance void .ctor() { ret } .field public object F; .method public static void M() { .locals init ([0] class C c) ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.F", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (C V_0) //c IL_0000: ldloc.0 IL_0001: ldfld ""object C.F"" IL_0006: ret }"); } /// <summary> /// Allow locals with optional custom modifiers. /// </summary> /// <remarks> /// The custom modifiers are not copied to the corresponding /// local in the generated method since there is no need. /// </remarks> [WorkItem(884627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884627")] [Fact] public void LocalType_CustomModifiers() { var source = @".class public C { .method public specialname rtspecialname instance void .ctor() { ret } .field public object F; .method public static void M() { .locals init ([0] class C modopt(int32) modopt(object) c) ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.F", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); var local = locals[0]; Assert.Equal("C", local.Type.ToString()); Assert.Equal(0, local.CustomModifiers.Length); // Custom modifiers are not copied. methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (C V_0) //c IL_0000: ldloc.0 IL_0001: ldfld ""object C.F"" IL_0006: ret }"); } [WorkItem(1012956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1012956")] [Fact] public void LocalType_ByRefOrPinned() { var source = @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .method private hidebysig static void M(string s, int32[] a) cil managed { // Code size 73 (0x49) .maxstack 2 .locals init ([0] string pinned s, [1] int32& pinned f, [2] int32& i) ret } } "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("s", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 2 (0x2) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.0 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileAssignment("s", "\"hello\"", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldstr ""hello"" IL_0005: stloc.0 IL_0006: ret }"); testData = new CompilationTestData(); context.CompileExpression("f", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 2 (0x2) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.1 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileAssignment("f", "1", out error, testData); Assert.Equal("error CS1656: Cannot assign to 'f' because it is a 'fixed variable'", error); testData = new CompilationTestData(); context.CompileExpression("i", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.2 IL_0001: ldind.i4 IL_0002: ret }"); testData = new CompilationTestData(); context.CompileAssignment("i", "1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (pinned string V_0, //s pinned int& V_1, //f int& V_2) //i IL_0000: ldloc.2 IL_0001: ldc.i4.1 IL_0002: stind.i4 IL_0003: ret }"); } [Fact] public void LocalType_FixedVariable() { var source = @"class C { static int x; static unsafe void M(string s, int[] a) { fixed (char* p1 = s) { fixed (int* p2 = &x) { fixed (void* p3 = a) { #line 999 int y = x + 1; } } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("(int)p1[0] + p2[0] + ((int*)p3)[0]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 2 .locals init (char* V_0, //p1 pinned string V_1, int* V_2, //p2 pinned int& V_3, void* V_4, //p3 pinned int[] V_5, int V_6) //y IL_0000: ldloc.0 IL_0001: ldind.u2 IL_0002: ldloc.2 IL_0003: ldind.i4 IL_0004: add IL_0005: ldloc.s V_4 IL_0007: ldind.i4 IL_0008: add IL_0009: ret }"); }); } [WorkItem(1034549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034549")] [Fact] public void AssignLocal() { var source = @"class C { static void M() { int x = 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "x", expr: "1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 3 (0x3) .maxstack 1 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ret }"); // Assign to a local, as above, but in an expression. testData = new CompilationTestData(); context.CompileExpression( expr: "x = 1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: dup IL_0002: stloc.0 IL_0003: ret }"); }); } [Fact] public void AssignInstanceMethodParametersAndLocals() { var source = @"class C { object[] a; static int F(int x) { return x; } void M(int x) { int y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "this.a[F(x)]", expr: "this.a[y]", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldfld ""object[] C.a"" IL_0006: ldarg.1 IL_0007: call ""int C.F(int)"" IL_000c: ldarg.0 IL_000d: ldfld ""object[] C.a"" IL_0012: ldloc.0 IL_0013: ldelem.ref IL_0014: stelem.ref IL_0015: ret }"); }); } [Fact] public void EvaluateNull() { var source = @"class C { static void M() { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "null", resultProperties: out resultProperties, error: out error); Assert.Equal(DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); var methodData = testData.GetMethodData("<>x.<>m0"); var method = (MethodSymbol)methodData.Method; Assert.Equal(SpecialType.System_Object, method.ReturnType.SpecialType); Assert.False(method.ReturnsVoid); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void MayHaveSideEffects() { var source = @"using System; using System.Diagnostics.Contracts; class C { object F() { return 1; } [Pure] object G() { return 2; } object P { get; set; } static object H() { return 3; } static void M(C o, int i) { ((dynamic)o).G(); } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); CheckResultFlags(context, "o.F()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); // Calls to methods are reported as having side effects, even if // the method is marked [Pure]. This matches the native EE. CheckResultFlags(context, "o.G()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "o.P", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "o.P = 2", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "((dynamic)o).G()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "(Action)(() => { })", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "++i", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "--i", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i++", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i--", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i += 2", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "i *= 3", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C() { P = 1 }", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C() { P = H() }", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); }); } [Fact] public void IsAssignable() { var source = @" using System; class C { int F; readonly int RF; const int CF = 1; event System.Action E; event System.Action CE { add { } remove { } } int RP { get { return 0; } } int WP { set { } } int RWP { get; set; } int this[int x] { get { return 0; } } int this[int x, int y] { set { } } int this[int x, int y, int z] { get { return 0; } set { } } int M() { return 0; } } "; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); CheckResultFlags(context, "F", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "RF", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "CF", DkmClrCompilationResultFlags.ReadOnlyResult); // Note: flags are always None in error cases. // CheckResultFlags(context, "E", DkmClrCompilationResultFlags.None); // TODO: DevDiv #1055825 CheckResultFlags(context, "CE", DkmClrCompilationResultFlags.None, "error CS0079: The event 'C.CE' can only appear on the left hand side of += or -="); CheckResultFlags(context, "RP", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "WP", DkmClrCompilationResultFlags.None, "error CS0154: The property or indexer 'C.WP' cannot be used in this context because it lacks the get accessor"); CheckResultFlags(context, "RWP", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "this[1]", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "this[1, 2]", DkmClrCompilationResultFlags.None, "error CS0154: The property or indexer 'C.this[int, int]' cannot be used in this context because it lacks the get accessor"); CheckResultFlags(context, "this[1, 2, 3]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "M()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "null", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "1", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "M", DkmClrCompilationResultFlags.None, "error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?"); CheckResultFlags(context, "typeof(C)", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "new C()", DkmClrCompilationResultFlags.ReadOnlyResult); }); } [Fact] public void IsAssignable_Array() { var source = @" using System; class C { readonly int[] RF = new int[1]; int[] rp = new int[2]; int[] RP { get { return rp; } } int[] m = new int[3]; int[] M() { return m; } } "; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); CheckResultFlags(context, "RF", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "RF[0]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "RP", DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "RP[0]", DkmClrCompilationResultFlags.None); CheckResultFlags(context, "M()", DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); CheckResultFlags(context, "M()[0]", DkmClrCompilationResultFlags.PotentialSideEffect); }); } private static void CheckResultFlags(EvaluationContext context, string expr, DkmClrCompilationResultFlags expectedFlags, string expectedError = null) { ResultProperties resultProperties; string error; var testData = new CompilationTestData(); var result = context.CompileExpression(expr, out resultProperties, out error, testData); Assert.Equal(expectedError, error); Assert.NotEqual(expectedError == null, result == null); Assert.Equal(expectedFlags, resultProperties.Flags); } /// <summary> /// Set BooleanResult for bool expressions. /// </summary> [Fact] public void EvaluateBooleanExpression() { var source = @"class C { static bool F() { return false; } static void M(bool x, bool? y) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; context.CompileExpression("x", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.BoolResult, resultProperties.Flags); context.CompileExpression("y", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); context.CompileExpression("(bool)y", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult); context.CompileExpression("!y", out resultProperties, out error); Assert.Equal(DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); context.CompileExpression("false", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult); context.CompileExpression("F()", out resultProperties, out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.BoolResult | DkmClrCompilationResultFlags.ReadOnlyResult | DkmClrCompilationResultFlags.PotentialSideEffect); }); } /// <summary> /// Expression that is not an rvalue. /// </summary> [Fact] public void EvaluateNonRValueExpression() { var source = @"class C { object P { set { } } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "P", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor", error); } /// <summary> /// Expression that does not return a value. /// </summary> [Fact] public void EvaluateVoidExpression() { var source = @"class C { void M() { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.M()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); var methodData = testData.GetMethodData("<>x.<>m0"); var method = (MethodSymbol)methodData.Method; Assert.Equal(SpecialType.System_Void, method.ReturnType.SpecialType); Assert.True(method.ReturnsVoid); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""void C.M()"" IL_0006: ret }"); } [Fact] public void EvaluateMethodGroup() { var source = @"class C { void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.M", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?", error); } [Fact] public void AssignMethodGroup() { var source = @"class C { static void M() { object o; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "M", error: out error, testData: testData); Assert.Equal("error CS0428: Cannot convert method group 'M' to non-delegate type 'object'. Did you intend to invoke the method?", error); }); } [Fact] public void EvaluateConstant() { var source = @"class C { static void M() { const string x = ""str""; const int y = 2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("x[y]", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 2 IL_0000: ldstr ""str"" IL_0005: ldc.i4.2 IL_0006: call ""char string.this[int].get"" IL_000b: ret }"); }); } [Fact] public void AssignToConstant() { var source = @"class C { static void M() { const int x = 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "x", expr: "2", error: out error, testData: testData); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [Fact] public void AssignOutParameter() { var source = @"class C { static void F<T>(System.Func<T> f) { } static void M1(out int x) { x = 1; } static void M2<T>(ref T y) { y = default(T); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "C.M1"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "x", expr: "2", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: stind.i4 IL_0003: ret }"); context = CreateMethodContext( runtime, methodName: "C.M2"); testData = new CompilationTestData(); context.CompileAssignment( target: "y", expr: "default(T)", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: initobj ""T"" IL_0007: ret }"); testData = new CompilationTestData(); context.CompileExpression( expr: "F(() => y)", error: out error, testData: testData); Assert.Equal("error CS1628: Cannot use ref, out, or in parameter 'y' inside an anonymous method, lambda expression, query expression, or local function", error); }); } [Fact] public void EvaluateNamespace() { var source = @"namespace N { class C { static void M() { } } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.C.M", expr: "N", resultProperties: out resultProperties, error: out error); // Note: The native EE reports "CS0119: 'N' is a namespace, which is not valid in the given context" Assert.Equal("error CS0118: 'N' is a namespace but is used like a variable", error); } [Fact] public void EvaluateType() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "C", resultProperties: out resultProperties, error: out error); // The native EE returns a representation of the type (but not System.Type) // that the user can expand to see the base type. To enable similar // behavior, the expression compiler would probably return something // other than IL. Instead, we disallow this scenario. Assert.Equal("error CS0119: 'C' is a type, which is not valid in the given context", error); } [Fact] public void EvaluateObjectAddress() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( "@0x123 ?? @0xa1b2c3 ?? (object)$exception ?? @0XA1B2C3.GetHashCode()", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(ExceptionAlias()), out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 61 (0x3d) .maxstack 2 IL_0000: ldc.i4 0x123 IL_0005: conv.i8 IL_0006: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_000b: dup IL_000c: brtrue.s IL_003c IL_000e: pop IL_000f: ldc.i4 0xa1b2c3 IL_0014: conv.i8 IL_0015: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_001a: dup IL_001b: brtrue.s IL_003c IL_001d: pop IL_001e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0023: dup IL_0024: brtrue.s IL_003c IL_0026: pop IL_0027: ldc.i4 0xa1b2c3 IL_002c: conv.i8 IL_002d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectAtAddress(ulong)"" IL_0032: callvirt ""int object.GetHashCode()"" IL_0037: box ""int"" IL_003c: ret }"); testData = new CompilationTestData(); // Report overflow, even though native EE does not. context.CompileExpression( "@0xffff0000ffff0000ffff0000", out error, testData); Assert.Equal("error CS1021: Integral constant is too large", error); }); } [WorkItem(986227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/986227")] [Fact] public void RewriteCatchLocal() { var source = @"using System; class E<T> : Exception { } class C<T> { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: @"((Func<E<T>>)(() => { E<T> e1 = null; try { string.Empty.ToString(); } catch (E<T> e2) { e1 = e2; } catch { } return e1; }))()", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x<T>.<>c.<<>m0>b__0_0"); var method = (MethodSymbol)methodData.Method; var containingType = method.ContainingType; var returnType = (NamedTypeSymbol)method.ReturnType; // Return type E<T> with type argument T from <>c<T>. Assert.Equal(returnType.TypeArguments()[0].ContainingSymbol, containingType.ContainingType); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); Assert.Equal(1, locals.Length); // All locals of type E<T> with type argument T from <>c<T>. foreach (var local in locals) { var localType = (NamedTypeSymbol)local.Type.GetInternalSymbol(); var typeArg = localType.TypeArguments()[0]; Assert.Equal(typeArg.ContainingSymbol, containingType.ContainingType); } methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 1 .locals init (E<T> V_0) //e1 IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldsfld ""string string.Empty"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: leave.s IL_0015 } catch E<T> { IL_000f: stloc.0 IL_0010: leave.s IL_0015 } catch object { IL_0012: pop IL_0013: leave.s IL_0015 } IL_0015: ldloc.0 IL_0016: ret }"); }); } [WorkItem(986227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/986227")] [Fact] public void RewriteSequenceTemps() { var source = @"class C { object F; static void M<T>() where T : C, new() { T t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: "new T() { F = 1 }", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x.<>m0<T>()"); var method = (MethodSymbol)methodData.Method; var returnType = method.ReturnTypeWithAnnotations; Assert.Equal(TypeKind.TypeParameter, returnType.TypeKind); Assert.Equal(returnType.Type.ContainingSymbol, method); var locals = methodData.ILBuilder.LocalSlotManager.LocalsInOrder(); // The original local of type T from <>m0<T>. Assert.Equal(1, locals.Length); foreach (var local in locals) { var localType = (TypeSymbol)local.Type.GetInternalSymbol(); Assert.Equal(localType.ContainingSymbol, method); } methodData.VerifyIL( @"{ // Code size 23 (0x17) .maxstack 3 .locals init (T V_0) //t IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: stfld ""object C.F"" IL_0016: ret }"); }); } [Fact] public void GenericWithInterfaceConstraint() { var source = @"public interface I { string Key { get; set; } } class C { public static void M<T>(T t) where T : I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression( expr: "t.Key", error: out error, testData: testData); var methodData = testData.GetMethodData("<>x.<>m0<T>(T)"); var method = (MethodSymbol)methodData.Method; Assert.Equal(1, method.Parameters.Length); var eeTypeParameterSymbol = (EETypeParameterSymbol)method.Parameters[0].Type; Assert.Equal(1, eeTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics.Length); Assert.Equal("I", eeTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics[0].Name); methodData.VerifyIL( @"{ // Code size 14 (0xe) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: constrained. ""T"" IL_0008: callvirt ""string I.Key.get"" IL_000d: ret }"); }); } [Fact] public void AssignEmitError() { var longName = new string('P', 1100); var source = @"class C { static void M(object o) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: string.Format("new {{ {0} = 1 }}", longName), error: out error, testData: testData); Assert.Equal(error, string.Format("error CS7013: Name '<{0}>i__Field' exceeds the maximum length allowed in metadata.", longName)); }); } /// <summary> /// Attempt to assign where the rvalue is not an rvalue. /// </summary> [Fact] public void AssignVoidExpression() { var source = @"class C { static void M() { object o; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "M()", error: out error, testData: testData); Assert.Equal("error CS0029: Cannot implicitly convert type 'void' to 'object'", error); }); } [Fact] public void AssignUnsafeExpression() { var source = @"class C { static unsafe void M(int *p) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileAssignment( target: "p[1]", expr: "p[0] + 1", error: out error, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.4 IL_0002: add IL_0003: ldarg.0 IL_0004: ldind.i4 IL_0005: ldc.i4.1 IL_0006: add IL_0007: stind.i4 IL_0008: ret }"); }); } /// <remarks> /// This is interesting because we're always in an unsafe context in /// the expression compiler and so an await expression would not /// normally be allowed. /// </remarks> [WorkItem(1075258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075258")] [Fact] public void Await() { var source = @" using System; using System.Threading.Tasks; class C { static async Task<object> F() { return null; } static void G(Func<Task<object>> f) { } static void Main() { } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); context.CompileExpression("G(async() => await F())", out error, testData); Assert.Null(error); }); } /// <remarks> /// This would be illegal in any non-debugger context. /// </remarks> [WorkItem(1075258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075258")] [Fact] public void AwaitInUnsafeContext() { var source = @" using System; using System.Threading.Tasks; class C { static async Task<object> F() { return null; } static void G(Func<Task<object>> f) { } static void Main() { } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); context.CompileExpression(@"G(async() => { unsafe { return await F(); } })", out error, testData); Assert.Null(error); }); } /// <summary> /// Flow analysis should catch definite assignment errors /// for variables declared within the expression. /// </summary> [WorkItem(549, "https://github.com/dotnet/roslyn/issues/549")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/549")] public void FlowAnalysis() { var source = @"class C { static void M(bool b) { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object>)(() => { object o; if (b) o = 1; return o; }))()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0165: Use of unassigned local variable 'o'", error); } /// <summary> /// Should be possible to evaluate an expression /// of a type that the compiler does not normally /// support as a return value. /// </summary> [Fact] public void EvaluateRestrictedTypeExpression() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new System.RuntimeArgumentHandle()"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 10 (0xa) .maxstack 1 .locals init (System.RuntimeArgumentHandle V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.RuntimeArgumentHandle"" IL_0008: ldloc.0 IL_0009: ret }"); } [Fact] public void NestedNamespacesAndTypes() { var source = @"namespace N { namespace M { class A { class B { static object F() { return null; } } } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.M.A.B.F", expr: "F()"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (object V_0) IL_0000: call ""object N.M.A.B.F()"" IL_0005: ret }"); } [Fact] public void GenericMethod() { var source = @"class A<T> { class B<U, V> where V : U { static void M1<W, X>() where X : A<W>.B<object, U[]> { var t = default(T); var w = default(W); } static void M2() { var t = default(T); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "A.B.M1"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("(object)t ?? (object)w ?? typeof(V) ?? typeof(X)", out error, testData); var methodData = testData.GetMethodData("<>x<T, U, V>.<>m0<W, X>"); methodData.VerifyIL( @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, //t W V_1) //w IL_0000: ldloc.0 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_002c IL_0009: pop IL_000a: ldloc.1 IL_000b: box ""W"" IL_0010: dup IL_0011: brtrue.s IL_002c IL_0013: pop IL_0014: ldtoken ""V"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: dup IL_001f: brtrue.s IL_002c IL_0021: pop IL_0022: ldtoken ""X"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ret }"); // Verify generated type and method are generic. Assert.Equal(Cci.CallingConvention.Generic, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly)); var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef(result.TypeName); reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U", "V"); var methodDef = reader.GetMethodDef(typeDef, result.MethodName); reader.CheckTypeParameters(methodDef.GetGenericParameters(), "W", "X"); context = CreateMethodContext( runtime, methodName: "A.B.M2"); testData = new CompilationTestData(); context.CompileExpression("(object)t ?? typeof(T) ?? typeof(U)", out error, testData); methodData = testData.GetMethodData("<>x<T, U, V>.<>m0"); Assert.Equal(Cci.CallingConvention.Default, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [Fact] public void GenericClosureClass() { var source = @"using System; class C<T> { static U F<U>(Func<U> f) { return f(); } U M<U>(U u) { return u; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => this.M(u))", out error, testData); var methodData = testData.GetMethodData("<>x<T>.<>m0<U>"); methodData.VerifyIL(@" { // Code size 36 (0x24) .maxstack 3 .locals init (U V_0) IL_0000: newobj ""<>x<T>.<>c__DisplayClass0_0<U>..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""C<T> <>x<T>.<>c__DisplayClass0_0<U>.<>4__this"" IL_000c: dup IL_000d: ldarg.1 IL_000e: stfld ""U <>x<T>.<>c__DisplayClass0_0<U>.u"" IL_0013: ldftn ""U <>x<T>.<>c__DisplayClass0_0<U>.<<>m0>b__0()"" IL_0019: newobj ""System.Func<U>..ctor(object, System.IntPtr)"" IL_001e: call ""U C<T>.F<U>(System.Func<U>)"" IL_0023: ret }"); Assert.Equal(Cci.CallingConvention.Generic, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [WorkItem(976847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976847")] [Fact] public void VarArgMethod() { var source = @"class C { static void M(object o, __arglist) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new System.ArgIterator(__arglist)", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: arglist IL_0002: newobj ""System.ArgIterator..ctor(System.RuntimeArgumentHandle)"" IL_0007: ret }"); Assert.Equal(Cci.CallingConvention.ExtraArguments, ((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention); }); } [Fact] public void EvaluateLambdaWithParameters() { var source = @"class C { static void M(object x, object y) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "((System.Func<object, object, object>)((a, b) => a ?? b))(x, y)"); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 39 (0x27) .maxstack 3 IL_0000: ldsfld ""System.Func<object, object, object> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""object <>x.<>c.<<>m0>b__0_0(object, object)"" IL_0014: newobj ""System.Func<object, object, object>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<object, object, object> <>x.<>c.<>9__0_0"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: callvirt ""object System.Func<object, object, object>.Invoke(object, object)"" IL_0026: ret }"); } [Fact] public void EvaluateLambdaWithLocals() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object>)(() => { int x = 1; if (x < 0) { int y = 2; return y; } else { int z = 3; return z; } }))()"); } /// <summary> /// Lambda expression containing names /// that shadow names outside expression. /// </summary> [Fact] public void EvaluateLambdaWithNameShadowing() { var source = @"class C { static void M(object x) { object y; } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: @"((System.Func<object, object>)(y => { object x = y; return y; }))(x, y)", resultProperties: out resultProperties, error: out error); // Currently generating errors but this seems unnecessary and // an extra burden for the user. Consider allowing names // inside the expression that shadow names outside. Assert.Equal("error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter", error); } [Fact] public void EvaluateNestedLambdaClosedOverLocal() { var source = @"delegate object D(C c); class C { object F(D d) { return d(this); } static void Main(string[] args) { int x = 1; C y = new C(); } }"; var testData = Evaluate( source, OutputKind.ConsoleApplication, methodName: "C.Main", expr: "y.F(a => y.F(b => x))"); // Verify display class was included. testData.GetMethodData("<>x.<>c__DisplayClass0_0..ctor").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 3 .locals init (int V_0, //x C V_1, //y <>x.<>c__DisplayClass0_0 V_2) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: ldloc.1 IL_0008: stfld ""C <>x.<>c__DisplayClass0_0.y"" IL_000d: ldloc.2 IL_000e: ldloc.0 IL_000f: stfld ""int <>x.<>c__DisplayClass0_0.x"" IL_0014: ldloc.2 IL_0015: ldfld ""C <>x.<>c__DisplayClass0_0.y"" IL_001a: ldloc.2 IL_001b: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0(C)"" IL_0021: newobj ""D..ctor(object, System.IntPtr)"" IL_0026: callvirt ""object C.F(D)"" IL_002b: ret }"); } [Fact] public void EvaluateLambdaClosedOverThis() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f1, System.Func<object> f2, object g) { return null; } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => this.G))()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: ldfld ""object B.G"" IL_000b: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => this.F() ?? this.P))()", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: callvirt ""object B.F()"" IL_000b: dup IL_000c: brtrue.s IL_001a IL_000e: pop IL_000f: ldarg.0 IL_0010: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0015: callvirt ""object B.P.get"" IL_001a: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => F(new System.Func<object>(this.F), this.F, this.G)))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: dup IL_0007: ldvirtftn ""object B.F()"" IL_000d: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0012: ldarg.0 IL_0013: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0018: dup IL_0019: ldvirtftn ""object B.F()"" IL_001f: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0024: ldarg.0 IL_0025: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_002a: ldfld ""object B.G"" IL_002f: call ""object B.F(System.Func<object>, System.Func<object>, object)"" IL_0034: ret }"); } [WorkItem(905986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/905986")] [Fact] public void EvaluateLambdaClosedOverBase() { var source = @"class A { internal virtual object F() { return null; } internal object G; internal virtual object P { get { return null; } } } class B : A { internal override object F() { return null; } internal new object G; internal override object P { get { return null; } } static object F(System.Func<object> f1, System.Func<object> f2, object g) { return null; } void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => base.F() ?? base.P))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: call ""object A.F()"" IL_000b: dup IL_000c: brtrue.s IL_001a IL_000e: pop IL_000f: ldarg.0 IL_0010: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0015: call ""object A.P.get"" IL_001a: ret }"); testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "((System.Func<object>)(() => F(new System.Func<object>(base.F), base.F, base.G)))()"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 51 (0x33) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0006: ldftn ""object A.F()"" IL_000c: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0017: ldftn ""object A.F()"" IL_001d: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0022: ldarg.0 IL_0023: ldfld ""B <>x.<>c__DisplayClass0_0.<>4__this"" IL_0028: ldfld ""object A.G"" IL_002d: call ""object B.F(System.Func<object>, System.Func<object>, object)"" IL_0032: ret }"); } [Fact] public void EvaluateCapturedLocalsAlreadyCaptured() { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M(object x) { object y = 1; F(() => this.F(x)); F(() => base.F(y)); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, methodName: "B.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => this.F(x))", out error, testData); // Note there are duplicate local names (one from the original // display class, the other from the new display class in each case). // That is expected since we do not rename old locals nor do we // offset numbering of new locals. Having duplicate local names // in the PDB should be harmless though. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 3 .locals init (B.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0017: call ""void B.F(System.Func<object>)"" IL_001c: ret }"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0006: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" IL_000b: ldarg.0 IL_000c: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0011: ldfld ""object B.<>c__DisplayClass2_0.x"" IL_0016: callvirt ""object B.F(object)"" IL_001b: ret }"); testData = new CompilationTestData(); context.CompileExpression("F(() => base.F(y))", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 3 .locals init (B.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0017: call ""void B.F(System.Func<object>)"" IL_001c: ret }"); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0006: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" IL_000b: ldarg.0 IL_000c: ldfld ""B.<>c__DisplayClass2_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_0011: ldfld ""object B.<>c__DisplayClass2_0.y"" IL_0016: call ""object A.F(object)"" IL_001b: ret }"); }); } [WorkItem(994485, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994485")] [Fact] public void Repro994485() { var source = @" using System; enum E { A } class C { Action M(E? e) { Action a = () => e.ToString(); E ee = e.Value; return a; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("e.HasValue", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Action V_1, //a E V_2, //ee System.Action V_3) IL_0000: ldloc.0 IL_0001: ldflda ""E? C.<>c__DisplayClass0_0.e"" IL_0006: call ""bool E?.HasValue.get"" IL_000b: ret }"); }); } [Theory] [MemberData(nameof(NonNullTypesTrueAndFalseDebugDll))] public void EvaluateCapturedLocalsOutsideLambda(CSharpCompilationOptions options) { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M<T>(object x) where T : A, new() { F(() => this.F(x)); if (x != null) { #line 999 var y = new T(); var z = 1; F(() => base.F(y)); } else { var w = 2; F(() => w); } } }"; var compilation0 = CreateCompilation(source, options: options); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "B.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("this.F(y)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 23 (0x17) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.2 IL_0007: ldfld ""T B.<>c__DisplayClass2_1<T>.y"" IL_000c: box ""T"" IL_0011: callvirt ""object B.F(object)"" IL_0016: ret }"); testData = new CompilationTestData(); context.CompileExpression("base.F(x)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.0 IL_0007: ldfld ""object B.<>c__DisplayClass2_0<T>.x"" IL_000c: call ""object A.F(object)"" IL_0011: ret }"); }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30767")] [WorkItem(30767, "https://github.com/dotnet/roslyn/issues/30767")] public void EvaluateCapturedLocalsOutsideLambda_PlusNullable() { var source = @"class A { internal virtual object F(object o) { return 1; } } class B : A { internal override object F(object o) { return 2; } static void F(System.Func<object> f) { f(); } void M<T>(object x) where T : A, new() { F(() => this.F(x)); if (x != null) { #line 999 var y = new T(); var z = 1; F(() => base.F(y)); } else { var w = 2; F(() => w); } } }"; var compilation0 = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugDll)); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "B.M", atLineNumber: 999); string error; var testData = new CompilationTestData(); context.CompileExpression("this.F(y)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 23 (0x17) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.2 IL_0007: ldfld ""T B.<>c__DisplayClass2_1<T>.y"" IL_000c: box ""T"" IL_0011: callvirt ""object B.F(object)"" IL_0016: ret }"); testData = new CompilationTestData(); context.CompileExpression("base.F(x)", out error, testData); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (B.<>c__DisplayClass2_0<T> V_0, //CS$<>8__locals0 bool V_1, B.<>c__DisplayClass2_1<T> V_2, //CS$<>8__locals1 int V_3, //z B.<>c__DisplayClass2_2<T> V_4) IL_0000: ldloc.0 IL_0001: ldfld ""B B.<>c__DisplayClass2_0<T>.<>4__this"" IL_0006: ldloc.0 IL_0007: ldfld ""object B.<>c__DisplayClass2_0<T>.x"" IL_000c: call ""object A.F(object)"" IL_0011: ret }"); }); } [Fact] public void EvaluateCapturedLocalsInsideLambda() { var source = @"class C { static void F(System.Func<object> f) { f(); } void M(C x) { F(() => x ?? this); if (x != null) { var y = new C(); F(() => { var z = 1; return y ?? this; }); } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.<>c__DisplayClass1_1.<M>b__1", expr: "y ?? this ?? (object)z"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 32 (0x20) .maxstack 2 .locals init (int V_0, //z object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_1.y"" IL_0006: dup IL_0007: brtrue.s IL_001f IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld ""C.<>c__DisplayClass1_0 C.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_0010: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0015: dup IL_0016: brtrue.s IL_001f IL_0018: pop IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ret }"); } /// <summary> /// Values of existing locals must be copied to new display /// classes generated in the compiled expression. /// </summary> [Fact] public void CopyLocalsToDisplayClass() { var source = @"class C { static void F(System.Func<object> f) { f(); } void M(int p, int q) { int x = 1; if (p > 0) { #line 999 int y = 2; F(() => x + q); } } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", atLineNumber: 999, expr: "F(() => x + y + p + q)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 43 (0x2b) .maxstack 3 .locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 bool V_1, int V_2) //y IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldloc.0 IL_0007: stfld ""C.<>c__DisplayClass1_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000c: dup IL_000d: ldloc.2 IL_000e: stfld ""int <>x.<>c__DisplayClass0_0.y"" IL_0013: dup IL_0014: ldarg.1 IL_0015: stfld ""int <>x.<>c__DisplayClass0_0.p"" IL_001a: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0020: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0025: call ""void C.F(System.Func<object>)"" IL_002a: ret }"); } [Fact] public void EvaluateNewAnonymousType() { var source = @"class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new { A = 1, B = 2 }"); // Verify anonymous type was generated (find an // accessor of one of the generated properties). testData.GetMethodData("<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>.A.get").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""<A>j__TPar <>f__AnonymousType0<<A>j__TPar, <B>j__TPar>.<A>i__Field"" IL_0006: ret }"); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0007: ret }"); } [Fact] public void EvaluateExistingAnonymousType() { var source = @"class C { static object F() { return new { A = new { }, B = 2 }; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.F", expr: "new { A = 1, B = new { } }"); // Verify anonymous types were generated. (There // shouldn't be any reuse of existing anonymous types // since the existing types were from metadata.) var methods = testData.GetMethodsByName(); Assert.True(methods.ContainsKey("<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>..ctor(<A>j__TPar, <B>j__TPar)")); Assert.True(methods.ContainsKey("<>f__AnonymousType1..ctor()")); // Verify evaluation method. testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 2 .locals init (object V_0) IL_0000: ldc.i4.1 IL_0001: newobj ""<>f__AnonymousType1..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<int, <empty anonymous type>>..ctor(int, <empty anonymous type>)"" IL_000b: ret }"); } /// <summary> /// Should re-use anonymous types from the module /// containing the current frame, so new instances can /// be used interchangeably with existing instances. /// </summary> [WorkItem(3188, "https://github.com/dotnet/roslyn/issues/3188")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/3188")] public void EvaluateExistingAnonymousType_2() { var source = @"class C { static void M() { var o = new { P = 1 }; } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "o == new { P = 2 }"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ ... }"); } /// <summary> /// Generate PrivateImplementationDetails class /// for initializer expressions. /// </summary> [Fact] public void EvaluateInitializerExpression() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll.WithModuleName("MODULE")); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("new [] { 1, 2, 3, 4, 5 }", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int[]", ((MethodSymbol)methodData.Method).ReturnType.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 3 IL_0000: ldc.i4.5 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=20 <PrivateImplementationDetails>.4F6ADDC9659D6FB90FE94B6688A79F2A1FA8D36EC43F8F3E1D9B6528C448A384"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: ret }"); }); } // Scenario from the lambda / anonymous type milestone. [Fact] public void EvaluateLINQExpression() { var source = @"using System.Collections.Generic; using System.Linq; class Employee { internal string Name; internal int Salary; internal List<Employee> Reports; } class Program { static void F(Employee mgr) { var o = mgr.Reports.Where(e => e.Salary < 100).Select(e => new { e.Name, e.Salary }).First(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "Program.F"); string error; var testData = new CompilationTestData(); context.CompileExpression("mgr.Reports.Where(e => e.Salary < 100).Select(e => new { e.Name, e.Salary }).First()", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 84 (0x54) .maxstack 3 .locals init (<>f__AnonymousType0<string, int> V_0) //o IL_0000: ldarg.0 IL_0001: ldfld ""System.Collections.Generic.List<Employee> Employee.Reports"" IL_0006: ldsfld ""System.Func<Employee, bool> <>x.<>c.<>9__0_0"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0014: ldftn ""bool <>x.<>c.<<>m0>b__0_0(Employee)"" IL_001a: newobj ""System.Func<Employee, bool>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<Employee, bool> <>x.<>c.<>9__0_0"" IL_0025: call ""System.Collections.Generic.IEnumerable<Employee> System.Linq.Enumerable.Where<Employee>(System.Collections.Generic.IEnumerable<Employee>, System.Func<Employee, bool>)"" IL_002a: ldsfld ""System.Func<Employee, <anonymous type: string Name, int Salary>> <>x.<>c.<>9__0_1"" IL_002f: dup IL_0030: brtrue.s IL_0049 IL_0032: pop IL_0033: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0038: ldftn ""<anonymous type: string Name, int Salary> <>x.<>c.<<>m0>b__0_1(Employee)"" IL_003e: newobj ""System.Func<Employee, <anonymous type: string Name, int Salary>>..ctor(object, System.IntPtr)"" IL_0043: dup IL_0044: stsfld ""System.Func<Employee, <anonymous type: string Name, int Salary>> <>x.<>c.<>9__0_1"" IL_0049: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Name, int Salary>> System.Linq.Enumerable.Select<Employee, <anonymous type: string Name, int Salary>>(System.Collections.Generic.IEnumerable<Employee>, System.Func<Employee, <anonymous type: string Name, int Salary>>)"" IL_004e: call ""<anonymous type: string Name, int Salary> System.Linq.Enumerable.First<<anonymous type: string Name, int Salary>>(System.Collections.Generic.IEnumerable<<anonymous type: string Name, int Salary>>)"" IL_0053: ret }"); }); } [Fact] public void ExpressionTree() { var source = @"using System; using System.Linq.Expressions; class C { static object F(Expression<Func<object>> e) { var f = e.Compile(); return f(); } static void M(int o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => o + 1)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 100 (0x64) .maxstack 3 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""int <>x.<>c__DisplayClass0_0.o"" IL_000c: ldtoken ""<>x.<>c__DisplayClass0_0"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001b: ldtoken ""int <>x.<>c__DisplayClass0_0.o"" IL_0020: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0025: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002a: ldc.i4.1 IL_002b: box ""int"" IL_0030: ldtoken ""int"" IL_0035: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_003f: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0044: ldtoken ""object"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0053: ldc.i4.0 IL_0054: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0059: call ""System.Linq.Expressions.Expression<System.Func<object>> System.Linq.Expressions.Expression.Lambda<System.Func<object>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_005e: call ""object C.F(System.Linq.Expressions.Expression<System.Func<object>>)"" IL_0063: ret }"); }); } /// <summary> /// DiagnosticsPass must be run on evaluation method. /// </summary> [WorkItem(530404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530404")] [Fact] public void DiagnosticsPass() { var source = @"using System; using System.Linq.Expressions; class C { static object F(Expression<Func<object>> e) { var f = e.Compile(); return f(); } static void M() { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("F(() => null ?? new object())", out error, testData); Assert.Equal("error CS0845: An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side", error); }); } [WorkItem(935651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/935651")] [Fact] public void EvaluatePropertySet() { var source = @"class C { object P { get; set; } void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.P = null"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 3 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: dup IL_0003: stloc.0 IL_0004: callvirt ""void C.P.set"" IL_0009: ldloc.0 IL_000a: ret }"); } /// <summary> /// Evaluating an expression where the imported namespace /// is valid but the required reference is missing. /// </summary> [Fact] public void EvaluateExpression_MissingReferenceImportedNamespace() { // System.Linq namespace is available but System.Core is // missing since the reference was not needed in compilation. var source = @"using System.Linq; class C { static void M(object []o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( "o.First()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal("error CS1061: 'object[]' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'object[]' could be found (are you missing a using directive or an assembly reference?)", error); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); }); } [Fact] public void EvaluateExpression_UnusedImportedType() { var source = @"using E=System.Linq.Enumerable; class C { static void M(object []o) { } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("E.First(o)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object System.Linq.Enumerable.First<object>(System.Collections.Generic.IEnumerable<object>)"" IL_0006: ret }"); }); } [Fact] public void NetModuleReference() { var sourceNetModule = @"class A { }"; var source1 = @"class B : A { void M() { } }"; var netModuleRef = CreateCompilation(sourceNetModule, options: TestOptions.DebugModule).EmitToImageReference(); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, references: new[] { netModuleRef }); WithRuntimeInstance(compilation1, runtime => { var context = CreateMethodContext(runtime, "B.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); }); } /// <summary> /// Netmodules with same name. /// </summary> [Fact] [WorkItem(30031, "https://github.com/dotnet/roslyn/issues/30031")] public void NetModuleDuplicateReferences() { // Netmodule 0 var sourceN0 = @"public class A0 { public int F0; }"; // Netmodule 1 var sourceN1 = @"public class A1 { public int F1; }"; // Netmodule 2 var sourceN2 = @"public class A2 { public int F2; }"; // DLL 0 + netmodule 0 var sourceD0 = @"public class B0 : A0 { }"; // DLL 1 + netmodule 0 var sourceD1 = @"public class B1 : A0 { }"; // DLL 2 + netmodule 1 + netmodule 2 var source = @"class C { static B0 x; static B1 y; static A1 z; static A2 w; static void M() { } }"; var assemblyName = ExpressionCompilerUtilities.GenerateUniqueName(); var compilationN0 = CreateCompilation( sourceN0, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N0"); var referenceN0 = ModuleMetadata.CreateFromImage(compilationN0.EmitToArray()).GetReference(display: assemblyName + "_N0"); var compilationN1 = CreateCompilation( sourceN1, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N0"); // Note: "_N0" not "_N1" var referenceN1 = ModuleMetadata.CreateFromImage(compilationN1.EmitToArray()).GetReference(display: assemblyName + "_N0"); var compilationN2 = CreateCompilation( sourceN2, options: TestOptions.DebugModule, assemblyName: assemblyName + "_N2"); var referenceN2 = ModuleMetadata.CreateFromImage(compilationN2.EmitToArray()).GetReference(display: assemblyName + "_N2"); var compilationD0 = CreateCompilation( sourceD0, options: TestOptions.DebugDll, assemblyName: assemblyName + "_D0", references: new MetadataReference[] { referenceN0 }); var referenceD0 = AssemblyMetadata.CreateFromImage(compilationD0.EmitToArray()).GetReference(display: assemblyName + "_D0"); var compilationD1 = CreateCompilation( sourceD1, options: TestOptions.DebugDll, assemblyName: assemblyName + "_D1", references: new MetadataReference[] { referenceN0 }); var referenceD1 = AssemblyMetadata.CreateFromImage(compilationD1.EmitToArray()).GetReference(display: assemblyName + "_D1"); var compilation = CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: assemblyName, references: new MetadataReference[] { referenceN1, referenceN2, referenceD0, referenceD1 }); Assert.Equal(((ModuleMetadata)referenceN0.GetMetadataNoCopy()).Name, ((ModuleMetadata)referenceN1.GetMetadataNoCopy()).Name); // different netmodule, same name var references = new[] { MscorlibRef, referenceD0, referenceN0, // From D0 referenceD1, referenceN0, // From D1 referenceN1, // From D2 referenceN2, // From D2 }; WithRuntimeInstance(compilation, references, runtime => { var context = CreateMethodContext(runtime, "C.M"); // Expression references ambiguous modules. ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F0 + y.F0", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS7079: The type 'A0' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); context.CompileExpression( "y.F0", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS7079: The type 'A0' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); context.CompileExpression( "z.F1", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Empty(missingAssemblyIdentities); Assert.Equal("error CS7079: The type 'A1' is defined in a module that has not been added. You must add the module '" + assemblyName + "_N0.netmodule'.", error); // Expression does not reference ambiguous modules. var testData = new CompilationTestData(); context.CompileExpression("w.F2", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldsfld ""A2 C.w"" IL_0005: ldfld ""int A2.F2"" IL_000a: ret }"); }); } [Fact] public void SizeOfReferenceType() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "sizeof(C)", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')", error); } [Fact] public void SizeOfValueType() { var source = @"struct S { } class C { static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "sizeof(S)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: sizeof ""S"" IL_0006: ret }"); } /// <summary> /// Unnamed temporaries at the end of the local /// signature should be preserved. /// </summary> [Fact] public void TrailingUnnamedTemporaries() { var source = @"class C { object F; static bool M(object[] c) { foreach (var o in c) { if (o != null) return true; } return false; } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new C() { F = 1 }", resultProperties: out resultProperties, error: out error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 3 .locals init (object[] V_0, int V_1, object V_2, bool V_3, bool V_4) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: box ""int"" IL_000c: stfld ""object C.F"" IL_0011: ret }"); } [WorkItem(958448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958448")] [Fact] public void ConditionalAttribute() { var source = @"using System.Diagnostics; class C { static void M(int x) { } [Conditional(""D"")] static void F(object o) { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(x + 1)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: add IL_0003: box ""int"" IL_0008: call ""void C.F(object)"" IL_000d: ret }"); } [WorkItem(958448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958448")] [Fact] public void ConditionalAttribute_CollectionInitializer() { var source = @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C : IEnumerable { private List<object> c = new List<object>(); [Conditional(""D"")] void Add(object o) { this.c.Add(o); } IEnumerator IEnumerable.GetEnumerator() { return this.c.GetEnumerator(); } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "new C() { 1, 2 }"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: box ""int"" IL_000c: callvirt ""void C.Add(object)"" IL_0011: dup IL_0012: ldc.i4.2 IL_0013: box ""int"" IL_0018: callvirt ""void C.Add(object)"" IL_001d: ret }"); } [Fact] public void ConditionalAttribute_Delegate() { var source = @"using System.Diagnostics; delegate void D(); class C { [Conditional(""D"")] static void F() { } static void G(D d) { } static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "G(F)", resultProperties: out resultProperties, error: out error); // Should delegates to [Conditional] methods be supported? Assert.Equal("error CS1618: Cannot create delegate with 'C.F()' because it or a method it overrides has a Conditional attribute", error); } [Fact] public void StaticDelegate() { var source = @"delegate void D(); class C { static void F() { } static void G(D d) { } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "G(F)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void C.F()"" IL_0007: newobj ""D..ctor(object, System.IntPtr)"" IL_000c: call ""void C.G(D)"" IL_0011: ret }"); } [Fact] public void StaticLambda() { var source = @" delegate int D(int x); class C { void M() { } } "; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "((D)(x => x + x))(1)"); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldsfld ""D <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""int <>x.<>c.<<>m0>b__0_0(int)"" IL_0014: newobj ""D..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D <>x.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: callvirt ""int D.Invoke(int)"" IL_0025: ret }"); } [WorkItem(984509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984509")] [Fact] public void LambdaContainingIncrementOperator() { var source = @"class C { static void M(int i) { } }"; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "(System.Action)(() => i++)", resultProperties: out resultProperties, error: out error); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.i"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld ""int <>x.<>c__DisplayClass0_0.i"" IL_0010: ret }"); } [Fact] public void NestedGenericTypes() { var source = @" class C<T> { class D<U> { void M(U u, T t, System.Type type1, System.Type type2) { } } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.D.M", expr: "M(u, t, typeof(U), typeof(T))", resultProperties: out resultProperties, error: out error); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL( @"{ // Code size 29 (0x1d) .maxstack 5 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldtoken ""U"" IL_0008: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000d: ldtoken ""T"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: callvirt ""void C<T>.D<U>.M(U, T, System.Type, System.Type)"" IL_001c: ret }"); } [Fact] public void NestedGenericTypes_GenericMethod() { var source = @" class C<T> { class D<U> { void M<V>(V v, U u, T t, System.Type type1, System.Type type2, System.Type type3) { } } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.D.M", expr: "M(v, u, t, typeof(V), typeof(U), typeof(T))", resultProperties: out resultProperties, error: out error); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x<T, U>.<>m0<V>").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 7 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: ldtoken ""V"" IL_0009: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000e: ldtoken ""U"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldtoken ""T"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: callvirt ""void C<T>.D<U>.M<V>(V, U, T, System.Type, System.Type, System.Type)"" IL_0027: ret }"); } [WorkItem(1000946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1000946")] [Fact] public void BaseExpression() { var source = @" class Base { } class Derived : Base { void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "Derived.M", expr: "base", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0175: Use of keyword 'base' is not valid in this context", error); } [Fact] public void StructBaseCall() { var source = @" struct S { public void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "base.ToString()", resultProperties: out resultProperties, error: out error); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""string System.ValueType.ToString()"" IL_0010: ret }"); } [WorkItem(1010922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010922")] [Fact] public void IntOverflow() { var source = @" class C { public void M() { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("checked(2147483647 + 1)", out error, testData); Assert.Equal("error CS0220: The operation overflows at compile time in checked mode", error); testData = new CompilationTestData(); context.CompileExpression("unchecked(2147483647 + 1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: ret }"); testData = new CompilationTestData(); context.CompileExpression("2147483647 + 1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: ret }"); }); } [WorkItem(1012956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1012956")] [Fact] public void AssignmentConversion() { var source = @" class C { public void M(uint u) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("u = 2147483647 + 1", out error, testData); Assert.Equal("error CS0031: Constant value '-2147483648' cannot be converted to a 'uint'", error); testData = new CompilationTestData(); context.CompileAssignment("u", "2147483647 + 1", out error, testData); Assert.Equal("error CS0031: Constant value '-2147483648' cannot be converted to a 'uint'", error); testData = new CompilationTestData(); context.CompileExpression("u = 2147483647 + 1u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldc.i4 0x80000000 IL_0005: dup IL_0006: starg.s V_1 IL_0008: ret }"); testData = new CompilationTestData(); context.CompileAssignment("u", "2147483647 + 1u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldc.i4 0x80000000 IL_0005: starg.s V_1 IL_0007: ret }"); }); } [WorkItem(1016530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016530")] [Fact] public void EvaluateStatement() { var source = @" class C { void M() { } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "throw new System.Exception()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS8115: A throw expression is not allowed in this context.", error); } [WorkItem(1016555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016555")] [Fact] public void UnmatchedCloseAndOpenParens() { var source = @"class C { static void M() { object o = 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileAssignment( target: "o", expr: "(System.Func<object>)(() => 2))(", error: out error, testData: testData); Assert.Equal("error CS1073: Unexpected token ')'", error); }); } [WorkItem(1015887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015887")] [Fact] public void DateTimeFieldConstant() { var source = @".class public C { .field public static initonly valuetype [mscorlib]System.DateTime D .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = {int64(633979872000000000)} .method public specialname rtspecialname instance void .ctor() { ret } .method public static void M() { ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("D", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""System.DateTime C.D"" IL_0005: ret }"); } [WorkItem(1015887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015887")] [Fact] public void DecimalFieldConstant() { var source = @" struct S { public const decimal D = 3.14M; public void M() { System.Console.WriteLine(); } } "; string error; ResultProperties resultProperties; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "S.M", expr: "D", resultProperties: out resultProperties, error: out error); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 15 (0xf) .maxstack 5 IL_0000: ldc.i4 0x13a IL_0005: ldc.i4.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldc.i4.2 IL_0009: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000e: ret }"); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void IteratorParameter() { var source = @"class C { System.Collections.IEnumerable F(int x) { yield return x; yield return this; // Until iterators always capture 'this', do it explicitly. } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((MethodSymbol)methodData.Method).ReturnType.SpecialType); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.x"" IL_0006: ret } "); }); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void IteratorGenericLocal() { var source = @"class C<T> { System.Collections.IEnumerable F(int x) { T t = default(T); yield return t; t.ToString(); yield return this; // Until iterators always capture 'this', do it explicitly. } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); var methodData = testData.GetMethodData("<>x<T>.<>m0"); Assert.Equal("T", ((MethodSymbol)methodData.Method).ReturnType.Name); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""T C<T>.<F>d__0.<t>5__1"" IL_0006: ret } "); }); } [WorkItem(1028808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028808")] [Fact] public void StaticLambdaInDisplayClass() { var source = @".class private auto ansi beforefieldinit C extends [mscorlib]System.Object { .class auto ansi sealed nested private beforefieldinit '<>c__DisplayClass2' extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .field public class C c .field private static class [mscorlib]System.Action`1<int32> 'CS$<>9__CachedAnonymousMethodDelegate4' .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method private hidebysig static void '<Test>b__1'(int32 x) cil managed { ret } } // Need some static method 'Test' with 'x' in scope. .method private hidebysig static void Test(int32 x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(source); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, methodName: "C.<>c__DisplayClass2.<Test>b__1"); string error; var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void ConditionalAccessExpressionType() { var source = @"class C { int F() { return 0; } C G() { return null; } void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this?.F()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int?", ((MethodSymbol)methodData.Method).ReturnTypeWithAnnotations.ToDisplayString()); methodData.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 1 .locals init (int? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""int?"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: call ""int C.F()"" IL_0013: newobj ""int?..ctor(int)"" IL_0018: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("(new C())?.G()?.F()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal("int?", ((MethodSymbol)methodData.Method).ReturnTypeWithAnnotations.ToDisplayString()); testData = new CompilationTestData(); result = context.CompileExpression("G()?.M()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""C C.G()"" IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ret IL_000b: call ""void C.M()"" IL_0010: ret }"); }); } [Fact] public void CallerInfoAttributes() { var source = @"using System.Runtime.CompilerServices; class C { static object F( [CallerFilePath]string path = null, [CallerMemberName]string member = null, [CallerLineNumber]int line = 0) { return string.Format(""[{0}] [{1}] [{2}]"", path, member, line); } static void Main() { } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("F()", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldstr ""Main"" IL_000a: ldc.i4.1 IL_000b: call ""object C.F(string, string, int)"" IL_0010: ret }"); }); } [Fact] public void ExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml.Linq; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0, System.Xml.Linq.LoadOptions V_1) IL_0000: ldc.i4.0 IL_0001: stloc.1 IL_0002: ldloca.s V_1 IL_0004: constrained. ""System.Xml.Linq.LoadOptions"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ret } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("SXL.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("LO.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("X.System.Xml.Linq.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("X::System.Xml.Linq.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); }); } [Fact] public void ExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0, System.Xml.Linq.LoadOptions V_1) IL_0000: ldc.i4.0 IL_0001: stloc.1 IL_0002: ldloca.s V_1 IL_0004: constrained. ""System.Xml.Linq.LoadOptions"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ret } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("A.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); result = context.CompileExpression("B.LoadOptions.None.ToString()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); }); } [Fact] public void ExternAliasForMultipleAssemblies() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); var d = new X::System.Xml.XmlDocument(); return 1; } } "; var comp = CreateCompilation( source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")), SystemXmlRef.WithAliases(ImmutableArray.Create("X")) }); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new X::System.Xml.XmlDocument()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 6 (0x6) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0) IL_0000: newobj ""System.Xml.XmlDocument..ctor()"" IL_0005: ret } "); testData = new CompilationTestData(); result = context.CompileExpression("X::System.Xml.Linq.LoadOptions.None", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (System.Xml.Linq.LoadOptions V_0) IL_0000: ldc.i4.0 IL_0001: ret } "); }); } [Fact] [WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")] public void FieldLikeEvent() { var source = @" class C { event System.Action E; void M() { } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var actionType = context.Compilation.GetWellKnownType(WellKnownType.System_Action); ResultProperties resultProperties; string error; CompilationTestData testData; CompileResult result; CompilationTestData.MethodData methodData; // Inspect the value. testData = new CompilationTestData(); result = context.CompileExpression("E", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""System.Action C.E"" IL_0006: ret } "); // Invoke the delegate. testData = new CompilationTestData(); result = context.CompileExpression("E()", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""System.Action C.E"" IL_0006: callvirt ""void System.Action.Invoke()"" IL_000b: ret } "); // Assign to the event. testData = new CompilationTestData(); result = context.CompileExpression("E = null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 11 (0xb) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldnull IL_0002: dup IL_0003: stloc.0 IL_0004: stfld ""System.Action C.E"" IL_0009: ldloc.0 IL_000a: ret } "); // Event (compound) assignment. testData = new CompilationTestData(); result = context.CompileExpression("E += null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: callvirt ""void C.E.add"" IL_0007: ret } "); }); } [Fact] [WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")] public void FieldLikeEvent_WinRT() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .field private class [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1<class [mscorlib]System.Action> E .method public hidebysig specialname instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_E(class [mscorlib]System.Action 'value') cil managed { ldnull throw } .method public hidebysig specialname instance void remove_E(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .event [mscorlib]System.Action E { .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C::add_E(class [mscorlib]System.Action) .removeon instance void C::remove_E(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } // end of event C::E .method public hidebysig instance void M() cil managed { ret } } // end of class C "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource); var runtime = CreateRuntimeInstance(module, WinRtRefs); var context = CreateMethodContext(runtime, "C.M"); var actionType = context.Compilation.GetWellKnownType(WellKnownType.System_Action); ResultProperties resultProperties; string error; CompilationTestData testData; CompileResult result; CompilationTestData.MethodData methodData; // Inspect the value. testData = new CompilationTestData(); result = context.CompileExpression("E", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(actionType, ((MethodSymbol)methodData.Method).ReturnType); methodData.VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> C.E"" IL_0006: call ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.GetOrCreateEventRegistrationTokenTable(ref System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>)"" IL_000b: callvirt ""System.Action System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.InvocationList.get"" IL_0010: ret } "); // Invoke the delegate. testData = new CompilationTestData(); result = context.CompileExpression("E()", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 22 (0x16) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> C.E"" IL_0006: call ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action> System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.GetOrCreateEventRegistrationTokenTable(ref System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>)"" IL_000b: callvirt ""System.Action System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<System.Action>.InvocationList.get"" IL_0010: callvirt ""void System.Action.Invoke()"" IL_0015: ret } "); // Assign to the event. testData = new CompilationTestData(); result = context.CompileExpression("E = null", out resultProperties, out error, testData); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 48 (0x30) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldftn ""void C.E.remove"" IL_0007: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_000c: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveAllEventHandlers(System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>)"" IL_0011: ldarg.0 IL_0012: ldftn ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C.E.add"" IL_0018: newobj ""System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_001d: ldarg.0 IL_001e: ldftn ""void C.E.remove"" IL_0024: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_0029: ldnull IL_002a: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler<System.Action>(System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action)"" IL_002f: ret } "); // Event (compound) assignment. testData = new CompilationTestData(); result = context.CompileExpression("E += null", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); methodData = testData.GetMethodData("<>x.<>m0"); Assert.True(((MethodSymbol)methodData.Method).ReturnsVoid); methodData.VerifyIL(@" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldftn ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken C.E.add"" IL_0007: newobj ""System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_000c: ldarg.0 IL_000d: ldftn ""void C.E.remove"" IL_0013: newobj ""System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>..ctor(object, System.IntPtr)"" IL_0018: ldnull IL_0019: call ""void System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler<System.Action>(System.Func<System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action<System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken>, System.Action)"" IL_001e: ret } "); } [WorkItem(1079749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079749")] [Fact] public void RangeVariableError() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "from c in \"ABC\" select c", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Equal(new AssemblyIdentity("System.Core"), missingAssemblyIdentities.Single()); Assert.Equal("error CS1935: Could not find an implementation of the query pattern for source type 'string'. 'Select' not found. Are you missing required assembly references or a using directive for 'System.Linq'?", error); }); } [WorkItem(1079762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079762")] [Fact] public void Bug1079762() { var source = @"class C { static void F(System.Func<object, bool> f, object o) { f(o); } static void M(object x, object y) { F(z => z != null && x != null, 3); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<>c__DisplayClass1_0.<M>b__0"); string error; var testData = new CompilationTestData(); context.CompileExpression("z", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret }"); testData = new CompilationTestData(); context.CompileExpression("y", out error, testData); Assert.Equal("error CS0103: The name 'y' does not exist in the current context", error); }); } [WorkItem(1079762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079762")] [Fact] public void LambdaParameter() { var source = @"class C { static void M() { System.Func<object, bool> f = z => z != null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<>c.<M>b__0_0"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("z", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret }"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void StaticTypeImport() { var source = @" using static System.Math; class C { static void M() { Max(1, 2); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("Min(1, 2)", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: call ""int System.Math.Min(int, int)"" IL_0007: ret }"); }); } [WorkItem(1014763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1014763")] [Fact] public void NonStateMachineTypeParameter() { var source = @" using System.Collections.Generic; class C { static IEnumerable<T> I<T>(T[] tt) { return tt; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.I"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(T)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (System.Collections.Generic.IEnumerable<T> V_0) IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); }); } [WorkItem(1014763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1014763")] [Fact] public void StateMachineTypeParameter() { var source = @" using System.Collections.Generic; class C { static IEnumerable<T> I<T>(T[] tt) { foreach (T t in tt) { yield return t; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<I>d__0.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(T)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (int V_0) IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); }); } [WorkItem(1085642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085642")] [Fact] public void ModuleWithBadImageFormat() { var source = @" class C { int F = 1; static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); using (var pinnedMetadata = new PinnedBlob(TestResources.ExpressionCompiler.NoValidTables)) { var corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, default(Guid)); var runtime = RuntimeInstance.Create(new[] { corruptMetadata, comp.ToModuleInstance(), MscorlibRef.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); // Verify that we can still evaluate expressions for modules that are not corrupt. context.CompileExpression("(new C()).F", out resultProperties, out error, testData); Assert.Null(error); Assert.Equal(DkmClrCompilationResultFlags.None, resultProperties.Flags); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""C..ctor()"" IL_0005: ldfld ""int C.F"" IL_000a: ret }"); } } [WorkItem(1089688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089688")] [Fact] public void MissingType() { var libSource = @" public class Missing { } "; var source = @" public class C { Missing field; public void M(Missing parameter) { Missing local; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateCompilation(source, new[] { libRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime => { var context = CreateMethodContext(runtime, "C.M"); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; void verify(string expr) { context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } verify("M(null)"); verify("field"); verify("field.Method"); verify("parameter"); verify("parameter.Method"); verify("local"); verify("local.Method"); // Note that even expressions that don't require the missing type will fail because // the method we synthesize refers to the original locals and parameters. verify("0"); }); } [WorkItem(1089688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089688")] [Fact] public void UseSiteWarning() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1Ref = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: signedDllOptions).EmitToImageReference(); var libBv2Ref = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: signedDllOptions).EmitToImageReference(); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A : B { } "; var libAv1Ref = CreateCompilation(libASource, new[] { libBv1Ref }, assemblyName: "A", options: signedDllOptions).EmitToImageReference(); var source = @" public class Source { public void Test() { object o = new A(); } } "; var comp = CreateCompilation(source, new[] { libAv1Ref, libBv2Ref }, TestOptions.DebugDll); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); WithRuntimeInstance(comp, new[] { MscorlibRef, libAv1Ref, libBv2Ref }, runtime => { var context = CreateMethodContext(runtime, "Source.Test"); string error; var testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); // Even though the method's return type has a use-site warning, we are able to evaluate the expression. Assert.Equal(ErrorCode.WRN_UnifyReferenceMajMin, (ErrorCode)((MethodSymbol)methodData.Method).ReturnType.GetUseSiteDiagnostic().Code); methodData.VerifyIL(@" { // Code size 6 (0x6) .maxstack 1 .locals init (object V_0) //o IL_0000: newobj ""A..ctor()"" IL_0005: ret }"); }); } [WorkItem(1090458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090458")] [Fact] public void ObsoleteAttribute() { var source = @" using System; using System.Diagnostics;   class C { static void Main() { C c = new C(); } [Obsolete(""Hello"", true)] int P { get; set; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); ResultProperties resultProperties; string error; context.CompileExpression("c.P", out resultProperties, out error); Assert.Null(error); }); } [WorkItem(1090458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090458")] [Fact] public void DeprecatedAttribute() { var source = @" using System; using Windows.Foundation.Metadata;   class C { static void Main() { C c = new C(); } [Deprecated(""Hello"", DeprecationType.Remove, 1)] int P { get; set; } } namespace Windows.Foundation.Metadata { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)] public sealed class DeprecatedAttribute : Attribute { public DeprecatedAttribute(string message, DeprecationType type, uint version) { } public DeprecatedAttribute(string message, DeprecationType type, uint version, Type contract) { } } public enum DeprecationType { Deprecate = 0, Remove = 1 } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); ResultProperties resultProperties; string error; context.CompileExpression("c.P", out resultProperties, out error); Assert.Null(error); }); } [WorkItem(1089591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089591")] [Fact] public void BadPdb_MissingMethod() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = new MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes>.Empty); var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); evalContext.CompileExpression("1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [WorkItem(1108133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108133")] [Fact] public void SymUnmanagedReaderNotImplemented() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var module = ModuleInstance.Create(peImage, NotImplementedSymUnmanagedReader.Instance); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); evalContext.CompileExpression("1", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [WorkItem(1115543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115543")] [Fact] public void MethodTypeParameterInLambda() { var source = @" using System; public class C<T> { public void M<U>() { Func<U, int> getInt = u => { return u.GetHashCode(); }; var result = getInt(default(U)); } } "; var comp = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.<>c__0.<M>b__0_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(U)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""U"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); }); } [WorkItem(1136085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1136085")] [Fact] public void TypeofOpenGenericType() { var source = @" using System; public class C { public void M() { } }"; var compilation = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(compilation, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var expectedIL = @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""System.Action<T>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"; var testData = new CompilationTestData(); context.CompileExpression("typeof(Action<>)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); testData = new CompilationTestData(); context.CompileExpression("typeof(Action<> )", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); context.CompileExpression("typeof(Action<Action<>>)", out error, testData); Assert.Equal("error CS7003: Unexpected use of an unbound generic name", error); context.CompileExpression("typeof(Action<Action< > > )", out error); Assert.Equal("error CS7003: Unexpected use of an unbound generic name", error); context.CompileExpression("typeof(Action<>a)", out error); Assert.Equal("error CS1026: ) expected", error); }); } [WorkItem(1068138, "DevDiv")] [Fact] public void GetSymAttributeByVersion() { var source1 = @" public class C { public static void M() { int x = 1; } }"; var source2 = @" public class C { public static void M() { int x = 1; string y = ""a""; } }"; var comp1 = CreateCompilation(source1, options: TestOptions.DebugDll); var comp2 = CreateCompilation(source2, options: TestOptions.DebugDll); using (MemoryStream peStream1Unused = new MemoryStream(), peStream2 = new MemoryStream(), pdbStream1 = new MemoryStream(), pdbStream2 = new MemoryStream()) { Assert.True(comp1.Emit(peStream1Unused, pdbStream1).Success); Assert.True(comp2.Emit(peStream2, pdbStream2).Success); pdbStream1.Position = 0; pdbStream2.Position = 0; peStream2.Position = 0; var symReader = SymReaderFactory.CreateReader(pdbStream1); symReader.UpdateSymbolStore(pdbStream2); var module = ModuleInstance.Create(peStream2.ToImmutable(), symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader2; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader2, out methodToken, out localSignatureToken); Assert.Same(symReader, symReader2); AssertEx.SetEqual(symReader.GetLocalNames(methodToken, methodVersion: 1), "x"); AssertEx.SetEqual(symReader.GetLocalNames(methodToken, methodVersion: 2), "x", "y"); var context1 = CreateMethodContext( new AppDomain(), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context1.CompileGetLocals( locals, argumentsOnly: false, typeName: out typeName, testData: null); AssertEx.SetEqual(locals.Select(l => l.LocalName), "x"); var context2 = CreateMethodContext( new AppDomain(), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 2, ilOffset: 0, localSignatureToken: localSignatureToken, kind: MakeAssemblyReferencesKind.AllAssemblies); locals.Clear(); context2.CompileGetLocals( locals, argumentsOnly: false, typeName: out typeName, testData: null); AssertEx.SetEqual(locals.Select(l => l.LocalName), "x", "y"); } } /// <summary> /// Ignore accessibility in lambda rewriter. /// </summary> [WorkItem(1618, "https://github.com/dotnet/roslyn/issues/1618")] [Fact] public void LambdaRewriterIgnoreAccessibility() { var source = @"using System.Linq; class C { static void M() { var q = new[] { new C() }.AsQueryable(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); string error; context.CompileExpression("q.Where(c => true)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 64 (0x40) .maxstack 6 .locals init (System.Linq.IQueryable<C> V_0, //q System.Linq.Expressions.ParameterExpression V_1) IL_0000: ldloc.0 IL_0001: ldtoken ""C"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""c"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.1 IL_0016: ldc.i4.1 IL_0017: box ""bool"" IL_001c: ldtoken ""bool"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002b: ldc.i4.1 IL_002c: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0031: dup IL_0032: ldc.i4.0 IL_0033: ldloc.1 IL_0034: stelem.ref IL_0035: call ""System.Linq.Expressions.Expression<System.Func<C, bool>> System.Linq.Expressions.Expression.Lambda<System.Func<C, bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_003a: call ""System.Linq.IQueryable<C> System.Linq.Queryable.Where<C>(System.Linq.IQueryable<C>, System.Linq.Expressions.Expression<System.Func<C, bool>>)"" IL_003f: ret }"); }); } /// <summary> /// Ignore accessibility in async rewriter. /// </summary> [Fact] public void AsyncRewriterIgnoreAccessibility() { var source = @"using System; using System.Threading.Tasks; class C { static void F<T>(Func<Task<T>> f) { } static void M() { } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); string error; context.CompileExpression("F(async () => new C())", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 37 (0x25) .maxstack 2 IL_0000: ldsfld ""System.Func<System.Threading.Tasks.Task<C>> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""System.Threading.Tasks.Task<C> <>x.<>c.<<>m0>b__0_0()"" IL_0014: newobj ""System.Func<System.Threading.Tasks.Task<C>>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<System.Threading.Tasks.Task<C>> <>x.<>c.<>9__0_0"" IL_001f: call ""void C.F<C>(System.Func<System.Threading.Tasks.Task<C>>)"" IL_0024: ret }"); }); } [Fact] public void CapturedLocalInLambda() { var source = @" using System; class C { void M(Func<int> f) { int x = 42; M(() => x); } }"; var comp = CreateCompilationWithMscorlib45(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("M(() => x)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 32 (0x20) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 <>x.<>c__DisplayClass0_0 V_1) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: ldloc.0 IL_0008: stfld ""C.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.CS$<>8__locals0"" IL_000d: ldarg.0 IL_000e: ldloc.1 IL_000f: ldftn ""int <>x.<>c__DisplayClass0_0.<<>m0>b__0()"" IL_0015: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001a: callvirt ""void C.M(System.Func<int>)"" IL_001f: ret }"); }); } [WorkItem(3309, "https://github.com/dotnet/roslyn/issues/3309")] [Fact] public void NullAnonymousTypeInstance() { var source = @"class C { static void Main() { } }"; var testData = Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "false ? new { P = 1 } : null"); var methodData = testData.GetMethodData("<>x.<>m0"); var returnType = (NamedTypeSymbol)((MethodSymbol)methodData.Method).ReturnType; Assert.True(returnType.IsAnonymousType); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } /// <summary> /// DkmClrInstructionAddress.ILOffset is set to uint.MaxValue /// if the instruction does not map to an IL offset. /// </summary> [WorkItem(1185315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185315")] [Fact] public void NoILOffset() { var source = @"class C { static void M(int x) { int y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var appDomain = new AppDomain(); var context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ExpressionCompilerTestHelpers.NoILOffset, localSignatureToken: localSignatureToken); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("x + y", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //y IL_0000: ldarg.0 IL_0001: ldloc.0 IL_0002: add IL_0003: ret }"); // Verify the context is re-used for ILOffset == 0. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); Assert.Same(GetMetadataContext(previous).EvaluationContext, context); // Verify the context is re-used for NoILOffset. previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ExpressionCompilerTestHelpers.NoILOffset, localSignatureToken: localSignatureToken); Assert.Same(GetMetadataContext(previous).EvaluationContext, context); }); } [WorkItem(4098, "https://github.com/dotnet/roslyn/issues/4098")] [Fact] public void SelectAnonymousType() { var source = @"using System.Collections.Generic; using System.Linq; class C { static void M(List<int> list) { var useLinq = list.Last(); } }"; var compilation0 = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("from x in list from y in list where x > 0 select new { x, y };", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 140 (0x8c) .maxstack 4 .locals init (int V_0, //useLinq <>x.<>c__DisplayClass0_0 V_1) //CS$<>8__locals0 IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: ldarg.0 IL_0008: stfld ""System.Collections.Generic.List<int> <>x.<>c__DisplayClass0_0.list"" IL_000d: ldloc.1 IL_000e: ldfld ""System.Collections.Generic.List<int> <>x.<>c__DisplayClass0_0.list"" IL_0013: ldloc.1 IL_0014: ldftn ""System.Collections.Generic.IEnumerable<int> <>x.<>c__DisplayClass0_0.<<>m0>b__0(int)"" IL_001a: newobj ""System.Func<int, System.Collections.Generic.IEnumerable<int>>..ctor(object, System.IntPtr)"" IL_001f: ldsfld ""System.Func<int, int, <anonymous type: int x, int y>> <>x.<>c.<>9__0_1"" IL_0024: dup IL_0025: brtrue.s IL_003e IL_0027: pop IL_0028: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_002d: ldftn ""<anonymous type: int x, int y> <>x.<>c.<<>m0>b__0_1(int, int)"" IL_0033: newobj ""System.Func<int, int, <anonymous type: int x, int y>>..ctor(object, System.IntPtr)"" IL_0038: dup IL_0039: stsfld ""System.Func<int, int, <anonymous type: int x, int y>> <>x.<>c.<>9__0_1"" IL_003e: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.SelectMany<int, int, <anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<int>, System.Func<int, System.Collections.Generic.IEnumerable<int>>, System.Func<int, int, <anonymous type: int x, int y>>)"" IL_0043: ldsfld ""System.Func<<anonymous type: int x, int y>, bool> <>x.<>c.<>9__0_2"" IL_0048: dup IL_0049: brtrue.s IL_0062 IL_004b: pop IL_004c: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0051: ldftn ""bool <>x.<>c.<<>m0>b__0_2(<anonymous type: int x, int y>)"" IL_0057: newobj ""System.Func<<anonymous type: int x, int y>, bool>..ctor(object, System.IntPtr)"" IL_005c: dup IL_005d: stsfld ""System.Func<<anonymous type: int x, int y>, bool> <>x.<>c.<>9__0_2"" IL_0062: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.Where<<anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>>, System.Func<<anonymous type: int x, int y>, bool>)"" IL_0067: ldsfld ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>> <>x.<>c.<>9__0_3"" IL_006c: dup IL_006d: brtrue.s IL_0086 IL_006f: pop IL_0070: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0075: ldftn ""<anonymous type: int x, int y> <>x.<>c.<<>m0>b__0_3(<anonymous type: int x, int y>)"" IL_007b: newobj ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>>..ctor(object, System.IntPtr)"" IL_0080: dup IL_0081: stsfld ""System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>> <>x.<>c.<>9__0_3"" IL_0086: call ""System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>> System.Linq.Enumerable.Select<<anonymous type: int x, int y>, <anonymous type: int x, int y>>(System.Collections.Generic.IEnumerable<<anonymous type: int x, int y>>, System.Func<<anonymous type: int x, int y>, <anonymous type: int x, int y>>)"" IL_008b: ret }"); }); } [WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")] [Fact] public void ImportsInAsyncLambda() { var source = @"namespace N { using System.Linq; class C { static void M() { System.Action f = async () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; } } }"; var compilation0 = CreateCompilationWithMscorlib45( source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "N.C.<>c.<<M>b__0_0>d.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("c.Where(n => n > 0)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 43 (0x2b) .maxstack 3 .locals init (int V_0, System.Exception V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int[] N.C.<>c.<<M>b__0_0>d.<c>5__1"" IL_0006: ldsfld ""System.Func<int, bool> <>x.<>c.<>9__0_0"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_0014: ldftn ""bool <>x.<>c.<<>m0>b__0_0(int)"" IL_001a: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<int, bool> <>x.<>c.<>9__0_0"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_002a: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void AssignDefaultToLocal() { var source = @" class C { void Test() { int a = 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.Test"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileAssignment("a", "default", NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); Assert.Empty(missingAssemblyIdentities); Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 3 (0x3) .maxstack 1 .locals init (int V_0) //a IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ret }"); testData = new CompilationTestData(); context.CompileExpression("a = default;", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 4 (0x4) .maxstack 2 .locals init (int V_0) //a IL_0000: ldc.i4.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ret }"); testData = new CompilationTestData(); context.CompileExpression("int b = default;", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, //a System.Guid V_1) IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""b"" IL_000f: ldloca.s V_1 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.1 IL_0018: ldnull IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_001e: ldstr ""b"" IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_0028: ldc.i4.0 IL_0029: stind.i4 IL_002a: ret }"); testData = new CompilationTestData(); context.CompileExpression("default", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Equal("error CS8716: There is no target type for the default literal.", error); testData = new CompilationTestData(); context.CompileExpression("null", DkmEvaluationFlags.None, ImmutableArray<Alias>.Empty, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (int V_0) //a IL_0000: ldnull IL_0001: ret }"); }); } [Fact] public void InLambdasEvaluationWillSynthesizeRequiredAttributes_Parameters() { var reference = CreateCompilation(@" public delegate void D(in int p);"); CompileAndVerify(reference, symbolValidator: module => { Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var comp = CreateCompilation(@" public class Test { void M(D lambda) { } }", references: new[] { reference.EmitToImageReference() }); CompileAndVerify(comp, symbolValidator: module => { Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var testData = Evaluate( comp, methodName: "Test.M", expr: "M((in int p) => {})"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.IsReadOnlyAttribute.FullName + "..ctor()", methodsGenerated); } [Fact] public void RefReadOnlyLambdasEvaluationWillSynthesizeRequiredAttributes_ReturnTypes() { var reference = CreateCompilation(@" public delegate ref readonly int D();"); CompileAndVerify(reference, symbolValidator: module => { Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.NotNull(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var comp = CreateCompilation(@" public class Test { private int x = 0; void M(D lambda) { } }", references: new[] { reference.EmitToImageReference() }); CompileAndVerify(comp, symbolValidator: module => { Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.IsReadOnlyAttribute.FullName)); }); var testData = Evaluate( comp, methodName: "Test.M", expr: "M(() => ref x)"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.IsReadOnlyAttribute.FullName + "..ctor()", methodsGenerated); } // https://github.com/dotnet/roslyn/issues/30033: EnsureNullableAttributeExists is not called. [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30033")] [WorkItem(30033, "https://github.com/dotnet/roslyn/issues/30033")] public void EmitNullableAttribute_ExpressionType() { var source = @"class C { static void Main() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("new object?[0]", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr ""object"" IL_0006: ret }"); // Verify NullableAttribute is emitted. using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef(result.TypeName); var methodHandle = reader.GetMethodDefHandle(typeDef, result.MethodName); var attributeHandle = reader.GetCustomAttributes(methodHandle).Single(); var attribute = reader.GetCustomAttribute(attributeHandle); var attributeConstructor = reader.GetMethodDefinition((System.Reflection.Metadata.MethodDefinitionHandle)attribute.Constructor); var attributeTypeName = reader.GetString(reader.GetName(attributeConstructor.GetDeclaringType())); Assert.Equal("NullableAttribute", attributeTypeName); } }); } // https://github.com/dotnet/roslyn/issues/30034: Expression below currently reports // "CS0453: The type 'object' must be a non-nullable value type ... 'Nullable<T>'" // because CSharpCompilationExtensions.IsFeatureEnabled() fails when there // the Compilation contains no syntax trees. [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30034")] [WorkItem(30034, "https://github.com/dotnet/roslyn/issues/30034")] public void EmitNullableAttribute_LambdaParameters() { var source = @"delegate T D<T>(T t); class C { static T F<T>(D<T> d, T t) => d(t); static void G() { } }"; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.G"); string error; var testData = new CompilationTestData(); context.CompileExpression("F((object? o) => o, null)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 38 (0x26) .maxstack 2 IL_0000: ldsfld ""D<object?> <>x.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""<>x.<>c <>x.<>c.<>9"" IL_000e: ldftn ""object? <>x.<>c.<<>m0>b__0_0(object?)"" IL_0014: newobj ""D<object?>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D<object?> <>x.<>c.<>9__0_0"" IL_001f: ldnull IL_0020: call ""object? C.F<object?>(D<object?>, object?)"" IL_0025: ret }"); var methodsGenerated = testData.GetMethodsByName().Keys; Assert.Contains(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName + "..ctor()", methodsGenerated); Assert.Contains(AttributeDescription.NullableAttribute.FullName + "..ctor()", methodsGenerated); }); } [Fact] [WorkItem(22206, "https://github.com/dotnet/roslyn/issues/22206")] public void RefReturnNonRefLocal() { var source = @" delegate ref int D(); class C { static void Main() { int local = 0; } static ref int M(D d) { return ref d(); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Main"); context.CompileExpression("M(() => ref local)", out var error); Assert.Equal("error CS8168: Cannot return local 'local' by reference because it is not a ref local", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void OutVarInExpression() { var source = @"class C { static void Main() { } static object Test(out int x) { x = 1; return x; } }"; var testData = Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "Test(out var z)"); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 46 (0x2e) .maxstack 4 .locals init (System.Guid V_0) IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""z"" IL_000f: ldloca.s V_0 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.0 IL_0018: ldnull IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_001e: ldstr ""z"" IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_0028: call ""object C.Test(out int)"" IL_002d: ret }"); } [Fact] public void IndexExpression() { var source = TestSources.Index + @" class C { static void Main() { var x = ^1; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Index V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 1 .locals init (System.Index V_0) //x IL_0000: ldloca.s V_0 IL_0002: call ""int System.Index.Value.get"" IL_0007: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "^2").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 8 (0x8) .maxstack 2 .locals init (System.Index V_0) //x IL_0000: ldc.i4.2 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: ret }"); } [Fact] public void RangeExpression_None() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = ..; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "..").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: call ""System.Range System.Range.All.get"" IL_0005: ret }"); } [Fact] public void RangeExpression_Left() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = 1..; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "2..").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldc.i4.2 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: call ""System.Range System.Range.StartAt(System.Index)"" IL_000b: ret }"); } [Fact] public void RangeExpression_Right() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = ..1; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "..2").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldc.i4.2 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: call ""System.Range System.Range.EndAt(System.Index)"" IL_000b: ret }"); } [Fact] public void RangeExpression_Both() { var source = TestSources.Index + TestSources.Range + @" class C { static void Main() { var x = 1..2; } }"; Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Range V_0) //x IL_0000: ldloc.0 IL_0001: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "x.Start.Value").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (System.Range V_0, //x System.Index V_1) IL_0000: ldloca.s V_0 IL_0002: call ""System.Index System.Range.Start.get"" IL_0007: stloc.1 IL_0008: ldloca.s V_1 IL_000a: call ""int System.Index.Value.get"" IL_000f: ret }"); Evaluate(source, OutputKind.ConsoleApplication, "C.Main", "3..4").GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.Range V_0) //x IL_0000: ldc.i4.3 IL_0001: call ""System.Index System.Index.op_Implicit(int)"" IL_0006: ldc.i4.4 IL_0007: call ""System.Index System.Index.op_Implicit(int)"" IL_000c: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0011: ret }"); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/MscorlibNamespacesAndTypes.bsl
<Global> <type name="&lt;Module&gt;" /> <type name="&lt;PrivateImplementationDetails&gt;{E929D9EA-3268-462F-B826-5115530AD12B}"> <type name="__StaticArrayInitTypeSize=10" /> <type name="__StaticArrayInitTypeSize=120" /> <type name="__StaticArrayInitTypeSize=1208" /> <type name="__StaticArrayInitTypeSize=126" /> <type name="__StaticArrayInitTypeSize=128" /> <type name="__StaticArrayInitTypeSize=130" /> <type name="__StaticArrayInitTypeSize=132" /> <type name="__StaticArrayInitTypeSize=14" /> <type name="__StaticArrayInitTypeSize=1440" /> <type name="__StaticArrayInitTypeSize=16" /> <type name="__StaticArrayInitTypeSize=18128" /> <type name="__StaticArrayInitTypeSize=2224" /> <type name="__StaticArrayInitTypeSize=24" /> <type name="__StaticArrayInitTypeSize=256" /> <type name="__StaticArrayInitTypeSize=28" /> <type name="__StaticArrayInitTypeSize=288" /> <type name="__StaticArrayInitTypeSize=3" /> <type name="__StaticArrayInitTypeSize=3200" /> <type name="__StaticArrayInitTypeSize=3456" /> <type name="__StaticArrayInitTypeSize=38" /> <type name="__StaticArrayInitTypeSize=392" /> <type name="__StaticArrayInitTypeSize=40" /> <type name="__StaticArrayInitTypeSize=4096" /> <type name="__StaticArrayInitTypeSize=440" /> <type name="__StaticArrayInitTypeSize=4540" /> <type name="__StaticArrayInitTypeSize=48" /> <type name="__StaticArrayInitTypeSize=52" /> <type name="__StaticArrayInitTypeSize=5264" /> <type name="__StaticArrayInitTypeSize=6" /> <type name="__StaticArrayInitTypeSize=64" /> <type name="__StaticArrayInitTypeSize=640" /> <type name="__StaticArrayInitTypeSize=72" /> <type name="__StaticArrayInitTypeSize=82" /> <type name="__StaticArrayInitTypeSize=84" /> <type name="__StaticArrayInitTypeSize=878" /> </type> <type name="AssemblyRef" /> <type name="FXAssembly" /> <type name="SRETW" /> <type name="ThisAssembly" /> <Microsoft> <Runtime> <Hosting> <type name="IClrStrongName" /> <type name="IClrStrongNameUsingIntPtr" /> <type name="StrongNameHelpers" /> </Hosting> </Runtime> <Win32> <type name="ASM_CACHE" /> <type name="ASM_NAME" /> <type name="CANOF" /> <type name="Fusion" /> <type name="IApplicationContext" /> <type name="IAssemblyEnum" /> <type name="IAssemblyName" /> <type name="OAVariantLib" /> <type name="Registry" /> <type name="RegistryHive" /> <type name="RegistryKey" /> <type name="RegistryKeyPermissionCheck" /> <type name="RegistryOptions" /> <type name="RegistryValueKind" /> <type name="RegistryValueOptions" /> <type name="RegistryView" /> <type name="SafeLibraryHandle" /> <type name="UnsafeNativeMethods"> <type name="EtwEnableCallback" /> <type name="EVENT_FILTER_DESCRIPTOR" /> </type> <type name="Win32Native"> <type name="CHAR_INFO" /> <type name="Color" /> <type name="ConsoleCtrlHandlerRoutine" /> <type name="CONSOLE_CURSOR_INFO" /> <type name="CONSOLE_SCREEN_BUFFER_INFO" /> <type name="COORD" /> <type name="DynamicTimeZoneInformation" /> <type name="FILE_TIME" /> <type name="InputRecord" /> <type name="KERB_S4U_LOGON" /> <type name="KeyEventRecord" /> <type name="LSA_OBJECT_ATTRIBUTES" /> <type name="LSA_REFERENCED_DOMAIN_LIST" /> <type name="LSA_TRANSLATED_NAME" /> <type name="LSA_TRANSLATED_SID" /> <type name="LSA_TRANSLATED_SID2" /> <type name="LSA_TRUST_INFORMATION" /> <type name="LUID" /> <type name="LUID_AND_ATTRIBUTES" /> <type name="MEMORYSTATUSEX" /> <type name="MEMORY_BASIC_INFORMATION" /> <type name="OSVERSIONINFO" /> <type name="OSVERSIONINFOEX" /> <type name="QUOTA_LIMITS" /> <type name="RegistryTimeZoneInformation" /> <type name="SECURITY_ATTRIBUTES" /> <type name="SECURITY_IMPERSONATION_LEVEL" /> <type name="SECURITY_LOGON_SESSION_DATA" /> <type name="SID_AND_ATTRIBUTES" /> <type name="SMALL_RECT" /> <type name="SystemTime" /> <type name="SYSTEM_INFO" /> <type name="TimeZoneInformation" /> <type name="TOKEN_GROUPS" /> <type name="TOKEN_PRIVILEGE" /> <type name="TOKEN_SOURCE" /> <type name="TOKEN_STATISTICS" /> <type name="TOKEN_USER" /> <type name="UNICODE_INTPTR_STRING" /> <type name="UNICODE_STRING" /> <type name="USEROBJECTFLAGS" /> <type name="WIN32_FILE_ATTRIBUTE_DATA" /> <type name="WIN32_FIND_DATA" /> </type> <SafeHandles> <type name="CriticalHandleMinusOneIsInvalid" /> <type name="CriticalHandleZeroOrMinusOneIsInvalid" /> <type name="SafeFileHandle" /> <type name="SafeFileMappingHandle" /> <type name="SafeFindHandle" /> <type name="SafeHandleMinusOneIsInvalid" /> <type name="SafeHandleZeroOrMinusOneIsInvalid" /> <type name="SafeLocalAllocHandle" /> <type name="SafeLsaLogonProcessHandle" /> <type name="SafeLsaMemoryHandle" /> <type name="SafeLsaPolicyHandle" /> <type name="SafeLsaReturnBufferHandle" /> <type name="SafePEFileHandle" /> <type name="SafeProcessHandle" /> <type name="SafeRegistryHandle" /> <type name="SafeThreadHandle" /> <type name="SafeTokenHandle" /> <type name="SafeViewOfFileHandle" /> <type name="SafeWaitHandle" /> </SafeHandles> </Win32> </Microsoft> <System> <type name="AccessViolationException" /> <type name="Action" /> <type name="Action" arity="1" /> <type name="Action" arity="2" /> <type name="Action" arity="3" /> <type name="Action" arity="4" /> <type name="Action" arity="5" /> <type name="Action" arity="6" /> <type name="Action" arity="7" /> <type name="Action" arity="8" /> <type name="ActivationContext"> <type name="ApplicationState" /> <type name="ApplicationStateDisposition" /> <type name="ContextForm" /> </type> <type name="Activator" /> <type name="AggregateException" /> <type name="AppDomain" /> <type name="AppDomainHandle" /> <type name="AppDomainInitializer" /> <type name="AppDomainInitializerInfo"> <type name="ItemInfo" /> </type> <type name="AppDomainManager" /> <type name="AppDomainManagerInitializationOptions" /> <type name="AppDomainSetup"> <type name="LoaderInformation" /> </type> <type name="AppDomainUnloadedException" /> <type name="ApplicationException" /> <type name="ApplicationId" /> <type name="ApplicationIdentity" /> <type name="ArgIterator" /> <type name="ArgumentException" /> <type name="ArgumentNullException" /> <type name="ArgumentOutOfRangeException" /> <type name="ArithmeticException" /> <type name="Array"> <type name="FunctorComparer" arity="1" /> </type> <type name="ArraySegment" arity="1" /> <type name="ArrayTypeMismatchException" /> <type name="AssemblyLoadEventArgs" /> <type name="AssemblyLoadEventHandler" /> <type name="AsyncCallback" /> <type name="Attribute" /> <type name="AttributeTargets" /> <type name="AttributeUsageAttribute" /> <type name="BadImageFormatException" /> <type name="Base64FormattingOptions" /> <type name="BaseConfigHandler" /> <type name="BCLDebug" /> <type name="BitConverter" /> <type name="Boolean" /> <type name="Buffer" /> <type name="Byte" /> <type name="CannotUnloadAppDomainException" /> <type name="Char" /> <type name="CharEnumerator" /> <type name="CLSCompliantAttribute" /> <type name="Comparison" arity="1" /> <type name="CompatibilityFlag" /> <type name="ConfigEvents" /> <type name="ConfigNode" /> <type name="ConfigNodeSubType" /> <type name="ConfigNodeType" /> <type name="ConfigServer" /> <type name="ConfigTreeParser" /> <type name="Console"> <type name="ControlCHooker" /> <type name="ControlKeyState" /> </type> <type name="ConsoleCancelEventArgs" /> <type name="ConsoleCancelEventHandler" /> <type name="ConsoleColor" /> <type name="ConsoleKey" /> <type name="ConsoleKeyInfo" /> <type name="ConsoleModifiers" /> <type name="ConsoleSpecialKey" /> <type name="ContextBoundObject" /> <type name="ContextMarshalException" /> <type name="ContextStaticAttribute" /> <type name="Convert" /> <type name="Converter" arity="2" /> <type name="CrossAppDomainDelegate" /> <type name="CtorDelegate" /> <type name="CultureAwareComparer" /> <type name="Currency" /> <type name="CurrentSystemTimeZone" /> <type name="DataMisalignedException" /> <type name="DateTime" /> <type name="DateTimeFormat" /> <type name="DateTimeKind" /> <type name="DateTimeOffset" /> <type name="DateTimeParse"> <type name="DS" /> <type name="DTT" /> <type name="MatchNumberDelegate" /> <type name="TM" /> </type> <type name="DateTimeRawInfo" /> <type name="DateTimeResult" /> <type name="DateTimeToken" /> <type name="DayOfWeek" /> <type name="DBNull" /> <type name="Decimal" /> <type name="DefaultBinder"> <type name="BinderState" /> </type> <type name="Delegate" /> <type name="DelegateBindingFlags" /> <type name="DelegateSerializationHolder"> <type name="DelegateEntry" /> </type> <type name="DivideByZeroException" /> <type name="DllNotFoundException" /> <type name="Double" /> <type name="DTSubString" /> <type name="DTSubStringType" /> <type name="DuplicateWaitObjectException" /> <type name="Empty" /> <type name="EntryPointNotFoundException" /> <type name="Enum" /> <type name="Environment"> <type name="OSName" /> <type name="ResourceHelper"> <type name="GetResourceStringUserData" /> </type> <type name="SpecialFolder" /> <type name="SpecialFolderOption" /> </type> <type name="EnvironmentVariableTarget" /> <type name="EventArgs" /> <type name="EventHandler" /> <type name="EventHandler" arity="1" /> <type name="Exception"> <type name="ExceptionMessageKind" /> </type> <type name="ExceptionArgument" /> <type name="ExceptionResource" /> <type name="ExecutionEngineException" /> <type name="FieldAccessException" /> <type name="FlagsAttribute" /> <type name="FormatException" /> <type name="Func" arity="1" /> <type name="Func" arity="2" /> <type name="Func" arity="3" /> <type name="Func" arity="4" /> <type name="Func" arity="5" /> <type name="Func" arity="6" /> <type name="Func" arity="7" /> <type name="Func" arity="8" /> <type name="Func" arity="9" /> <type name="GC" /> <type name="GCCollectionMode" /> <type name="GCNotificationStatus" /> <type name="Guid" /> <type name="IAppDomainSetup" /> <type name="IAsyncResult" /> <type name="ICloneable" /> <type name="IComparable" /> <type name="IComparable" arity="1" /> <type name="IConfigHandler" /> <type name="IConvertible" /> <type name="IConvertibleContract" /> <type name="ICustomFormatter" /> <type name="IDisposable" /> <type name="IEquatable" arity="1" /> <type name="IFormatProvider" /> <type name="IFormattable" /> <type name="IFormattableContract" /> <type name="IndexOutOfRangeException" /> <type name="InsufficientExecutionStackException" /> <type name="InsufficientMemoryException" /> <type name="Int16" /> <type name="Int32" /> <type name="Int64" /> <type name="Internal" /> <type name="IntPtr" /> <type name="InvalidCastException" /> <type name="InvalidOperationException" /> <type name="InvalidProgramException" /> <type name="InvalidTimeZoneException" /> <type name="IObservable" arity="1" /> <type name="IObserver" arity="1" /> <type name="IRuntimeFieldInfo" /> <type name="IRuntimeMethodInfo" /> <type name="IServiceProvider" /> <type name="ITuple" /> <type name="Lazy" arity="1" /> <type name="LoaderOptimization" /> <type name="LoaderOptimizationAttribute" /> <type name="LocalDataStore" /> <type name="LocalDataStoreElement" /> <type name="LocalDataStoreHolder" /> <type name="LocalDataStoreMgr" /> <type name="LocalDataStoreSlot" /> <type name="LogLevel" /> <type name="MarshalByRefObject" /> <type name="Math" /> <type name="Mda"> <type name="StreamWriterBufferedDataLost" /> </type> <type name="MemberAccessException" /> <type name="MethodAccessException" /> <type name="MidpointRounding" /> <type name="MissingFieldException" /> <type name="MissingMemberException" /> <type name="MissingMethodException" /> <type name="ModuleHandle" /> <type name="MTAThreadAttribute" /> <type name="MulticastDelegate" /> <type name="MulticastNotSupportedException" /> <type name="NonSerializedAttribute" /> <type name="NotFiniteNumberException" /> <type name="NotImplementedException" /> <type name="NotSupportedException" /> <type name="Nullable" /> <type name="Nullable" arity="1" /> <type name="NullReferenceException" /> <type name="Number"> <type name="NumberBuffer" /> </type> <type name="Object" /> <type name="ObjectDisposedException" /> <type name="ObsoleteAttribute" /> <type name="OleAutBinder" /> <type name="OperatingSystem" /> <type name="OperationCanceledException" /> <type name="OrdinalComparer" /> <type name="OutOfMemoryException" /> <type name="OverflowException" /> <type name="ParamArrayAttribute" /> <type name="ParseFailureKind" /> <type name="ParseFlags" /> <type name="ParseNumbers" /> <type name="ParsingInfo" /> <type name="PlatformID" /> <type name="PlatformNotSupportedException" /> <type name="Predicate" arity="1" /> <type name="Random" /> <type name="RankException" /> <type name="ReflectionOnlyType" /> <type name="ResId" /> <type name="ResolveEventArgs" /> <type name="ResolveEventHandler" /> <type name="Resolver"> <type name="CORINFO_EH_CLAUSE" /> </type> <type name="RuntimeArgumentHandle" /> <type name="RuntimeFieldHandle" /> <type name="RuntimeFieldHandleInternal" /> <type name="RuntimeFieldInfoStub" /> <type name="RuntimeMethodHandle" /> <type name="RuntimeMethodHandleInternal" /> <type name="RuntimeMethodInfoStub" /> <type name="RuntimeType"> <type name="RuntimeTypeCache"> <type name="CacheType" /> <type name="WhatsCached" /> </type> </type> <type name="RuntimeTypeHandle"> <type name="IntroducedMethodEnumerator" /> </type> <type name="SafeTypeNameParserHandle" /> <type name="SByte" /> <type name="SerializableAttribute" /> <type name="SharedStatics" /> <type name="Signature"> <type name="MdSigCallingConvention" /> </type> <type name="SignatureStruct" /> <type name="Single" /> <type name="SizedReference" /> <type name="StackOverflowException" /> <type name="STAThreadAttribute" /> <type name="String" /> <type name="StringComparer" /> <type name="StringComparison" /> <type name="StringSplitOptions" /> <type name="SwitchStructure" /> <type name="SystemException" /> <type name="System_LazyDebugView" arity="1" /> <type name="SZArrayHelper" /> <type name="ThreadStaticAttribute" /> <type name="ThrowHelper" /> <type name="TimeoutException" /> <type name="TimeSpan" /> <type name="TimeZone" /> <type name="TimeZoneInfo"> <type name="AdjustmentRule" /> <type name="TransitionTime" /> </type> <type name="TimeZoneInfoOptions" /> <type name="TimeZoneNotFoundException" /> <type name="TokenType" /> <type name="Tuple" /> <type name="Tuple" arity="1" /> <type name="Tuple" arity="2" /> <type name="Tuple" arity="3" /> <type name="Tuple" arity="4" /> <type name="Tuple" arity="5" /> <type name="Tuple" arity="6" /> <type name="Tuple" arity="7" /> <type name="Tuple" arity="8" /> <type name="Type" /> <type name="TypeAccessException" /> <type name="TypeCode" /> <type name="TypeContracts" /> <type name="TypedReference" /> <type name="TypeInitializationException" /> <type name="TypeLoadException" /> <type name="TypeNameParser" /> <type name="TypeUnloadedException" /> <type name="UInt16" /> <type name="UInt32" /> <type name="UInt64" /> <type name="UIntPtr" /> <type name="UnauthorizedAccessException" /> <type name="UnhandledExceptionEventArgs" /> <type name="UnhandledExceptionEventHandler" /> <type name="UnitySerializationHolder" /> <type name="UnSafeCharBuffer" /> <type name="Utf8String" /> <type name="ValueType" /> <type name="Variant" /> <type name="Version"> <type name="ParseFailureKind" /> <type name="VersionResult" /> </type> <type name="Void" /> <type name="WeakReference" /> <type name="XmlIgnoreMemberAttribute" /> <type name="_AppDomain" /> <type name="__Canon" /> <type name="__ComObject" /> <type name="__DTString" /> <type name="__Filters" /> <type name="__HResults" /> <Collections> <type name="ArrayList"> <type name="ArrayListDebugView" /> </type> <type name="BitArray" /> <type name="CaseInsensitiveComparer" /> <type name="CaseInsensitiveHashCodeProvider" /> <type name="CollectionBase" /> <type name="Comparer" /> <type name="CompatibleComparer" /> <type name="DictionaryBase" /> <type name="DictionaryEntry" /> <type name="EmptyReadOnlyDictionaryInternal" /> <type name="HashHelpers" /> <type name="Hashtable"> <type name="HashtableDebugView" /> </type> <type name="ICollection" /> <type name="ICollectionContract" /> <type name="IComparer" /> <type name="IDictionary" /> <type name="IDictionaryContract" /> <type name="IDictionaryEnumerator" /> <type name="IEnumerable" /> <type name="IEnumerableContract" /> <type name="IEnumerator" /> <type name="IEqualityComparer" /> <type name="IHashCodeProvider" /> <type name="IList" /> <type name="IListContract" /> <type name="IStructuralComparable" /> <type name="IStructuralEquatable" /> <type name="KeyValuePairs" /> <type name="ListDictionaryInternal" /> <type name="Queue"> <type name="QueueDebugView" /> </type> <type name="ReadOnlyCollectionBase" /> <type name="SortedList"> <type name="SortedListDebugView" /> </type> <type name="Stack"> <type name="StackDebugView" /> </type> <type name="StructuralComparer" /> <type name="StructuralComparisons" /> <type name="StructuralEqualityComparer" /> <Concurrent> <type name="CDSCollectionETWBCLProvider" /> <type name="ConcurrentDictionary" arity="2" /> <type name="ConcurrentQueue" arity="1" /> <type name="ConcurrentStack" arity="1" /> <type name="IProducerConsumerCollection" arity="1" /> <type name="OrderablePartitioner" arity="1" /> <type name="Partitioner" /> <type name="Partitioner" arity="1" /> <type name="SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView" arity="1" /> </Concurrent> <Generic> <type name="ArraySortHelper" arity="1" /> <type name="ArraySortHelper" arity="2" /> <type name="ByteEqualityComparer" /> <type name="Comparer" arity="1" /> <type name="Dictionary" arity="2"> <type name="Enumerator" /> <type name="KeyCollection"> <type name="Enumerator" /> </type> <type name="ValueCollection"> <type name="Enumerator" /> </type> </type> <type name="EnumEqualityComparer" arity="1" /> <type name="EqualityComparer" arity="1" /> <type name="GenericArraySortHelper" arity="1" /> <type name="GenericArraySortHelper" arity="2" /> <type name="GenericComparer" arity="1" /> <type name="GenericEqualityComparer" arity="1" /> <type name="IArraySortHelper" arity="1" /> <type name="IArraySortHelper" arity="2" /> <type name="IArraySortHelperContract" arity="1" /> <type name="ICollection" arity="1" /> <type name="ICollectionContract" arity="1" /> <type name="IComparer" arity="1" /> <type name="IDictionary" arity="2" /> <type name="IDictionaryContract" arity="2" /> <type name="IEnumerable" arity="1" /> <type name="IEnumerableContract" arity="1" /> <type name="IEnumerator" arity="1" /> <type name="IEqualityComparer" arity="1" /> <type name="IList" arity="1" /> <type name="IListContract" arity="1" /> <type name="KeyNotFoundException" /> <type name="KeyValuePair" arity="2" /> <type name="List" arity="1"> <type name="Enumerator" /> <type name="SynchronizedList" /> </type> <type name="Mscorlib_CollectionDebugView" arity="1" /> <type name="Mscorlib_DictionaryDebugView" arity="2" /> <type name="Mscorlib_DictionaryKeyCollectionDebugView" arity="2" /> <type name="Mscorlib_DictionaryValueCollectionDebugView" arity="2" /> <type name="Mscorlib_KeyedCollectionDebugView" arity="2" /> <type name="NullableComparer" arity="1" /> <type name="NullableEqualityComparer" arity="1" /> <type name="ObjectComparer" arity="1" /> <type name="ObjectEqualityComparer" arity="1" /> </Generic> <ObjectModel> <type name="Collection" arity="1" /> <type name="KeyedCollection" arity="2" /> <type name="ReadOnlyCollection" arity="1" /> </ObjectModel> </Collections> <Configuration> <Assemblies> <type name="AssemblyHash" /> <type name="AssemblyHashAlgorithm" /> <type name="AssemblyVersionCompatibility" /> </Assemblies> </Configuration> <Deployment> <Internal> <type name="InternalActivationContextHelper" /> <type name="InternalApplicationIdentityHelper" /> <Isolation> <type name="BLOB" /> <type name="CATEGORY" /> <type name="CATEGORY_INSTANCE" /> <type name="CATEGORY_SUBCATEGORY" /> <type name="IActContext" /> <type name="IAppIdAuthority" /> <type name="IAPPIDAUTHORITY_ARE_DEFINITIONS_EQUAL_FLAGS" /> <type name="IAPPIDAUTHORITY_ARE_REFERENCES_EQUAL_FLAGS" /> <type name="ICDF" /> <type name="IDefinitionAppId" /> <type name="IDefinitionIdentity" /> <type name="IDENTITY_ATTRIBUTE" /> <type name="IEnumDefinitionIdentity" /> <type name="IEnumIDENTITY_ATTRIBUTE" /> <type name="IEnumReferenceIdentity" /> <type name="IEnumSTORE_ASSEMBLY" /> <type name="IEnumSTORE_ASSEMBLY_FILE" /> <type name="IEnumSTORE_ASSEMBLY_INSTALLATION_REFERENCE" /> <type name="IEnumSTORE_CATEGORY" /> <type name="IEnumSTORE_CATEGORY_INSTANCE" /> <type name="IEnumSTORE_CATEGORY_SUBCATEGORY" /> <type name="IEnumSTORE_DEPLOYMENT_METADATA" /> <type name="IEnumSTORE_DEPLOYMENT_METADATA_PROPERTY" /> <type name="IEnumUnknown" /> <type name="IIdentityAuthority" /> <type name="IIDENTITYAUTHORITY_DEFINITION_IDENTITY_TO_TEXT_FLAGS" /> <type name="IIDENTITYAUTHORITY_DOES_DEFINITION_MATCH_REFERENCE_FLAGS" /> <type name="IIDENTITYAUTHORITY_REFERENCE_IDENTITY_TO_TEXT_FLAGS" /> <type name="IManifestInformation" /> <type name="IManifestParseErrorCallback" /> <type name="IReferenceAppId" /> <type name="IReferenceIdentity" /> <type name="ISection" /> <type name="ISectionEntry" /> <type name="ISectionWithReferenceIdentityKey" /> <type name="ISectionWithStringKey" /> <type name="IsolationInterop"> <type name="CreateActContextParameters"> <type name="CreateFlags" /> </type> <type name="CreateActContextParametersSource"> <type name="SourceFlags" /> </type> <type name="CreateActContextParametersSourceDefinitionAppid" /> </type> <type name="IStateManager" /> <type name="IStore" /> <type name="IStore_BindingResult" /> <type name="IStore_BindingResult_BoundVersion" /> <type name="ISTORE_BIND_REFERENCE_TO_ASSEMBLY_FLAGS" /> <type name="ISTORE_ENUM_ASSEMBLIES_FLAGS" /> <type name="ISTORE_ENUM_FILES_FLAGS" /> <type name="StateManager_RunningState" /> <type name="Store"> <type name="EnumApplicationPrivateFiles" /> <type name="EnumAssembliesFlags" /> <type name="EnumAssemblyFilesFlags" /> <type name="EnumAssemblyInstallReferenceFlags" /> <type name="EnumCategoriesFlags" /> <type name="EnumCategoryInstancesFlags" /> <type name="EnumSubcategoriesFlags" /> <type name="GetPackagePropertyFlags" /> <type name="IPathLock" /> </type> <type name="StoreApplicationReference"> <type name="RefFlags" /> </type> <type name="StoreAssemblyEnumeration" /> <type name="StoreAssemblyFileEnumeration" /> <type name="StoreCategoryEnumeration" /> <type name="StoreCategoryInstanceEnumeration" /> <type name="StoreDeploymentMetadataEnumeration" /> <type name="StoreDeploymentMetadataPropertyEnumeration" /> <type name="StoreOperationInstallDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationMetadataProperty" /> <type name="StoreOperationPinDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationScavenge"> <type name="OpFlags" /> </type> <type name="StoreOperationSetCanonicalizationContext"> <type name="OpFlags" /> </type> <type name="StoreOperationSetDeploymentMetadata"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationStageComponent"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationStageComponentFile"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationUninstallDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationUnpinDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreSubcategoryEnumeration" /> <type name="StoreTransaction" /> <type name="StoreTransactionData" /> <type name="StoreTransactionOperation" /> <type name="StoreTransactionOperationType" /> <type name="STORE_ASSEMBLY" /> <type name="STORE_ASSEMBLY_FILE" /> <type name="STORE_ASSEMBLY_FILE_STATUS_FLAGS" /> <type name="STORE_ASSEMBLY_STATUS_FLAGS" /> <type name="STORE_CATEGORY" /> <type name="STORE_CATEGORY_INSTANCE" /> <type name="STORE_CATEGORY_SUBCATEGORY" /> <Manifest> <type name="AssemblyReferenceDependentAssemblyEntry" /> <type name="AssemblyReferenceDependentAssemblyEntryFieldId" /> <type name="AssemblyReferenceEntry" /> <type name="AssemblyReferenceEntryFieldId" /> <type name="AssemblyRequestEntry" /> <type name="AssemblyRequestEntryFieldId" /> <type name="CategoryMembershipDataEntry" /> <type name="CategoryMembershipDataEntryFieldId" /> <type name="CategoryMembershipEntry" /> <type name="CategoryMembershipEntryFieldId" /> <type name="CLRSurrogateEntry" /> <type name="CLRSurrogateEntryFieldId" /> <type name="CMSSECTIONID" /> <type name="CmsUtils" /> <type name="CMS_ASSEMBLY_DEPLOYMENT_FLAG" /> <type name="CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG" /> <type name="CMS_ASSEMBLY_REFERENCE_FLAG" /> <type name="CMS_COM_SERVER_FLAG" /> <type name="CMS_ENTRY_POINT_FLAG" /> <type name="CMS_FILE_FLAG" /> <type name="CMS_FILE_HASH_ALGORITHM" /> <type name="CMS_FILE_WRITABLE_TYPE" /> <type name="CMS_HASH_DIGESTMETHOD" /> <type name="CMS_HASH_TRANSFORM" /> <type name="CMS_SCHEMA_VERSION" /> <type name="CMS_TIME_UNIT_TYPE" /> <type name="CMS_USAGE_PATTERN" /> <type name="CompatibleFrameworksMetadataEntry" /> <type name="CompatibleFrameworksMetadataEntryFieldId" /> <type name="COMServerEntry" /> <type name="COMServerEntryFieldId" /> <type name="DependentOSMetadataEntry" /> <type name="DependentOSMetadataEntryFieldId" /> <type name="DeploymentMetadataEntry" /> <type name="DeploymentMetadataEntryFieldId" /> <type name="DescriptionMetadataEntry" /> <type name="DescriptionMetadataEntryFieldId" /> <type name="EntryPointEntry" /> <type name="EntryPointEntryFieldId" /> <type name="FileAssociationEntry" /> <type name="FileAssociationEntryFieldId" /> <type name="FileEntry" /> <type name="FileEntryFieldId" /> <type name="HashElementEntry" /> <type name="HashElementEntryFieldId" /> <type name="IAssemblyReferenceDependentAssemblyEntry" /> <type name="IAssemblyReferenceEntry" /> <type name="IAssemblyRequestEntry" /> <type name="ICategoryMembershipDataEntry" /> <type name="ICategoryMembershipEntry" /> <type name="ICLRSurrogateEntry" /> <type name="ICMS" /> <type name="ICompatibleFrameworksMetadataEntry" /> <type name="ICOMServerEntry" /> <type name="IDependentOSMetadataEntry" /> <type name="IDeploymentMetadataEntry" /> <type name="IDescriptionMetadataEntry" /> <type name="IEntryPointEntry" /> <type name="IFileAssociationEntry" /> <type name="IFileEntry" /> <type name="IHashElementEntry" /> <type name="IMetadataSectionEntry" /> <type name="IMuiResourceIdLookupMapEntry" /> <type name="IMuiResourceMapEntry" /> <type name="IMuiResourceTypeIdIntEntry" /> <type name="IMuiResourceTypeIdStringEntry" /> <type name="IPermissionSetEntry" /> <type name="IProgIdRedirectionEntry" /> <type name="IResourceTableMappingEntry" /> <type name="ISubcategoryMembershipEntry" /> <type name="IWindowClassEntry" /> <type name="MetadataSectionEntry" /> <type name="MetadataSectionEntryFieldId" /> <type name="MuiResourceIdLookupMapEntry" /> <type name="MuiResourceIdLookupMapEntryFieldId" /> <type name="MuiResourceMapEntry" /> <type name="MuiResourceMapEntryFieldId" /> <type name="MuiResourceTypeIdIntEntry" /> <type name="MuiResourceTypeIdIntEntryFieldId" /> <type name="MuiResourceTypeIdStringEntry" /> <type name="MuiResourceTypeIdStringEntryFieldId" /> <type name="PermissionSetEntry" /> <type name="PermissionSetEntryFieldId" /> <type name="ProgIdRedirectionEntry" /> <type name="ProgIdRedirectionEntryFieldId" /> <type name="ResourceTableMappingEntry" /> <type name="ResourceTableMappingEntryFieldId" /> <type name="SubcategoryMembershipEntry" /> <type name="SubcategoryMembershipEntryFieldId" /> <type name="WindowClassEntry" /> <type name="WindowClassEntryFieldId" /> </Manifest> </Isolation> </Internal> </Deployment> <Diagnostics> <type name="Assert" /> <type name="AssertFilter" /> <type name="AssertFilters" /> <type name="ConditionalAttribute" /> <type name="DebuggableAttribute"> <type name="DebuggingModes" /> </type> <type name="Debugger" /> <type name="DebuggerBrowsableAttribute" /> <type name="DebuggerBrowsableState" /> <type name="DebuggerDisplayAttribute" /> <type name="DebuggerHiddenAttribute" /> <type name="DebuggerNonUserCodeAttribute" /> <type name="DebuggerStepperBoundaryAttribute" /> <type name="DebuggerStepThroughAttribute" /> <type name="DebuggerTypeProxyAttribute" /> <type name="DebuggerVisualizerAttribute" /> <type name="DefaultFilter" /> <type name="EditAndContinueHelper" /> <type name="ICustomDebuggerNotification" /> <type name="Log" /> <type name="LoggingLevels" /> <type name="LogMessageEventHandler" /> <type name="LogSwitch" /> <type name="LogSwitchLevelHandler" /> <type name="StackFrame" /> <type name="StackFrameHelper" /> <type name="StackTrace"> <type name="TraceFormat" /> </type> <CodeAnalysis> <type name="SuppressMessageAttribute" /> </CodeAnalysis> <Contracts> <type name="Contract" /> <type name="ContractClassAttribute" /> <type name="ContractClassForAttribute" /> <type name="ContractException" /> <type name="ContractFailedEventArgs" /> <type name="ContractFailureKind" /> <type name="ContractInvariantMethodAttribute" /> <type name="ContractPublicPropertyNameAttribute" /> <type name="ContractReferenceAssemblyAttribute" /> <type name="ContractRuntimeIgnoredAttribute" /> <type name="ContractVerificationAttribute" /> <type name="PureAttribute" /> <Internal> <type name="ContractHelper" /> </Internal> </Contracts> <Eventing> <type name="ControllerCommand" /> <type name="EventAttribute" /> <type name="EventChannel" /> <type name="EventDescriptorInternal" /> <type name="EventKeywords" /> <type name="EventLevel" /> <type name="EventOpcode" /> <type name="EventProvider"> <type name="ClassicEtw"> <type name="ControlCallback" /> <type name="EVENT_HEADER" /> <type name="EVENT_TRACE_HEADER" /> <type name="TRACE_GUID_REGISTRATION" /> <type name="WMIDPREQUESTCODE" /> <type name="WNODE_HEADER" /> </type> <type name="EventData" /> <type name="ManifestEtw"> <type name="EtwEnableCallback" /> <type name="EVENT_FILTER_DESCRIPTOR" /> </type> <type name="WriteEventErrorCode" /> </type> <type name="EventProviderBase"> <type name="EventData" /> </type> <type name="EventProviderCreatedEventArgs" /> <type name="EventProviderDataStream" /> <type name="EventTask" /> <type name="EventWrittenEventArgs" /> <type name="FrameworkEventSource" /> <type name="ManifestBuilder" /> <type name="ManifestEnvelope"> <type name="ManifestFormats" /> </type> <type name="NonEventAttribute" /> </Eventing> <SymbolStore> <type name="ISymbolBinder" /> <type name="ISymbolBinder1" /> <type name="ISymbolDocument" /> <type name="ISymbolDocumentWriter" /> <type name="ISymbolMethod" /> <type name="ISymbolNamespace" /> <type name="ISymbolReader" /> <type name="ISymbolScope" /> <type name="ISymbolVariable" /> <type name="ISymbolWriter" /> <type name="SymAddressKind" /> <type name="SymbolToken" /> <type name="SymDocumentType" /> <type name="SymLanguageType" /> <type name="SymLanguageVendor" /> </SymbolStore> </Diagnostics> <Globalization> <type name="BidiCategory" /> <type name="Calendar" /> <type name="CalendarAlgorithmType" /> <type name="CalendarData" /> <type name="CalendarId" /> <type name="CalendarWeekRule" /> <type name="CharUnicodeInfo"> <type name="DigitValues" /> <type name="UnicodeDataHeader" /> </type> <type name="ChineseLunisolarCalendar" /> <type name="CodePageDataItem" /> <type name="CompareInfo" /> <type name="CompareOptions" /> <type name="CultureData" /> <type name="CultureInfo" /> <type name="CultureNotFoundException" /> <type name="CultureTypes" /> <type name="DateTimeFormatFlags" /> <type name="DateTimeFormatInfo" /> <type name="DateTimeFormatInfoScanner" /> <type name="DateTimeStyles" /> <type name="DaylightTime" /> <type name="DigitShapes" /> <type name="EastAsianLunisolarCalendar" /> <type name="EncodingTable" /> <type name="EraInfo" /> <type name="FORMATFLAGS" /> <type name="GlobalizationAssembly" /> <type name="GregorianCalendar" /> <type name="GregorianCalendarHelper" /> <type name="GregorianCalendarTypes" /> <type name="HebrewCalendar"> <type name="__DateBuffer" /> </type> <type name="HebrewNumber"> <type name="HS" /> </type> <type name="HebrewNumberParsingContext" /> <type name="HebrewNumberParsingState" /> <type name="HijriCalendar" /> <type name="IdnMapping" /> <type name="InternalCodePageDataItem" /> <type name="InternalEncodingDataItem" /> <type name="JapaneseCalendar" /> <type name="JapaneseLunisolarCalendar" /> <type name="JulianCalendar" /> <type name="KoreanCalendar" /> <type name="KoreanLunisolarCalendar" /> <type name="MonthNameStyles" /> <type name="NumberFormatInfo" /> <type name="NumberStyles" /> <type name="PersianCalendar" /> <type name="RegionInfo" /> <type name="SortKey" /> <type name="StringInfo" /> <type name="TaiwanCalendar" /> <type name="TaiwanLunisolarCalendar" /> <type name="TextElementEnumerator" /> <type name="TextInfo" /> <type name="ThaiBuddhistCalendar" /> <type name="TimeSpanFormat"> <type name="FormatLiterals" /> <type name="Pattern" /> </type> <type name="TimeSpanParse" /> <type name="TimeSpanStyles" /> <type name="TokenHashValue" /> <type name="UmAlQuraCalendar"> <type name="DateMapping" /> </type> <type name="UnicodeCategory" /> </Globalization> <IO> <type name="BinaryReader" /> <type name="BinaryWriter" /> <type name="BufferedStream" /> <type name="Directory"> <type name="SearchData" /> </type> <type name="DirectoryInfo" /> <type name="DirectoryInfoResultHandler" /> <type name="DirectoryNotFoundException" /> <type name="DriveInfo" /> <type name="DriveNotFoundException" /> <type name="DriveType" /> <type name="EndOfStreamException" /> <type name="File" /> <type name="FileAccess" /> <type name="FileAttributes" /> <type name="FileInfo" /> <type name="FileInfoResultHandler" /> <type name="FileLoadException" /> <type name="FileMode" /> <type name="FileNotFoundException" /> <type name="FileOptions" /> <type name="FileShare" /> <type name="FileStream" /> <type name="FileStreamAsyncResult" /> <type name="FileSystemEnumerableFactory" /> <type name="FileSystemEnumerableHelpers" /> <type name="FileSystemEnumerableIterator" arity="1" /> <type name="FileSystemInfo" /> <type name="FileSystemInfoResultHandler" /> <type name="IOException" /> <type name="Iterator" arity="1" /> <type name="LongPath" /> <type name="LongPathDirectory" /> <type name="LongPathFile" /> <type name="MdaHelper" /> <type name="MemoryStream" /> <type name="Path" /> <type name="PathHelper" /> <type name="PathTooLongException" /> <type name="PinnedBufferMemoryStream" /> <type name="SearchOption" /> <type name="SearchResult" /> <type name="SearchResultHandler" arity="1" /> <type name="SeekOrigin" /> <type name="Stream"> <type name="SyncStream" /> </type> <type name="StreamContract" /> <type name="StreamReader" /> <type name="StreamWriter" /> <type name="StringReader" /> <type name="StringResultHandler" /> <type name="StringWriter" /> <type name="TextReader"> <type name="SyncTextReader" /> </type> <type name="TextWriter"> <type name="SyncTextWriter" /> </type> <type name="UnmanagedMemoryAccessor" /> <type name="UnmanagedMemoryStream" /> <type name="UnmanagedMemoryStreamWrapper" /> <type name="__ConsoleStream" /> <type name="__Error" /> <type name="__HResults" /> <IsolatedStorage> <type name="INormalizeForIsolatedStorage" /> <type name="IsolatedStorage" /> <type name="IsolatedStorageException" /> <type name="IsolatedStorageFile" /> <type name="IsolatedStorageFileEnumerator" /> <type name="IsolatedStorageFileStream" /> <type name="IsolatedStorageScope" /> <type name="IsolatedStorageSecurityOptions" /> <type name="IsolatedStorageSecurityState" /> <type name="SafeIsolatedStorageFileHandle" /> <type name="TwoLevelFileEnumerator" /> <type name="TwoPaths" /> <type name="__HResults" /> </IsolatedStorage> </IO> <Reflection> <type name="AmbiguousMatchException" /> <type name="Assembly" /> <type name="AssemblyAlgorithmIdAttribute" /> <type name="AssemblyCompanyAttribute" /> <type name="AssemblyConfigurationAttribute" /> <type name="AssemblyCopyrightAttribute" /> <type name="AssemblyCultureAttribute" /> <type name="AssemblyDefaultAliasAttribute" /> <type name="AssemblyDelaySignAttribute" /> <type name="AssemblyDescriptionAttribute" /> <type name="AssemblyFileVersionAttribute" /> <type name="AssemblyFlagsAttribute" /> <type name="AssemblyInformationalVersionAttribute" /> <type name="AssemblyKeyFileAttribute" /> <type name="AssemblyKeyNameAttribute" /> <type name="AssemblyMetadata" /> <type name="AssemblyName" /> <type name="AssemblyNameFlags" /> <type name="AssemblyNameProxy" /> <type name="AssemblyProductAttribute" /> <type name="AssemblyTitleAttribute" /> <type name="AssemblyTrademarkAttribute" /> <type name="AssemblyVersionAttribute" /> <type name="AssociateRecord" /> <type name="Associates"> <type name="Attributes" /> </type> <type name="Binder" /> <type name="BindingFlags" /> <type name="CallingConventions" /> <type name="CerArrayList" arity="1" /> <type name="CerHashtable" arity="2" /> <type name="ConstArray" /> <type name="ConstructorInfo" /> <type name="CorElementType" /> <type name="CustomAttribute" /> <type name="CustomAttributeCtorParameter" /> <type name="CustomAttributeData" /> <type name="CustomAttributeEncodedArgument" /> <type name="CustomAttributeEncoding" /> <type name="CustomAttributeFormatException" /> <type name="CustomAttributeNamedArgument" /> <type name="CustomAttributeNamedParameter" /> <type name="CustomAttributeRecord" /> <type name="CustomAttributeType" /> <type name="CustomAttributeTypedArgument" /> <type name="DeclSecurityAttributes" /> <type name="DefaultMemberAttribute" /> <type name="EventAttributes" /> <type name="EventInfo" /> <type name="ExceptionHandlingClause" /> <type name="ExceptionHandlingClauseOptions" /> <type name="FieldAttributes" /> <type name="FieldInfo" /> <type name="GenericParameterAttributes" /> <type name="ICustomAttributeProvider" /> <type name="ImageFileMachine" /> <type name="InterfaceMapping" /> <type name="InvalidFilterCriteriaException" /> <type name="INVOCATION_FLAGS" /> <type name="IReflect" /> <type name="LoaderAllocator" /> <type name="LoaderAllocatorScout" /> <type name="LocalVariableInfo" /> <type name="ManifestResourceAttributes" /> <type name="ManifestResourceInfo" /> <type name="MdConstant" /> <type name="MdFieldInfo" /> <type name="MdSigCallingConvention" /> <type name="MemberFilter" /> <type name="MemberInfo" /> <type name="MemberInfoContracts" /> <type name="MemberInfoSerializationHolder" /> <type name="MemberListType" /> <type name="MemberTypes" /> <type name="MetadataArgs"> <type name="SkipAddresses" /> </type> <type name="MetadataCodedTokenType" /> <type name="MetadataColumn" /> <type name="MetadataColumnType" /> <type name="MetadataException" /> <type name="MetadataFieldOffset" /> <type name="MetadataFileAttributes" /> <type name="MetadataImport" /> <type name="MetadataTable" /> <type name="MetadataToken" /> <type name="MetadataTokenType" /> <type name="MethodAttributes" /> <type name="MethodBase" /> <type name="MethodBody" /> <type name="MethodImplAttributes" /> <type name="MethodInfo" /> <type name="MethodSemanticsAttributes" /> <type name="Missing" /> <type name="Module" /> <type name="ModuleResolveEventHandler" /> <type name="ObfuscateAssemblyAttribute" /> <type name="ObfuscationAttribute" /> <type name="ParameterAttributes" /> <type name="ParameterInfo" /> <type name="ParameterModifier" /> <type name="PInvokeAttributes" /> <type name="Pointer" /> <type name="PortableExecutableKinds" /> <type name="ProcessorArchitecture" /> <type name="PropertyAttributes" /> <type name="PropertyInfo" /> <type name="PseudoCustomAttribute" /> <type name="ReflectionTypeLoadException" /> <type name="ResourceAttributes" /> <type name="ResourceLocation" /> <type name="RtFieldInfo" /> <type name="RuntimeAssembly" /> <type name="RuntimeConstructorInfo" /> <type name="RuntimeEventInfo" /> <type name="RuntimeFieldInfo" /> <type name="RuntimeMethodInfo" /> <type name="RuntimeModule" /> <type name="RuntimeParameterInfo" /> <type name="RuntimePropertyInfo" /> <type name="SecurityContextFrame" /> <type name="StrongNameKeyPair" /> <type name="TargetException" /> <type name="TargetInvocationException" /> <type name="TargetParameterCountException" /> <type name="TypeAttributes" /> <type name="TypeDelegator" /> <type name="TypeFilter" /> <type name="__Filters" /> <Cache> <type name="CacheAction" /> <type name="CacheObjType" /> <type name="ClearCacheEventArgs" /> <type name="ClearCacheHandler" /> <type name="InternalCache" /> <type name="InternalCacheItem" /> <type name="TypeNameStruct" /> </Cache> <Emit> <type name="AssemblyBuilder" /> <type name="AssemblyBuilderAccess" /> <type name="AssemblyBuilderData" /> <type name="ConstructorBuilder" /> <type name="ConstructorOnTypeBuilderInstantiation" /> <type name="CustomAttributeBuilder" /> <type name="DynamicAssemblyFlags" /> <type name="DynamicILGenerator" /> <type name="DynamicILInfo" /> <type name="DynamicMethod"> <type name="RTDynamicMethod" /> </type> <type name="DynamicResolver"> <type name="SecurityControlFlags" /> </type> <type name="DynamicScope" /> <type name="EnumBuilder" /> <type name="EventBuilder" /> <type name="EventToken" /> <type name="FieldBuilder" /> <type name="FieldOnTypeBuilderInstantiation" /> <type name="FieldToken" /> <type name="FlowControl" /> <type name="GenericFieldInfo" /> <type name="GenericMethodInfo" /> <type name="GenericTypeParameterBuilder" /> <type name="ILGenerator" /> <type name="InternalAssemblyBuilder" /> <type name="InternalModuleBuilder" /> <type name="Label" /> <type name="LineNumberInfo" /> <type name="LocalBuilder" /> <type name="LocalSymInfo" /> <type name="MethodBuilder" /> <type name="MethodBuilderInstantiation" /> <type name="MethodOnTypeBuilderInstantiation" /> <type name="MethodRental" /> <type name="MethodToken" /> <type name="ModuleBuilder" /> <type name="ModuleBuilderData" /> <type name="NativeVersionInfo" /> <type name="OpCode" /> <type name="OpCodes" /> <type name="OpCodeType" /> <type name="OperandType" /> <type name="PackingSize" /> <type name="ParameterBuilder" /> <type name="ParameterToken" /> <type name="PEFileKinds" /> <type name="PropertyBuilder" /> <type name="PropertyToken" /> <type name="REDocument" /> <type name="ResWriterData" /> <type name="ScopeAction" /> <type name="ScopeTree" /> <type name="SignatureHelper" /> <type name="SignatureToken" /> <type name="StackBehaviour" /> <type name="StringToken" /> <type name="SymbolMethod" /> <type name="SymbolType" /> <type name="TypeBuilder"> <type name="CustAttr" /> </type> <type name="TypeBuilderInstantiation" /> <type name="TypeKind" /> <type name="TypeNameBuilder"> <type name="Format" /> </type> <type name="TypeToken" /> <type name="UnmanagedMarshal" /> <type name="VarArgMethod" /> <type name="__ExceptionInfo" /> <type name="__ExceptionInstance" /> <type name="__FixupData" /> </Emit> </Reflection> <Resources> <type name="FastResourceComparer" /> <type name="FileBasedResourceGroveler" /> <type name="IResourceGroveler" /> <type name="IResourceReader" /> <type name="IResourceWriter" /> <type name="ManifestBasedResourceGroveler" /> <type name="MissingManifestResourceException" /> <type name="MissingSatelliteAssemblyException" /> <type name="NeutralResourcesLanguageAttribute" /> <type name="ResourceFallbackManager" /> <type name="ResourceLocator" /> <type name="ResourceManager"> <type name="ResourceManagerMediator" /> </type> <type name="ResourceReader"> <type name="ResourceEnumerator" /> <type name="TypeLimitingDeserializationBinder" /> </type> <type name="ResourceSet" /> <type name="ResourceTypeCode" /> <type name="ResourceWriter" /> <type name="RuntimeResourceSet" /> <type name="SatelliteContractVersionAttribute" /> <type name="UltimateResourceFallbackLocation" /> </Resources> <Runtime> <type name="AssemblyTargetedPatchBandAttribute" /> <type name="ForceTokenStabilizationAttribute" /> <type name="GCLatencyMode" /> <type name="GCSettings" /> <type name="MemoryFailPoint" /> <type name="TargetedPatchingOptOutAttribute" /> <CompilerServices> <type name="AccessedThroughPropertyAttribute" /> <type name="AssemblyAttributesGoHere" /> <type name="AssemblyAttributesGoHereM" /> <type name="AssemblyAttributesGoHereS" /> <type name="AssemblyAttributesGoHereSM" /> <type name="CallConvCdecl" /> <type name="CallConvFastcall" /> <type name="CallConvStdcall" /> <type name="CallConvThiscall" /> <type name="CompilationRelaxations" /> <type name="CompilationRelaxationsAttribute" /> <type name="CompilerGeneratedAttribute" /> <type name="CompilerGlobalScopeAttribute" /> <type name="CompilerMarshalOverride" /> <type name="ConditionalWeakTable" arity="2"> <type name="CreateValueCallback" /> </type> <type name="CustomConstantAttribute" /> <type name="DateTimeConstantAttribute" /> <type name="DecimalConstantAttribute" /> <type name="DecoratedNameAttribute" /> <type name="DefaultDependencyAttribute" /> <type name="DependencyAttribute" /> <type name="DependentHandle" /> <type name="DiscardableAttribute" /> <type name="FixedAddressValueTypeAttribute" /> <type name="FixedBufferAttribute" /> <type name="FriendAccessAllowedAttribute" /> <type name="HasCopySemanticsAttribute" /> <type name="IDispatchConstantAttribute" /> <type name="IndexerNameAttribute" /> <type name="InternalsVisibleToAttribute" /> <type name="IsBoxed" /> <type name="IsByValue" /> <type name="IsConst" /> <type name="IsCopyConstructed" /> <type name="IsExplicitlyDereferenced" /> <type name="IsImplicitlyDereferenced" /> <type name="IsJitIntrinsic" /> <type name="IsLong" /> <type name="IsPinned" /> <type name="IsSignUnspecifiedByte" /> <type name="IsUdtReturn" /> <type name="IsVolatile" /> <type name="IUnknownConstantAttribute" /> <type name="JitHelpers" /> <type name="LoadHint" /> <type name="MethodCodeType" /> <type name="MethodImplAttribute" /> <type name="MethodImplOptions" /> <type name="NativeCppClassAttribute" /> <type name="ObjectHandleOnStack" /> <type name="PinningHelper" /> <type name="ReferenceAssemblyAttribute" /> <type name="RequiredAttributeAttribute" /> <type name="RuntimeCompatibilityAttribute" /> <type name="RuntimeHelpers"> <type name="CleanupCode" /> <type name="TryCode" /> </type> <type name="RuntimeWrappedException" /> <type name="ScopelessEnumAttribute" /> <type name="SpecialNameAttribute" /> <type name="StackCrawlMarkHandle" /> <type name="StringFreezingAttribute" /> <type name="StringHandleOnStack" /> <type name="SuppressIldasmAttribute" /> <type name="SuppressMergeCheckAttribute" /> <type name="TypeDependencyAttribute" /> <type name="TypeForwardedFromAttribute" /> <type name="TypeForwardedToAttribute" /> <type name="UnsafeValueTypeAttribute" /> </CompilerServices> <ConstrainedExecution> <type name="Cer" /> <type name="Consistency" /> <type name="CriticalFinalizerObject" /> <type name="PrePrepareMethodAttribute" /> <type name="ReliabilityContractAttribute" /> </ConstrainedExecution> <ExceptionServices> <type name="FirstChanceExceptionEventArgs" /> <type name="HandleProcessCorruptedStateExceptionsAttribute" /> </ExceptionServices> <Hosting> <type name="ActivationArguments" /> <type name="ApplicationActivator" /> <type name="ManifestRunner" /> </Hosting> <InteropServices> <type name="AllowReversePInvokeCallsAttribute" /> <type name="ArrayWithOffset" /> <type name="AssemblyRegistrationFlags" /> <type name="AutomationProxyAttribute" /> <type name="BestFitMappingAttribute" /> <type name="BINDPTR" /> <type name="BIND_OPTS" /> <type name="BStrWrapper" /> <type name="CALLCONV" /> <type name="CallingConvention" /> <type name="CharSet" /> <type name="ClassInterfaceAttribute" /> <type name="ClassInterfaceType" /> <type name="CoClassAttribute" /> <type name="ComAliasNameAttribute" /> <type name="ComCompatibleVersionAttribute" /> <type name="ComConversionLossAttribute" /> <type name="ComDefaultInterfaceAttribute" /> <type name="ComEventInterfaceAttribute" /> <type name="ComEventsHelper" /> <type name="ComEventsInfo" /> <type name="ComEventsMethod"> <type name="DelegateWrapper" /> </type> <type name="ComEventsSink" /> <type name="COMException" /> <type name="ComImportAttribute" /> <type name="ComInterfaceType" /> <type name="ComMemberType" /> <type name="ComRegisterFunctionAttribute" /> <type name="ComSourceInterfacesAttribute" /> <type name="ComUnregisterFunctionAttribute" /> <type name="ComVisibleAttribute" /> <type name="CONNECTDATA" /> <type name="CriticalHandle" /> <type name="CurrencyWrapper" /> <type name="CustomQueryInterfaceMode" /> <type name="CustomQueryInterfaceResult" /> <type name="DefaultCharSetAttribute" /> <type name="DESCKIND" /> <type name="DispatchWrapper" /> <type name="DispIdAttribute" /> <type name="DISPPARAMS" /> <type name="DllImportAttribute" /> <type name="ELEMDESC"> <type name="DESCUNION" /> </type> <type name="ErrorWrapper" /> <type name="EXCEPINFO" /> <type name="ExporterEventKind" /> <type name="ExtensibleClassFactory" /> <type name="ExternalException" /> <type name="FieldOffsetAttribute" /> <type name="FILETIME" /> <type name="FUNCDESC" /> <type name="FUNCFLAGS" /> <type name="FUNCKIND" /> <type name="GCHandle" /> <type name="GCHandleCookieTable" /> <type name="GCHandleType" /> <type name="GuidAttribute" /> <type name="HandleRef" /> <type name="ICustomAdapter" /> <type name="ICustomFactory" /> <type name="ICustomMarshaler" /> <type name="ICustomQueryInterface" /> <type name="IDispatchImplAttribute" /> <type name="IDispatchImplType" /> <type name="IDLDESC" /> <type name="IDLFLAG" /> <type name="IMPLTYPEFLAGS" /> <type name="ImportedFromTypeLibAttribute" /> <type name="ImporterCallback" /> <type name="ImporterEventKind" /> <type name="InAttribute" /> <type name="InterfaceTypeAttribute" /> <type name="InvalidComObjectException" /> <type name="InvalidOleVariantTypeException" /> <type name="INVOKEKIND" /> <type name="IRegistrationServices" /> <type name="ITypeLibConverter" /> <type name="ITypeLibExporterNameProvider" /> <type name="ITypeLibExporterNotifySink" /> <type name="ITypeLibImporterNotifySink" /> <type name="LayoutKind" /> <type name="LCIDConversionAttribute" /> <type name="LIBFLAGS" /> <type name="ManagedToNativeComInteropStubAttribute" /> <type name="Marshal" /> <type name="MarshalAsAttribute" /> <type name="MarshalDirectiveException" /> <type name="NativeMethods"> <type name="IDispatch" /> </type> <type name="ObjectCreationDelegate" /> <type name="OptionalAttribute" /> <type name="OutAttribute" /> <type name="PARAMDESC" /> <type name="PARAMFLAG" /> <type name="PInvokeMap" /> <type name="PreserveSigAttribute" /> <type name="PrimaryInteropAssemblyAttribute" /> <type name="ProgIdAttribute" /> <type name="RegistrationClassContext" /> <type name="RegistrationConnectionType" /> <type name="RegistrationServices" /> <type name="RuntimeEnvironment" /> <type name="SafeArrayRankMismatchException" /> <type name="SafeArrayTypeMismatchException" /> <type name="SafeBuffer" /> <type name="SafeHandle" /> <type name="SEHException" /> <type name="SetWin32ContextInIDispatchAttribute" /> <type name="STATSTG" /> <type name="StructLayoutAttribute" /> <type name="SYSKIND" /> <type name="TYPEATTR" /> <type name="TYPEDESC" /> <type name="TYPEFLAGS" /> <type name="TypeIdentifierAttribute" /> <type name="TYPEKIND" /> <type name="TYPELIBATTR" /> <type name="TypeLibConverter" /> <type name="TypeLibExporterFlags" /> <type name="TypeLibFuncAttribute" /> <type name="TypeLibFuncFlags" /> <type name="TypeLibImportClassAttribute" /> <type name="TypeLibImporterFlags" /> <type name="TypeLibTypeAttribute" /> <type name="TypeLibTypeFlags" /> <type name="TypeLibVarAttribute" /> <type name="TypeLibVarFlags" /> <type name="TypeLibVersionAttribute" /> <type name="UCOMIBindCtx" /> <type name="UCOMIConnectionPoint" /> <type name="UCOMIConnectionPointContainer" /> <type name="UCOMIEnumConnectionPoints" /> <type name="UCOMIEnumConnections" /> <type name="UCOMIEnumerable" /> <type name="UCOMIEnumerator" /> <type name="UCOMIEnumMoniker" /> <type name="UCOMIEnumString" /> <type name="UCOMIEnumVARIANT" /> <type name="UCOMIExpando" /> <type name="UCOMIMoniker" /> <type name="UCOMIPersistFile" /> <type name="UCOMIReflect" /> <type name="UCOMIRunningObjectTable" /> <type name="UCOMIStream" /> <type name="UCOMITypeComp" /> <type name="UCOMITypeInfo" /> <type name="UCOMITypeLib" /> <type name="UnknownWrapper" /> <type name="UnmanagedFunctionPointerAttribute" /> <type name="UnmanagedType" /> <type name="VARDESC"> <type name="DESCUNION" /> </type> <type name="VarEnum" /> <type name="VARFLAGS" /> <type name="Variant"> <type name="Record" /> <type name="TypeUnion" /> <type name="UnionTypes" /> </type> <type name="VariantWrapper" /> <type name="_Activator" /> <type name="_Assembly" /> <type name="_AssemblyBuilder" /> <type name="_AssemblyName" /> <type name="_Attribute" /> <type name="_ConstructorBuilder" /> <type name="_ConstructorInfo" /> <type name="_CustomAttributeBuilder" /> <type name="_EnumBuilder" /> <type name="_EventBuilder" /> <type name="_EventInfo" /> <type name="_Exception" /> <type name="_FieldBuilder" /> <type name="_FieldInfo" /> <type name="_ILGenerator" /> <type name="_LocalBuilder" /> <type name="_MemberInfo" /> <type name="_MethodBase" /> <type name="_MethodBuilder" /> <type name="_MethodInfo" /> <type name="_MethodRental" /> <type name="_Module" /> <type name="_ModuleBuilder" /> <type name="_ParameterBuilder" /> <type name="_ParameterInfo" /> <type name="_PropertyBuilder" /> <type name="_PropertyInfo" /> <type name="_SignatureHelper" /> <type name="_Thread" /> <type name="_Type" /> <type name="_TypeBuilder" /> <ComTypes> <type name="BINDPTR" /> <type name="BIND_OPTS" /> <type name="CALLCONV" /> <type name="CONNECTDATA" /> <type name="DESCKIND" /> <type name="DISPPARAMS" /> <type name="ELEMDESC"> <type name="DESCUNION" /> </type> <type name="EXCEPINFO" /> <type name="FILETIME" /> <type name="FUNCDESC" /> <type name="FUNCFLAGS" /> <type name="FUNCKIND" /> <type name="IBindCtx" /> <type name="IConnectionPoint" /> <type name="IConnectionPointContainer" /> <type name="IDLDESC" /> <type name="IDLFLAG" /> <type name="IEnumConnectionPoints" /> <type name="IEnumConnections" /> <type name="IEnumerable" /> <type name="IEnumerator" /> <type name="IEnumMoniker" /> <type name="IEnumString" /> <type name="IEnumVARIANT" /> <type name="IExpando" /> <type name="IMoniker" /> <type name="IMPLTYPEFLAGS" /> <type name="INVOKEKIND" /> <type name="IPersistFile" /> <type name="IReflect" /> <type name="IRunningObjectTable" /> <type name="IStream" /> <type name="ITypeComp" /> <type name="ITypeInfo" /> <type name="ITypeInfo2" /> <type name="ITypeLib" /> <type name="ITypeLib2" /> <type name="LIBFLAGS" /> <type name="PARAMDESC" /> <type name="PARAMFLAG" /> <type name="STATSTG" /> <type name="SYSKIND" /> <type name="TYPEATTR" /> <type name="TYPEDESC" /> <type name="TYPEFLAGS" /> <type name="TYPEKIND" /> <type name="TYPELIBATTR" /> <type name="VARDESC"> <type name="DESCUNION" /> </type> <type name="VARFLAGS" /> <type name="VARKIND" /> </ComTypes> <Expando> <type name="IExpando" /> </Expando> <TCEAdapterGen> <type name="EventItfInfo" /> <type name="EventProviderWriter" /> <type name="EventSinkHelperWriter" /> <type name="NameSpaceExtractor" /> <type name="TCEAdapterGenerator" /> </TCEAdapterGen> </InteropServices> <Remoting> <type name="ActivatedClientTypeEntry" /> <type name="ActivatedServiceTypeEntry" /> <type name="ChannelInfo" /> <type name="ComRedirectionProxy" /> <type name="CustomErrorsModes" /> <type name="DelayLoadClientChannelEntry" /> <type name="DomainSpecificRemotingData" /> <type name="DuplicateIdentityOption" /> <type name="DynamicTypeInfo" /> <type name="EnvoyInfo" /> <type name="IChannelInfo" /> <type name="Identity" /> <type name="IdentityHolder" /> <type name="IdOps" /> <type name="IEnvoyInfo" /> <type name="InternalRemotingServices" /> <type name="IObjectHandle" /> <type name="IRemotingTypeInfo" /> <type name="ObjectHandle" /> <type name="ObjRef" /> <type name="RedirectionProxy" /> <type name="RemoteAppEntry" /> <type name="RemotingConfigHandler"> <type name="RemotingConfigInfo" /> </type> <type name="RemotingConfiguration" /> <type name="RemotingException" /> <type name="RemotingServices" /> <type name="RemotingTimeoutException" /> <type name="ServerException" /> <type name="ServerIdentity" /> <type name="SoapServices" /> <type name="TypeEntry" /> <type name="TypeInfo" /> <type name="WellKnownClientTypeEntry" /> <type name="WellKnownObjectMode" /> <type name="WellKnownServiceTypeEntry" /> <type name="XmlNamespaceEncoder" /> <type name="__HResults" /> <Activation> <type name="ActivationAttributeStack" /> <type name="ActivationListener" /> <type name="ActivationServices" /> <type name="ActivatorLevel" /> <type name="AppDomainLevelActivator" /> <type name="ConstructionLevelActivator" /> <type name="ContextLevelActivator" /> <type name="IActivator" /> <type name="IConstructionCallMessage" /> <type name="IConstructionReturnMessage" /> <type name="LocalActivator" /> <type name="RemotePropertyHolderAttribute" /> <type name="RemotingXmlConfigFileData"> <type name="ChannelEntry" /> <type name="ClientWellKnownEntry" /> <type name="ContextAttributeEntry" /> <type name="CustomErrorsEntry" /> <type name="InteropXmlElementEntry" /> <type name="InteropXmlTypeEntry" /> <type name="LifetimeEntry" /> <type name="PreLoadEntry" /> <type name="RemoteAppEntry" /> <type name="ServerWellKnownEntry" /> <type name="SinkProviderEntry" /> <type name="TypeEntry" /> </type> <type name="RemotingXmlConfigFileParser" /> <type name="UrlAttribute" /> </Activation> <Channels> <type name="ADAsyncWorkItem" /> <type name="AggregateDictionary" /> <type name="AsyncMessageHelper" /> <type name="AsyncWorkItem" /> <type name="BaseChannelObjectWithProperties" /> <type name="BaseChannelSinkWithProperties" /> <type name="BaseChannelWithProperties" /> <type name="ChannelDataStore" /> <type name="ChannelServices" /> <type name="ChannelServicesData" /> <type name="ClientChannelSinkStack" /> <type name="CrossAppDomainChannel" /> <type name="CrossAppDomainData" /> <type name="CrossAppDomainSerializer" /> <type name="CrossAppDomainSink" /> <type name="CrossContextChannel" /> <type name="DictionaryEnumeratorByKeys" /> <type name="DispatchChannelSink" /> <type name="DispatchChannelSinkProvider" /> <type name="IChannel" /> <type name="IChannelDataStore" /> <type name="IChannelReceiver" /> <type name="IChannelReceiverHook" /> <type name="IChannelSender" /> <type name="IChannelSinkBase" /> <type name="IClientChannelSink" /> <type name="IClientChannelSinkProvider" /> <type name="IClientChannelSinkStack" /> <type name="IClientFormatterSink" /> <type name="IClientFormatterSinkProvider" /> <type name="IClientResponseChannelSinkStack" /> <type name="ISecurableChannel" /> <type name="IServerChannelSink" /> <type name="IServerChannelSinkProvider" /> <type name="IServerChannelSinkStack" /> <type name="IServerFormatterSinkProvider" /> <type name="IServerResponseChannelSinkStack" /> <type name="ITransportHeaders" /> <type name="Perf_Contexts" /> <type name="RegisteredChannel" /> <type name="RegisteredChannelList" /> <type name="RemotingProfilerEvent" /> <type name="ServerAsyncReplyTerminatorSink" /> <type name="ServerChannelSinkStack" /> <type name="ServerProcessing" /> <type name="SinkProviderData" /> <type name="TransportHeaders" /> </Channels> <Contexts> <type name="ArrayWithSize" /> <type name="CallBackHelper" /> <type name="Context" /> <type name="ContextAttribute" /> <type name="ContextProperty" /> <type name="CrossContextDelegate" /> <type name="DynamicPropertyHolder" /> <type name="IContextAttribute" /> <type name="IContextProperty" /> <type name="IContextPropertyActivator" /> <type name="IContributeClientContextSink" /> <type name="IContributeDynamicSink" /> <type name="IContributeEnvoySink" /> <type name="IContributeObjectSink" /> <type name="IContributeServerContextSink" /> <type name="IDynamicMessageSink" /> <type name="IDynamicProperty" /> <type name="SynchronizationAttribute" /> <type name="SynchronizedClientContextSink"> <type name="AsyncReplySink" /> </type> <type name="SynchronizedServerContextSink" /> <type name="WorkItem" /> </Contexts> <Lifetime> <type name="ClientSponsor" /> <type name="ILease" /> <type name="ISponsor" /> <type name="Lease"> <type name="AsyncRenewal" /> <type name="SponsorState" /> <type name="SponsorStateInfo" /> </type> <type name="LeaseLifeTimeServiceProperty" /> <type name="LeaseManager"> <type name="SponsorInfo" /> </type> <type name="LeaseSink" /> <type name="LeaseState" /> <type name="LifetimeServices" /> </Lifetime> <Messaging> <type name="ArgMapper" /> <type name="AsyncReplySink" /> <type name="AsyncResult" /> <type name="CallContext" /> <type name="CallContextRemotingData" /> <type name="CallContextSecurityData" /> <type name="CCMDictionary" /> <type name="ClientAsyncReplyTerminatorSink" /> <type name="ClientContextTerminatorSink" /> <type name="ConstructionCall" /> <type name="ConstructionResponse" /> <type name="ConstructorCallMessage" /> <type name="ConstructorReturnMessage" /> <type name="CRMDictionary" /> <type name="DisposeSink" /> <type name="EnvoyTerminatorSink" /> <type name="ErrorMessage" /> <type name="Header" /> <type name="HeaderHandler" /> <type name="IInternalMessage" /> <type name="IllogicalCallContext" /> <type name="ILogicalThreadAffinative" /> <type name="IMessage" /> <type name="IMessageCtrl" /> <type name="IMessageSink" /> <type name="IMethodCallMessage" /> <type name="IMethodMessage" /> <type name="IMethodReturnMessage" /> <type name="InternalMessageWrapper" /> <type name="InternalSink" /> <type name="IRemotingFormatter" /> <type name="ISerializationRootObject" /> <type name="LogicalCallContext" /> <type name="MCMDictionary" /> <type name="Message" /> <type name="MessageDictionary" /> <type name="MessageDictionaryEnumerator" /> <type name="MessageSmuggler"> <type name="SerializedArg" /> </type> <type name="MessageSurrogate" /> <type name="MessageSurrogateFilter" /> <type name="MethodCall" /> <type name="MethodCallMessageWrapper" /> <type name="MethodResponse" /> <type name="MethodReturnMessageWrapper" /> <type name="MRMDictionary" /> <type name="ObjRefSurrogate" /> <type name="OneWayAttribute" /> <type name="RemotingSurrogate" /> <type name="RemotingSurrogateSelector" /> <type name="ReturnMessage" /> <type name="SerializationMonkey" /> <type name="ServerContextTerminatorSink" /> <type name="ServerObjectTerminatorSink" /> <type name="SmuggledMethodCallMessage" /> <type name="SmuggledMethodReturnMessage" /> <type name="SmuggledObjRef" /> <type name="SoapMessageSurrogate" /> <type name="StackBasedReturnMessage" /> <type name="StackBuilderSink" /> <type name="TransitionCall" /> </Messaging> <Metadata> <type name="RemotingCachedData" /> <type name="RemotingMethodCachedData" /> <type name="RemotingTypeCachedData" /> <type name="SoapAttribute" /> <type name="SoapFieldAttribute" /> <type name="SoapMethodAttribute" /> <type name="SoapOption" /> <type name="SoapParameterAttribute" /> <type name="SoapTypeAttribute" /> <type name="XmlFieldOrderOption" /> <W3cXsd2001> <type name="ISoapXsd" /> <type name="SoapAnyUri" /> <type name="SoapBase64Binary" /> <type name="SoapDate" /> <type name="SoapDateTime" /> <type name="SoapDay" /> <type name="SoapDuration" /> <type name="SoapEntities" /> <type name="SoapEntity" /> <type name="SoapHexBinary" /> <type name="SoapId" /> <type name="SoapIdref" /> <type name="SoapIdrefs" /> <type name="SoapInteger" /> <type name="SoapLanguage" /> <type name="SoapMonth" /> <type name="SoapMonthDay" /> <type name="SoapName" /> <type name="SoapNcName" /> <type name="SoapNegativeInteger" /> <type name="SoapNmtoken" /> <type name="SoapNmtokens" /> <type name="SoapNonNegativeInteger" /> <type name="SoapNonPositiveInteger" /> <type name="SoapNormalizedString" /> <type name="SoapNotation" /> <type name="SoapPositiveInteger" /> <type name="SoapQName" /> <type name="SoapTime" /> <type name="SoapToken" /> <type name="SoapType" /> <type name="SoapYear" /> <type name="SoapYearMonth" /> </W3cXsd2001> </Metadata> <Proxies> <type name="AgileAsyncWorkerItem" /> <type name="CallType" /> <type name="MessageData" /> <type name="ProxyAttribute" /> <type name="RealProxy" /> <type name="RealProxyFlags" /> <type name="RemotingProxy" /> <type name="__TransparentProxy" /> </Proxies> <Services> <type name="EnterpriseServicesHelper" /> <type name="ITrackingHandler" /> <type name="TrackingServices" /> </Services> </Remoting> <Serialization> <type name="DeserializationEventHandler" /> <type name="FixupHolder" /> <type name="FixupHolderList" /> <type name="Formatter" /> <type name="FormatterConverter" /> <type name="FormatterServices" /> <type name="IDeserializationCallback" /> <type name="IFormatter" /> <type name="IFormatterConverter" /> <type name="IObjectReference" /> <type name="ISafeSerializationData" /> <type name="ISerializable" /> <type name="ISerializationSurrogate" /> <type name="ISurrogateSelector" /> <type name="LongList" /> <type name="MemberHolder" /> <type name="ObjectCloneHelper" /> <type name="ObjectHolder" /> <type name="ObjectHolderList" /> <type name="ObjectHolderListEnumerator" /> <type name="ObjectIDGenerator" /> <type name="ObjectManager" /> <type name="OnDeserializedAttribute" /> <type name="OnDeserializingAttribute" /> <type name="OnSerializedAttribute" /> <type name="OnSerializingAttribute" /> <type name="OptionalFieldAttribute" /> <type name="SafeSerializationEventArgs" /> <type name="SafeSerializationManager" /> <type name="SerializationBinder" /> <type name="SerializationEntry" /> <type name="SerializationEventHandler" /> <type name="SerializationEvents" /> <type name="SerializationEventsCache" /> <type name="SerializationException" /> <type name="SerializationFieldInfo" /> <type name="SerializationInfo" /> <type name="SerializationInfoEnumerator" /> <type name="SerializationObjectManager" /> <type name="StreamingContext" /> <type name="StreamingContextStates" /> <type name="SurrogateForCyclicalReference" /> <type name="SurrogateHashtable" /> <type name="SurrogateKey" /> <type name="SurrogateSelector" /> <type name="TypeLoadExceptionHolder" /> <type name="ValueTypeFixupInfo" /> <Formatters> <type name="FormatterAssemblyStyle" /> <type name="FormatterTypeStyle" /> <type name="IFieldInfo" /> <type name="InternalRM" /> <type name="InternalST" /> <type name="ISoapMessage" /> <type name="SerTrace" /> <type name="ServerFault" /> <type name="SoapFault" /> <type name="SoapMessage" /> <type name="TypeFilterLevel" /> <Binary> <type name="BinaryArray" /> <type name="BinaryArrayTypeEnum" /> <type name="BinaryAssembly" /> <type name="BinaryAssemblyInfo" /> <type name="BinaryConverter" /> <type name="BinaryCrossAppDomainAssembly" /> <type name="BinaryCrossAppDomainMap" /> <type name="BinaryCrossAppDomainString" /> <type name="BinaryFormatter" /> <type name="BinaryHeaderEnum" /> <type name="BinaryMethodCall" /> <type name="BinaryMethodCallMessage" /> <type name="BinaryMethodReturn" /> <type name="BinaryMethodReturnMessage" /> <type name="BinaryObject" /> <type name="BinaryObjectString" /> <type name="BinaryObjectWithMap" /> <type name="BinaryObjectWithMapTyped" /> <type name="BinaryTypeEnum" /> <type name="BinaryUtil" /> <type name="Converter" /> <type name="InternalArrayTypeE" /> <type name="InternalElementTypeE" /> <type name="InternalFE" /> <type name="InternalMemberTypeE" /> <type name="InternalMemberValueE" /> <type name="InternalNameSpaceE" /> <type name="InternalObjectPositionE" /> <type name="InternalObjectTypeE" /> <type name="InternalParseStateE" /> <type name="InternalParseTypeE" /> <type name="InternalPrimitiveTypeE" /> <type name="InternalSerializerTypeE" /> <type name="IntSizedArray" /> <type name="IOUtil" /> <type name="IStreamable" /> <type name="MemberPrimitiveTyped" /> <type name="MemberPrimitiveUnTyped" /> <type name="MemberReference" /> <type name="MessageEnd" /> <type name="MessageEnum" /> <type name="NameCache" /> <type name="NameInfo" /> <type name="ObjectMap" /> <type name="ObjectMapInfo" /> <type name="ObjectNull" /> <type name="ObjectProgress" /> <type name="ObjectReader"> <type name="TopLevelAssemblyTypeResolver" /> <type name="TypeNAssembly" /> </type> <type name="ObjectWriter" /> <type name="ParseRecord" /> <type name="PrimitiveArray" /> <type name="ReadObjectInfo" /> <type name="SerializationHeaderRecord" /> <type name="SerObjectInfoCache" /> <type name="SerObjectInfoInit" /> <type name="SerStack" /> <type name="SizedArray" /> <type name="SoapAttributeType" /> <type name="TypeInformation" /> <type name="ValueFixup" /> <type name="ValueFixupEnum" /> <type name="WriteObjectInfo" /> <type name="__BinaryParser" /> <type name="__BinaryWriter" /> </Binary> </Formatters> </Serialization> <Versioning> <type name="ComponentGuaranteesAttribute" /> <type name="ComponentGuaranteesOptions" /> <type name="MultitargetingHelpers" /> <type name="ResourceConsumptionAttribute" /> <type name="ResourceExposureAttribute" /> <type name="ResourceScope" /> <type name="SxSRequirements" /> <type name="TargetFrameworkAttribute" /> <type name="VersioningHelper" /> </Versioning> </Runtime> <Security> <type name="AllowPartiallyTrustedCallersAttribute" /> <type name="BuiltInPermissionSets" /> <type name="CodeAccessPermission" /> <type name="CodeAccessSecurityEngine" /> <type name="DynamicSecurityMethodAttribute" /> <type name="FrameSecurityDescriptor" /> <type name="HostProtectionException" /> <type name="HostSecurityManager" /> <type name="HostSecurityManagerOptions" /> <type name="IEvidenceFactory" /> <type name="IPermission" /> <type name="ISecurityElementFactory" /> <type name="ISecurityEncodable" /> <type name="ISecurityPolicyEncodable" /> <type name="IStackWalk" /> <type name="NamedPermissionSet" /> <type name="PartialTrustVisibilityLevel" /> <type name="PermissionListSet" /> <type name="PermissionSet"> <type name="IsSubsetOfType" /> </type> <type name="PermissionSetEnumerator" /> <type name="PermissionSetEnumeratorInternal" /> <type name="PermissionSetTriple" /> <type name="PermissionToken" /> <type name="PermissionTokenFactory" /> <type name="PermissionTokenKeyComparer" /> <type name="PermissionTokenType" /> <type name="PermissionType" /> <type name="PolicyLevelType" /> <type name="PolicyManager" /> <type name="ReadOnlyPermissionSet" /> <type name="ReadOnlyPermissionSetEnumerator" /> <type name="SafeBSTRHandle" /> <type name="SecureString" /> <type name="SecurityContext"> <type name="SecurityContextRunData" /> </type> <type name="SecurityContextDisableFlow" /> <type name="SecurityContextSource" /> <type name="SecurityContextSwitcher" /> <type name="SecurityCriticalAttribute" /> <type name="SecurityCriticalScope" /> <type name="SecurityDocument" /> <type name="SecurityDocumentElement" /> <type name="SecurityElement" /> <type name="SecurityElementType" /> <type name="SecurityException" /> <type name="SecurityManager" /> <type name="SecurityRulesAttribute" /> <type name="SecurityRuleSet" /> <type name="SecurityRuntime" /> <type name="SecuritySafeCriticalAttribute" /> <type name="SecurityState" /> <type name="SecurityTransparentAttribute" /> <type name="SecurityTreatAsSafeAttribute" /> <type name="SecurityZone" /> <type name="SpecialPermissionSetFlag" /> <type name="SuppressUnmanagedCodeSecurityAttribute" /> <type name="UnverifiableCodeAttribute" /> <type name="VerificationException" /> <type name="WindowsImpersonationFlowMode" /> <type name="XmlSyntaxException" /> <AccessControl> <type name="AccessControlActions" /> <type name="AccessControlModification" /> <type name="AccessControlSections" /> <type name="AccessControlType" /> <type name="AccessRule" /> <type name="AccessRule" arity="1" /> <type name="AceEnumerator" /> <type name="AceFlags" /> <type name="AceQualifier" /> <type name="AceType" /> <type name="AuditFlags" /> <type name="AuditRule" /> <type name="AuditRule" arity="1" /> <type name="AuthorizationRule" /> <type name="AuthorizationRuleCollection" /> <type name="CommonAce" /> <type name="CommonAcl" /> <type name="CommonObjectSecurity" /> <type name="CommonSecurityDescriptor" /> <type name="CompoundAce" /> <type name="CompoundAceType" /> <type name="ControlFlags" /> <type name="CryptoKeyAccessRule" /> <type name="CryptoKeyAuditRule" /> <type name="CryptoKeyRights" /> <type name="CryptoKeySecurity" /> <type name="CustomAce" /> <type name="DirectoryObjectSecurity" /> <type name="DirectorySecurity" /> <type name="DiscretionaryAcl" /> <type name="EventWaitHandleAccessRule" /> <type name="EventWaitHandleAuditRule" /> <type name="EventWaitHandleRights" /> <type name="EventWaitHandleSecurity" /> <type name="FileSecurity" /> <type name="FileSystemAccessRule" /> <type name="FileSystemAuditRule" /> <type name="FileSystemRights" /> <type name="FileSystemSecurity" /> <type name="GenericAce" /> <type name="GenericAcl" /> <type name="GenericSecurityDescriptor" /> <type name="InheritanceFlags" /> <type name="KnownAce" /> <type name="MutexAccessRule" /> <type name="MutexAuditRule" /> <type name="MutexRights" /> <type name="MutexSecurity" /> <type name="NativeObjectSecurity"> <type name="ExceptionFromErrorCode" /> </type> <type name="ObjectAccessRule" /> <type name="ObjectAce" /> <type name="ObjectAceFlags" /> <type name="ObjectAuditRule" /> <type name="ObjectSecurity" /> <type name="ObjectSecurity" arity="1" /> <type name="Privilege" /> <type name="PrivilegeNotHeldException" /> <type name="PropagationFlags" /> <type name="QualifiedAce" /> <type name="RawAcl" /> <type name="RawSecurityDescriptor" /> <type name="RegistryAccessRule" /> <type name="RegistryAuditRule" /> <type name="RegistryRights" /> <type name="RegistrySecurity" /> <type name="ResourceType" /> <type name="SecurityInfos" /> <type name="SystemAcl" /> <type name="Win32" /> </AccessControl> <Cryptography> <type name="Aes" /> <type name="AsymmetricAlgorithm" /> <type name="AsymmetricKeyExchangeDeformatter" /> <type name="AsymmetricKeyExchangeFormatter" /> <type name="AsymmetricSignatureDeformatter" /> <type name="AsymmetricSignatureFormatter" /> <type name="CipherMode" /> <type name="Constants" /> <type name="CryptoAPITransform" /> <type name="CryptoAPITransformMode" /> <type name="CryptoConfig" /> <type name="CryptographicException" /> <type name="CryptographicUnexpectedOperationException" /> <type name="CryptoStream" /> <type name="CryptoStreamMode" /> <type name="CspAlgorithmType" /> <type name="CspKeyContainerInfo" /> <type name="CspParameters" /> <type name="CspProviderFlags" /> <type name="DeriveBytes" /> <type name="DES" /> <type name="DESCryptoServiceProvider" /> <type name="DSA" /> <type name="DSACryptoServiceProvider" /> <type name="DSACspObject" /> <type name="DSAParameters" /> <type name="DSASignatureDeformatter" /> <type name="DSASignatureDescription" /> <type name="DSASignatureFormatter" /> <type name="FromBase64Transform" /> <type name="FromBase64TransformMode" /> <type name="HashAlgorithm" /> <type name="HMAC" /> <type name="HMACMD5" /> <type name="HMACRIPEMD160" /> <type name="HMACSHA1" /> <type name="HMACSHA256" /> <type name="HMACSHA384" /> <type name="HMACSHA512" /> <type name="ICryptoTransform" /> <type name="ICspAsymmetricAlgorithm" /> <type name="KeyedHashAlgorithm" /> <type name="KeyNumber" /> <type name="KeySizes" /> <type name="MACTripleDES" /> <type name="MaskGenerationMethod" /> <type name="MD5" /> <type name="MD5CryptoServiceProvider" /> <type name="PaddingMode" /> <type name="PasswordDeriveBytes" /> <type name="PKCS1MaskGenerationMethod" /> <type name="RandomNumberGenerator" /> <type name="RC2" /> <type name="RC2CryptoServiceProvider" /> <type name="Rfc2898DeriveBytes" /> <type name="Rijndael" /> <type name="RijndaelManaged" /> <type name="RijndaelManagedTransform" /> <type name="RijndaelManagedTransformMode" /> <type name="RIPEMD160" /> <type name="RIPEMD160Managed" /> <type name="RNGCryptoServiceProvider" /> <type name="RSA" /> <type name="RSACryptoServiceProvider" /> <type name="RSACspObject" /> <type name="RSAOAEPKeyExchangeDeformatter" /> <type name="RSAOAEPKeyExchangeFormatter" /> <type name="RSAParameters" /> <type name="RSAPKCS1KeyExchangeDeformatter" /> <type name="RSAPKCS1KeyExchangeFormatter" /> <type name="RSAPKCS1SHA1SignatureDescription" /> <type name="RSAPKCS1SignatureDeformatter" /> <type name="RSAPKCS1SignatureFormatter" /> <type name="SafeHashHandle" /> <type name="SafeKeyHandle" /> <type name="SafeProvHandle" /> <type name="SHA1" /> <type name="SHA1CryptoServiceProvider" /> <type name="SHA1Managed" /> <type name="SHA256" /> <type name="SHA256Managed" /> <type name="SHA384" /> <type name="SHA384Managed" /> <type name="SHA512" /> <type name="SHA512Managed" /> <type name="SignatureDescription" /> <type name="SymmetricAlgorithm" /> <type name="TailStream" /> <type name="ToBase64Transform" /> <type name="TripleDES" /> <type name="TripleDESCryptoServiceProvider" /> <type name="Utils" /> <X509Certificates> <type name="SafeCertContextHandle" /> <type name="SafeCertStoreHandle" /> <type name="X509Certificate" /> <type name="X509Constants" /> <type name="X509ContentType" /> <type name="X509KeyStorageFlags" /> <type name="X509Utils" /> </X509Certificates> </Cryptography> <Permissions> <type name="BuiltInPermissionFlag" /> <type name="BuiltInPermissionIndex" /> <type name="CodeAccessSecurityAttribute" /> <type name="EnvironmentPermission" /> <type name="EnvironmentPermissionAccess" /> <type name="EnvironmentPermissionAttribute" /> <type name="EnvironmentStringExpressionSet" /> <type name="FileDialogPermission" /> <type name="FileDialogPermissionAccess" /> <type name="FileDialogPermissionAttribute" /> <type name="FileIOAccess" /> <type name="FileIOPermission" /> <type name="FileIOPermissionAccess" /> <type name="FileIOPermissionAttribute" /> <type name="GacIdentityPermission" /> <type name="GacIdentityPermissionAttribute" /> <type name="HostProtectionAttribute" /> <type name="HostProtectionPermission" /> <type name="HostProtectionResource" /> <type name="IBuiltInPermission" /> <type name="IDRole" /> <type name="IsolatedStorageContainment" /> <type name="IsolatedStorageFilePermission" /> <type name="IsolatedStorageFilePermissionAttribute" /> <type name="IsolatedStoragePermission" /> <type name="IsolatedStoragePermissionAttribute" /> <type name="IUnrestrictedPermission" /> <type name="KeyContainerPermission" /> <type name="KeyContainerPermissionAccessEntry" /> <type name="KeyContainerPermissionAccessEntryCollection" /> <type name="KeyContainerPermissionAccessEntryEnumerator" /> <type name="KeyContainerPermissionAttribute" /> <type name="KeyContainerPermissionFlags" /> <type name="PermissionSetAttribute" /> <type name="PermissionState" /> <type name="PrincipalPermission" /> <type name="PrincipalPermissionAttribute" /> <type name="PublisherIdentityPermission" /> <type name="PublisherIdentityPermissionAttribute" /> <type name="ReflectionPermission" /> <type name="ReflectionPermissionAttribute" /> <type name="ReflectionPermissionFlag" /> <type name="RegistryPermission" /> <type name="RegistryPermissionAccess" /> <type name="RegistryPermissionAttribute" /> <type name="SecurityAction" /> <type name="SecurityAttribute" /> <type name="SecurityPermission" /> <type name="SecurityPermissionAttribute" /> <type name="SecurityPermissionFlag" /> <type name="SiteIdentityPermission" /> <type name="SiteIdentityPermissionAttribute" /> <type name="StrongName2" /> <type name="StrongNameIdentityPermission" /> <type name="StrongNameIdentityPermissionAttribute" /> <type name="StrongNamePublicKeyBlob" /> <type name="UIPermission" /> <type name="UIPermissionAttribute" /> <type name="UIPermissionClipboard" /> <type name="UIPermissionWindow" /> <type name="UrlIdentityPermission" /> <type name="UrlIdentityPermissionAttribute" /> <type name="ZoneIdentityPermission" /> <type name="ZoneIdentityPermissionAttribute" /> </Permissions> <Policy> <type name="AllMembershipCondition" /> <type name="AppDomainEvidenceFactory" /> <type name="ApplicationDirectory" /> <type name="ApplicationDirectoryMembershipCondition" /> <type name="ApplicationSecurityInfo" /> <type name="ApplicationSecurityManager" /> <type name="ApplicationTrust" /> <type name="ApplicationTrustCollection" /> <type name="ApplicationTrustEnumerator" /> <type name="ApplicationVersionMatch" /> <type name="AssemblyEvidenceFactory" /> <type name="CodeConnectAccess" /> <type name="CodeGroup" /> <type name="CodeGroupPositionMarker" /> <type name="CodeGroupStack" /> <type name="CodeGroupStackFrame" /> <type name="ConfigId" /> <type name="Evidence"> <type name="RawEvidenceEnumerator" /> </type> <type name="EvidenceBase" /> <type name="EvidenceTypeDescriptor" /> <type name="EvidenceTypeGenerated" /> <type name="FileCodeGroup" /> <type name="FirstMatchCodeGroup" /> <type name="GacInstalled" /> <type name="GacMembershipCondition" /> <type name="Hash" /> <type name="HashMembershipCondition" /> <type name="IApplicationTrustManager" /> <type name="IConstantMembershipCondition" /> <type name="IDelayEvaluatedEvidence" /> <type name="IIdentityPermissionFactory" /> <type name="ILegacyEvidenceAdapter" /> <type name="IMembershipCondition" /> <type name="IReportMatchMembershipCondition" /> <type name="IRuntimeEvidenceFactory" /> <type name="IUnionSemanticCodeGroup" /> <type name="LegacyEvidenceList" /> <type name="LegacyEvidenceWrapper" /> <type name="NetCodeGroup" /> <type name="PEFileEvidenceFactory" /> <type name="PermissionRequestEvidence" /> <type name="PolicyException" /> <type name="PolicyLevel" /> <type name="PolicyStatement" /> <type name="PolicyStatementAttribute" /> <type name="Publisher" /> <type name="PublisherMembershipCondition" /> <type name="Site" /> <type name="SiteMembershipCondition" /> <type name="StrongName" /> <type name="StrongNameMembershipCondition" /> <type name="TrustManagerContext" /> <type name="TrustManagerUIContext" /> <type name="UnionCodeGroup" /> <type name="Url" /> <type name="UrlMembershipCondition" /> <type name="Zone" /> <type name="ZoneMembershipCondition" /> </Policy> <Principal> <type name="GenericIdentity" /> <type name="GenericPrincipal" /> <type name="IdentifierAuthority" /> <type name="IdentityNotMappedException" /> <type name="IdentityReference" /> <type name="IdentityReferenceCollection" /> <type name="IdentityReferenceEnumerator" /> <type name="IIdentity" /> <type name="ImpersonationQueryResult" /> <type name="IPrincipal" /> <type name="KerbLogonSubmitType" /> <type name="NTAccount" /> <type name="PolicyRights" /> <type name="PrincipalPolicy" /> <type name="SecurityIdentifier" /> <type name="SecurityLogonType" /> <type name="SidNameUse" /> <type name="TokenAccessLevels" /> <type name="TokenImpersonationLevel" /> <type name="TokenInformationClass" /> <type name="TokenType" /> <type name="WellKnownSidType" /> <type name="Win32" /> <type name="WindowsAccountType" /> <type name="WindowsBuiltInRole" /> <type name="WindowsIdentity" /> <type name="WindowsImpersonationContext" /> <type name="WindowsPrincipal" /> <type name="WinSecurityContext" /> </Principal> <Util> <type name="Config" /> <type name="DirectoryString" /> <type name="Hex" /> <type name="LocalSiteString" /> <type name="Parser" /> <type name="QuickCacheEntryType" /> <type name="SiteString" /> <type name="StringExpressionSet" /> <type name="TokenBasedSet" /> <type name="TokenBasedSetEnumerator" /> <type name="Tokenizer"> <type name="ByteTokenEncoding" /> <type name="ITokenReader" /> <type name="StreamTokenReader" /> <type name="StringMaker" /> </type> <type name="TokenizerShortBlock" /> <type name="TokenizerStream" /> <type name="TokenizerStringBlock" /> <type name="URLString" /> <type name="XMLUtil" /> </Util> </Security> <StubHelpers> <type name="AnsiBSTRMarshaler" /> <type name="AnsiCharMarshaler" /> <type name="AsAnyMarshaler"> <type name="BackPropAction" /> </type> <type name="BSTRMarshaler" /> <type name="CleanupWorkList" /> <type name="CleanupWorkListElement" /> <type name="CopyCtorStubCookie" /> <type name="CopyCtorStubDesc" /> <type name="CSTRMarshaler" /> <type name="DateMarshaler" /> <type name="InterfaceMarshaler" /> <type name="MngdNativeArrayMarshaler" /> <type name="MngdRefCustomMarshaler" /> <type name="MngdSafeArrayMarshaler" /> <type name="NativeVariant" /> <type name="ObjectMarshaler" /> <type name="StubHelpers" /> <type name="ValueClassMarshaler" /> <type name="VBByValStrMarshaler" /> <type name="WSTRBufferMarshaler" /> </StubHelpers> <Text> <type name="ASCIIEncoding" /> <type name="BaseCodePageEncoding"> <type name="CodePageDataFileHeader" /> <type name="CodePageHeader" /> <type name="CodePageIndex" /> </type> <type name="CodePageEncoding"> <type name="Decoder" /> </type> <type name="DBCSCodePageEncoding"> <type name="DBCSDecoder" /> </type> <type name="Decoder" /> <type name="DecoderExceptionFallback" /> <type name="DecoderExceptionFallbackBuffer" /> <type name="DecoderFallback" /> <type name="DecoderFallbackBuffer" /> <type name="DecoderFallbackException" /> <type name="DecoderNLS" /> <type name="DecoderReplacementFallback" /> <type name="DecoderReplacementFallbackBuffer" /> <type name="Encoder" /> <type name="EncoderExceptionFallback" /> <type name="EncoderExceptionFallbackBuffer" /> <type name="EncoderFallback" /> <type name="EncoderFallbackBuffer" /> <type name="EncoderFallbackException" /> <type name="EncoderNLS" /> <type name="EncoderReplacementFallback" /> <type name="EncoderReplacementFallbackBuffer" /> <type name="Encoding"> <type name="DefaultDecoder" /> <type name="DefaultEncoder" /> <type name="EncodingByteBuffer" /> <type name="EncodingCharBuffer" /> </type> <type name="EncodingInfo" /> <type name="EncodingNLS" /> <type name="EUCJPEncoding" /> <type name="ExtendedNormalizationForms" /> <type name="GB18030Encoding"> <type name="GB18030Decoder" /> </type> <type name="InternalDecoderBestFitFallback" /> <type name="InternalDecoderBestFitFallbackBuffer" /> <type name="InternalEncoderBestFitFallback" /> <type name="InternalEncoderBestFitFallbackBuffer" /> <type name="ISCIIEncoding"> <type name="ISCIIDecoder" /> <type name="ISCIIEncoder" /> </type> <type name="ISO2022Encoding"> <type name="ISO2022Decoder" /> <type name="ISO2022Encoder" /> <type name="ISO2022Modes" /> </type> <type name="Latin1Encoding" /> <type name="MLangCodePageEncoding"> <type name="MLangDecoder" /> <type name="MLangEncoder" /> </type> <type name="Normalization" /> <type name="NormalizationForm" /> <type name="SBCSCodePageEncoding" /> <type name="StringBuilder" /> <type name="SurrogateEncoder" /> <type name="UnicodeEncoding" /> <type name="UTF32Encoding"> <type name="UTF32Decoder" /> </type> <type name="UTF7Encoding"> <type name="DecoderUTF7Fallback" /> <type name="DecoderUTF7FallbackBuffer" /> </type> <type name="UTF8Encoding"> <type name="UTF8Decoder" /> <type name="UTF8Encoder" /> </type> </Text> <Threading> <type name="AbandonedMutexException" /> <type name="ApartmentState" /> <type name="AsyncFlowControl" /> <type name="AutoResetEvent" /> <type name="CancellationCallbackCoreWorkArguments" /> <type name="CancellationCallbackInfo" /> <type name="CancellationToken" /> <type name="CancellationTokenRegistration" /> <type name="CancellationTokenSource" /> <type name="CdsSyncEtwBCLProvider" /> <type name="CompressedStack"> <type name="CompressedStackRunData" /> </type> <type name="CompressedStackSwitcher" /> <type name="ContextCallback" /> <type name="CountdownEvent" /> <type name="DomainCompressedStack" /> <type name="EventResetMode" /> <type name="EventWaitHandle" /> <type name="ExceptionType" /> <type name="ExecutionContext"> <type name="CaptureOptions" /> <type name="ExecutionContextRunData" /> </type> <type name="ExecutionContextSwitcher" /> <type name="HostExecutionContext" /> <type name="HostExecutionContextManager" /> <type name="HostExecutionContextSwitcher" /> <type name="Interlocked" /> <type name="InternalCrossContextDelegate" /> <type name="IOCompletionCallback" /> <type name="IThreadPoolWorkItem" /> <type name="IUnknownSafeHandle" /> <type name="LazyInitializer" /> <type name="LazyThreadSafetyMode" /> <type name="LockCookie" /> <type name="LockRecursionException" /> <type name="ManualResetEvent" /> <type name="ManualResetEventSlim" /> <type name="Monitor" /> <type name="Mutex"> <type name="MutexCleanupInfo" /> <type name="MutexTryCodeHelper" /> </type> <type name="NativeOverlapped" /> <type name="Overlapped" /> <type name="OverlappedData" /> <type name="OverlappedDataCache" /> <type name="OverlappedDataCacheLine" /> <type name="ParameterizedThreadStart" /> <type name="PlatformHelper" /> <type name="QueueUserWorkItemCallback" /> <type name="ReaderWriterLock" /> <type name="RegisteredWaitHandle" /> <type name="RegisteredWaitHandleSafe" /> <type name="SafeCompressedStackHandle" /> <type name="SemaphoreFullException" /> <type name="SemaphoreSlim" /> <type name="SendOrPostCallback" /> <type name="SparselyPopulatedArray" arity="1" /> <type name="SparselyPopulatedArrayAddInfo" arity="1" /> <type name="SparselyPopulatedArrayFragment" arity="1" /> <type name="SpinLock"> <type name="SystemThreading_SpinLockDebugView" /> </type> <type name="SpinWait" /> <type name="StackCrawlMark" /> <type name="SynchronizationContext" /> <type name="SynchronizationContextProperties" /> <type name="SynchronizationContextSwitcher" /> <type name="SynchronizationLockException" /> <type name="SystemThreading_ThreadLocalDebugView" arity="1" /> <type name="Thread" /> <type name="ThreadAbortException" /> <type name="ThreadHandle" /> <type name="ThreadHelper" /> <type name="ThreadInterruptedException" /> <type name="ThreadLocal" arity="1" /> <type name="ThreadLocalGlobalCounter" /> <type name="ThreadPool" /> <type name="ThreadPoolGlobals" /> <type name="ThreadPoolRequestQueue" /> <type name="ThreadPoolWorkQueue"> <type name="QueueSegment" /> <type name="SparseArray" arity="1" /> <type name="WorkStealingQueue" /> </type> <type name="ThreadPoolWorkQueueThreadLocals" /> <type name="ThreadPriority" /> <type name="ThreadStart" /> <type name="ThreadStartException" /> <type name="ThreadState" /> <type name="ThreadStateException" /> <type name="Timeout" /> <type name="Timer" /> <type name="TimerBase" /> <type name="TimerCallback" /> <type name="TplEtwProvider"> <type name="ForkJoinOperationType" /> </type> <type name="WaitCallback" /> <type name="WaitDelegate" /> <type name="WaitHandle" /> <type name="WaitHandleCannotBeOpenedException" /> <type name="WaitOrTimerCallback" /> <type name="_IOCompletionCallback" /> <type name="_ThreadPoolWaitCallback" /> <type name="_ThreadPoolWaitOrTimerCallback" /> <type name="_TimerCallback" /> <Tasks> <type name="IndexRange" /> <type name="InternalTaskOptions" /> <type name="Parallel"> <type name="LoopTimer" /> </type> <type name="ParallelForReplicaTask" /> <type name="ParallelForReplicatingTask" /> <type name="ParallelLoopResult" /> <type name="ParallelLoopState" /> <type name="ParallelLoopState32" /> <type name="ParallelLoopState64" /> <type name="ParallelLoopStateFlags" /> <type name="ParallelLoopStateFlags32" /> <type name="ParallelLoopStateFlags64" /> <type name="ParallelOptions" /> <type name="RangeManager" /> <type name="RangeWorker" /> <type name="Shared" arity="1" /> <type name="StackGuard" /> <type name="SynchronizationContextTaskScheduler" /> <type name="SystemThreadingTasks_FutureDebugView" arity="1" /> <type name="SystemThreadingTasks_TaskDebugView" /> <type name="Task"> <type name="ContingentProperties" /> <type name="TaskContinuation" /> </type> <type name="Task" arity="1" /> <type name="TaskCanceledException" /> <type name="TaskCompletionSource" arity="1" /> <type name="TaskContinuationOptions" /> <type name="TaskCreationOptions" /> <type name="TaskExceptionHolder" /> <type name="TaskFactory" /> <type name="TaskFactory" arity="1" /> <type name="TaskScheduler"> <type name="SystemThreadingTasks_TaskSchedulerDebugView" /> </type> <type name="TaskSchedulerException" /> <type name="TaskStatus" /> <type name="ThreadPoolTaskScheduler" /> <type name="UnobservedTaskExceptionEventArgs" /> </Tasks> </Threading> </System> </Global>
<Global> <type name="&lt;Module&gt;" /> <type name="&lt;PrivateImplementationDetails&gt;{E929D9EA-3268-462F-B826-5115530AD12B}"> <type name="__StaticArrayInitTypeSize=10" /> <type name="__StaticArrayInitTypeSize=120" /> <type name="__StaticArrayInitTypeSize=1208" /> <type name="__StaticArrayInitTypeSize=126" /> <type name="__StaticArrayInitTypeSize=128" /> <type name="__StaticArrayInitTypeSize=130" /> <type name="__StaticArrayInitTypeSize=132" /> <type name="__StaticArrayInitTypeSize=14" /> <type name="__StaticArrayInitTypeSize=1440" /> <type name="__StaticArrayInitTypeSize=16" /> <type name="__StaticArrayInitTypeSize=18128" /> <type name="__StaticArrayInitTypeSize=2224" /> <type name="__StaticArrayInitTypeSize=24" /> <type name="__StaticArrayInitTypeSize=256" /> <type name="__StaticArrayInitTypeSize=28" /> <type name="__StaticArrayInitTypeSize=288" /> <type name="__StaticArrayInitTypeSize=3" /> <type name="__StaticArrayInitTypeSize=3200" /> <type name="__StaticArrayInitTypeSize=3456" /> <type name="__StaticArrayInitTypeSize=38" /> <type name="__StaticArrayInitTypeSize=392" /> <type name="__StaticArrayInitTypeSize=40" /> <type name="__StaticArrayInitTypeSize=4096" /> <type name="__StaticArrayInitTypeSize=440" /> <type name="__StaticArrayInitTypeSize=4540" /> <type name="__StaticArrayInitTypeSize=48" /> <type name="__StaticArrayInitTypeSize=52" /> <type name="__StaticArrayInitTypeSize=5264" /> <type name="__StaticArrayInitTypeSize=6" /> <type name="__StaticArrayInitTypeSize=64" /> <type name="__StaticArrayInitTypeSize=640" /> <type name="__StaticArrayInitTypeSize=72" /> <type name="__StaticArrayInitTypeSize=82" /> <type name="__StaticArrayInitTypeSize=84" /> <type name="__StaticArrayInitTypeSize=878" /> </type> <type name="AssemblyRef" /> <type name="FXAssembly" /> <type name="SRETW" /> <type name="ThisAssembly" /> <Microsoft> <Runtime> <Hosting> <type name="IClrStrongName" /> <type name="IClrStrongNameUsingIntPtr" /> <type name="StrongNameHelpers" /> </Hosting> </Runtime> <Win32> <type name="ASM_CACHE" /> <type name="ASM_NAME" /> <type name="CANOF" /> <type name="Fusion" /> <type name="IApplicationContext" /> <type name="IAssemblyEnum" /> <type name="IAssemblyName" /> <type name="OAVariantLib" /> <type name="Registry" /> <type name="RegistryHive" /> <type name="RegistryKey" /> <type name="RegistryKeyPermissionCheck" /> <type name="RegistryOptions" /> <type name="RegistryValueKind" /> <type name="RegistryValueOptions" /> <type name="RegistryView" /> <type name="SafeLibraryHandle" /> <type name="UnsafeNativeMethods"> <type name="EtwEnableCallback" /> <type name="EVENT_FILTER_DESCRIPTOR" /> </type> <type name="Win32Native"> <type name="CHAR_INFO" /> <type name="Color" /> <type name="ConsoleCtrlHandlerRoutine" /> <type name="CONSOLE_CURSOR_INFO" /> <type name="CONSOLE_SCREEN_BUFFER_INFO" /> <type name="COORD" /> <type name="DynamicTimeZoneInformation" /> <type name="FILE_TIME" /> <type name="InputRecord" /> <type name="KERB_S4U_LOGON" /> <type name="KeyEventRecord" /> <type name="LSA_OBJECT_ATTRIBUTES" /> <type name="LSA_REFERENCED_DOMAIN_LIST" /> <type name="LSA_TRANSLATED_NAME" /> <type name="LSA_TRANSLATED_SID" /> <type name="LSA_TRANSLATED_SID2" /> <type name="LSA_TRUST_INFORMATION" /> <type name="LUID" /> <type name="LUID_AND_ATTRIBUTES" /> <type name="MEMORYSTATUSEX" /> <type name="MEMORY_BASIC_INFORMATION" /> <type name="OSVERSIONINFO" /> <type name="OSVERSIONINFOEX" /> <type name="QUOTA_LIMITS" /> <type name="RegistryTimeZoneInformation" /> <type name="SECURITY_ATTRIBUTES" /> <type name="SECURITY_IMPERSONATION_LEVEL" /> <type name="SECURITY_LOGON_SESSION_DATA" /> <type name="SID_AND_ATTRIBUTES" /> <type name="SMALL_RECT" /> <type name="SystemTime" /> <type name="SYSTEM_INFO" /> <type name="TimeZoneInformation" /> <type name="TOKEN_GROUPS" /> <type name="TOKEN_PRIVILEGE" /> <type name="TOKEN_SOURCE" /> <type name="TOKEN_STATISTICS" /> <type name="TOKEN_USER" /> <type name="UNICODE_INTPTR_STRING" /> <type name="UNICODE_STRING" /> <type name="USEROBJECTFLAGS" /> <type name="WIN32_FILE_ATTRIBUTE_DATA" /> <type name="WIN32_FIND_DATA" /> </type> <SafeHandles> <type name="CriticalHandleMinusOneIsInvalid" /> <type name="CriticalHandleZeroOrMinusOneIsInvalid" /> <type name="SafeFileHandle" /> <type name="SafeFileMappingHandle" /> <type name="SafeFindHandle" /> <type name="SafeHandleMinusOneIsInvalid" /> <type name="SafeHandleZeroOrMinusOneIsInvalid" /> <type name="SafeLocalAllocHandle" /> <type name="SafeLsaLogonProcessHandle" /> <type name="SafeLsaMemoryHandle" /> <type name="SafeLsaPolicyHandle" /> <type name="SafeLsaReturnBufferHandle" /> <type name="SafePEFileHandle" /> <type name="SafeProcessHandle" /> <type name="SafeRegistryHandle" /> <type name="SafeThreadHandle" /> <type name="SafeTokenHandle" /> <type name="SafeViewOfFileHandle" /> <type name="SafeWaitHandle" /> </SafeHandles> </Win32> </Microsoft> <System> <type name="AccessViolationException" /> <type name="Action" /> <type name="Action" arity="1" /> <type name="Action" arity="2" /> <type name="Action" arity="3" /> <type name="Action" arity="4" /> <type name="Action" arity="5" /> <type name="Action" arity="6" /> <type name="Action" arity="7" /> <type name="Action" arity="8" /> <type name="ActivationContext"> <type name="ApplicationState" /> <type name="ApplicationStateDisposition" /> <type name="ContextForm" /> </type> <type name="Activator" /> <type name="AggregateException" /> <type name="AppDomain" /> <type name="AppDomainHandle" /> <type name="AppDomainInitializer" /> <type name="AppDomainInitializerInfo"> <type name="ItemInfo" /> </type> <type name="AppDomainManager" /> <type name="AppDomainManagerInitializationOptions" /> <type name="AppDomainSetup"> <type name="LoaderInformation" /> </type> <type name="AppDomainUnloadedException" /> <type name="ApplicationException" /> <type name="ApplicationId" /> <type name="ApplicationIdentity" /> <type name="ArgIterator" /> <type name="ArgumentException" /> <type name="ArgumentNullException" /> <type name="ArgumentOutOfRangeException" /> <type name="ArithmeticException" /> <type name="Array"> <type name="FunctorComparer" arity="1" /> </type> <type name="ArraySegment" arity="1" /> <type name="ArrayTypeMismatchException" /> <type name="AssemblyLoadEventArgs" /> <type name="AssemblyLoadEventHandler" /> <type name="AsyncCallback" /> <type name="Attribute" /> <type name="AttributeTargets" /> <type name="AttributeUsageAttribute" /> <type name="BadImageFormatException" /> <type name="Base64FormattingOptions" /> <type name="BaseConfigHandler" /> <type name="BCLDebug" /> <type name="BitConverter" /> <type name="Boolean" /> <type name="Buffer" /> <type name="Byte" /> <type name="CannotUnloadAppDomainException" /> <type name="Char" /> <type name="CharEnumerator" /> <type name="CLSCompliantAttribute" /> <type name="Comparison" arity="1" /> <type name="CompatibilityFlag" /> <type name="ConfigEvents" /> <type name="ConfigNode" /> <type name="ConfigNodeSubType" /> <type name="ConfigNodeType" /> <type name="ConfigServer" /> <type name="ConfigTreeParser" /> <type name="Console"> <type name="ControlCHooker" /> <type name="ControlKeyState" /> </type> <type name="ConsoleCancelEventArgs" /> <type name="ConsoleCancelEventHandler" /> <type name="ConsoleColor" /> <type name="ConsoleKey" /> <type name="ConsoleKeyInfo" /> <type name="ConsoleModifiers" /> <type name="ConsoleSpecialKey" /> <type name="ContextBoundObject" /> <type name="ContextMarshalException" /> <type name="ContextStaticAttribute" /> <type name="Convert" /> <type name="Converter" arity="2" /> <type name="CrossAppDomainDelegate" /> <type name="CtorDelegate" /> <type name="CultureAwareComparer" /> <type name="Currency" /> <type name="CurrentSystemTimeZone" /> <type name="DataMisalignedException" /> <type name="DateTime" /> <type name="DateTimeFormat" /> <type name="DateTimeKind" /> <type name="DateTimeOffset" /> <type name="DateTimeParse"> <type name="DS" /> <type name="DTT" /> <type name="MatchNumberDelegate" /> <type name="TM" /> </type> <type name="DateTimeRawInfo" /> <type name="DateTimeResult" /> <type name="DateTimeToken" /> <type name="DayOfWeek" /> <type name="DBNull" /> <type name="Decimal" /> <type name="DefaultBinder"> <type name="BinderState" /> </type> <type name="Delegate" /> <type name="DelegateBindingFlags" /> <type name="DelegateSerializationHolder"> <type name="DelegateEntry" /> </type> <type name="DivideByZeroException" /> <type name="DllNotFoundException" /> <type name="Double" /> <type name="DTSubString" /> <type name="DTSubStringType" /> <type name="DuplicateWaitObjectException" /> <type name="Empty" /> <type name="EntryPointNotFoundException" /> <type name="Enum" /> <type name="Environment"> <type name="OSName" /> <type name="ResourceHelper"> <type name="GetResourceStringUserData" /> </type> <type name="SpecialFolder" /> <type name="SpecialFolderOption" /> </type> <type name="EnvironmentVariableTarget" /> <type name="EventArgs" /> <type name="EventHandler" /> <type name="EventHandler" arity="1" /> <type name="Exception"> <type name="ExceptionMessageKind" /> </type> <type name="ExceptionArgument" /> <type name="ExceptionResource" /> <type name="ExecutionEngineException" /> <type name="FieldAccessException" /> <type name="FlagsAttribute" /> <type name="FormatException" /> <type name="Func" arity="1" /> <type name="Func" arity="2" /> <type name="Func" arity="3" /> <type name="Func" arity="4" /> <type name="Func" arity="5" /> <type name="Func" arity="6" /> <type name="Func" arity="7" /> <type name="Func" arity="8" /> <type name="Func" arity="9" /> <type name="GC" /> <type name="GCCollectionMode" /> <type name="GCNotificationStatus" /> <type name="Guid" /> <type name="IAppDomainSetup" /> <type name="IAsyncResult" /> <type name="ICloneable" /> <type name="IComparable" /> <type name="IComparable" arity="1" /> <type name="IConfigHandler" /> <type name="IConvertible" /> <type name="IConvertibleContract" /> <type name="ICustomFormatter" /> <type name="IDisposable" /> <type name="IEquatable" arity="1" /> <type name="IFormatProvider" /> <type name="IFormattable" /> <type name="IFormattableContract" /> <type name="IndexOutOfRangeException" /> <type name="InsufficientExecutionStackException" /> <type name="InsufficientMemoryException" /> <type name="Int16" /> <type name="Int32" /> <type name="Int64" /> <type name="Internal" /> <type name="IntPtr" /> <type name="InvalidCastException" /> <type name="InvalidOperationException" /> <type name="InvalidProgramException" /> <type name="InvalidTimeZoneException" /> <type name="IObservable" arity="1" /> <type name="IObserver" arity="1" /> <type name="IRuntimeFieldInfo" /> <type name="IRuntimeMethodInfo" /> <type name="IServiceProvider" /> <type name="ITuple" /> <type name="Lazy" arity="1" /> <type name="LoaderOptimization" /> <type name="LoaderOptimizationAttribute" /> <type name="LocalDataStore" /> <type name="LocalDataStoreElement" /> <type name="LocalDataStoreHolder" /> <type name="LocalDataStoreMgr" /> <type name="LocalDataStoreSlot" /> <type name="LogLevel" /> <type name="MarshalByRefObject" /> <type name="Math" /> <type name="Mda"> <type name="StreamWriterBufferedDataLost" /> </type> <type name="MemberAccessException" /> <type name="MethodAccessException" /> <type name="MidpointRounding" /> <type name="MissingFieldException" /> <type name="MissingMemberException" /> <type name="MissingMethodException" /> <type name="ModuleHandle" /> <type name="MTAThreadAttribute" /> <type name="MulticastDelegate" /> <type name="MulticastNotSupportedException" /> <type name="NonSerializedAttribute" /> <type name="NotFiniteNumberException" /> <type name="NotImplementedException" /> <type name="NotSupportedException" /> <type name="Nullable" /> <type name="Nullable" arity="1" /> <type name="NullReferenceException" /> <type name="Number"> <type name="NumberBuffer" /> </type> <type name="Object" /> <type name="ObjectDisposedException" /> <type name="ObsoleteAttribute" /> <type name="OleAutBinder" /> <type name="OperatingSystem" /> <type name="OperationCanceledException" /> <type name="OrdinalComparer" /> <type name="OutOfMemoryException" /> <type name="OverflowException" /> <type name="ParamArrayAttribute" /> <type name="ParseFailureKind" /> <type name="ParseFlags" /> <type name="ParseNumbers" /> <type name="ParsingInfo" /> <type name="PlatformID" /> <type name="PlatformNotSupportedException" /> <type name="Predicate" arity="1" /> <type name="Random" /> <type name="RankException" /> <type name="ReflectionOnlyType" /> <type name="ResId" /> <type name="ResolveEventArgs" /> <type name="ResolveEventHandler" /> <type name="Resolver"> <type name="CORINFO_EH_CLAUSE" /> </type> <type name="RuntimeArgumentHandle" /> <type name="RuntimeFieldHandle" /> <type name="RuntimeFieldHandleInternal" /> <type name="RuntimeFieldInfoStub" /> <type name="RuntimeMethodHandle" /> <type name="RuntimeMethodHandleInternal" /> <type name="RuntimeMethodInfoStub" /> <type name="RuntimeType"> <type name="RuntimeTypeCache"> <type name="CacheType" /> <type name="WhatsCached" /> </type> </type> <type name="RuntimeTypeHandle"> <type name="IntroducedMethodEnumerator" /> </type> <type name="SafeTypeNameParserHandle" /> <type name="SByte" /> <type name="SerializableAttribute" /> <type name="SharedStatics" /> <type name="Signature"> <type name="MdSigCallingConvention" /> </type> <type name="SignatureStruct" /> <type name="Single" /> <type name="SizedReference" /> <type name="StackOverflowException" /> <type name="STAThreadAttribute" /> <type name="String" /> <type name="StringComparer" /> <type name="StringComparison" /> <type name="StringSplitOptions" /> <type name="SwitchStructure" /> <type name="SystemException" /> <type name="System_LazyDebugView" arity="1" /> <type name="SZArrayHelper" /> <type name="ThreadStaticAttribute" /> <type name="ThrowHelper" /> <type name="TimeoutException" /> <type name="TimeSpan" /> <type name="TimeZone" /> <type name="TimeZoneInfo"> <type name="AdjustmentRule" /> <type name="TransitionTime" /> </type> <type name="TimeZoneInfoOptions" /> <type name="TimeZoneNotFoundException" /> <type name="TokenType" /> <type name="Tuple" /> <type name="Tuple" arity="1" /> <type name="Tuple" arity="2" /> <type name="Tuple" arity="3" /> <type name="Tuple" arity="4" /> <type name="Tuple" arity="5" /> <type name="Tuple" arity="6" /> <type name="Tuple" arity="7" /> <type name="Tuple" arity="8" /> <type name="Type" /> <type name="TypeAccessException" /> <type name="TypeCode" /> <type name="TypeContracts" /> <type name="TypedReference" /> <type name="TypeInitializationException" /> <type name="TypeLoadException" /> <type name="TypeNameParser" /> <type name="TypeUnloadedException" /> <type name="UInt16" /> <type name="UInt32" /> <type name="UInt64" /> <type name="UIntPtr" /> <type name="UnauthorizedAccessException" /> <type name="UnhandledExceptionEventArgs" /> <type name="UnhandledExceptionEventHandler" /> <type name="UnitySerializationHolder" /> <type name="UnSafeCharBuffer" /> <type name="Utf8String" /> <type name="ValueType" /> <type name="Variant" /> <type name="Version"> <type name="ParseFailureKind" /> <type name="VersionResult" /> </type> <type name="Void" /> <type name="WeakReference" /> <type name="XmlIgnoreMemberAttribute" /> <type name="_AppDomain" /> <type name="__Canon" /> <type name="__ComObject" /> <type name="__DTString" /> <type name="__Filters" /> <type name="__HResults" /> <Collections> <type name="ArrayList"> <type name="ArrayListDebugView" /> </type> <type name="BitArray" /> <type name="CaseInsensitiveComparer" /> <type name="CaseInsensitiveHashCodeProvider" /> <type name="CollectionBase" /> <type name="Comparer" /> <type name="CompatibleComparer" /> <type name="DictionaryBase" /> <type name="DictionaryEntry" /> <type name="EmptyReadOnlyDictionaryInternal" /> <type name="HashHelpers" /> <type name="Hashtable"> <type name="HashtableDebugView" /> </type> <type name="ICollection" /> <type name="ICollectionContract" /> <type name="IComparer" /> <type name="IDictionary" /> <type name="IDictionaryContract" /> <type name="IDictionaryEnumerator" /> <type name="IEnumerable" /> <type name="IEnumerableContract" /> <type name="IEnumerator" /> <type name="IEqualityComparer" /> <type name="IHashCodeProvider" /> <type name="IList" /> <type name="IListContract" /> <type name="IStructuralComparable" /> <type name="IStructuralEquatable" /> <type name="KeyValuePairs" /> <type name="ListDictionaryInternal" /> <type name="Queue"> <type name="QueueDebugView" /> </type> <type name="ReadOnlyCollectionBase" /> <type name="SortedList"> <type name="SortedListDebugView" /> </type> <type name="Stack"> <type name="StackDebugView" /> </type> <type name="StructuralComparer" /> <type name="StructuralComparisons" /> <type name="StructuralEqualityComparer" /> <Concurrent> <type name="CDSCollectionETWBCLProvider" /> <type name="ConcurrentDictionary" arity="2" /> <type name="ConcurrentQueue" arity="1" /> <type name="ConcurrentStack" arity="1" /> <type name="IProducerConsumerCollection" arity="1" /> <type name="OrderablePartitioner" arity="1" /> <type name="Partitioner" /> <type name="Partitioner" arity="1" /> <type name="SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView" arity="1" /> </Concurrent> <Generic> <type name="ArraySortHelper" arity="1" /> <type name="ArraySortHelper" arity="2" /> <type name="ByteEqualityComparer" /> <type name="Comparer" arity="1" /> <type name="Dictionary" arity="2"> <type name="Enumerator" /> <type name="KeyCollection"> <type name="Enumerator" /> </type> <type name="ValueCollection"> <type name="Enumerator" /> </type> </type> <type name="EnumEqualityComparer" arity="1" /> <type name="EqualityComparer" arity="1" /> <type name="GenericArraySortHelper" arity="1" /> <type name="GenericArraySortHelper" arity="2" /> <type name="GenericComparer" arity="1" /> <type name="GenericEqualityComparer" arity="1" /> <type name="IArraySortHelper" arity="1" /> <type name="IArraySortHelper" arity="2" /> <type name="IArraySortHelperContract" arity="1" /> <type name="ICollection" arity="1" /> <type name="ICollectionContract" arity="1" /> <type name="IComparer" arity="1" /> <type name="IDictionary" arity="2" /> <type name="IDictionaryContract" arity="2" /> <type name="IEnumerable" arity="1" /> <type name="IEnumerableContract" arity="1" /> <type name="IEnumerator" arity="1" /> <type name="IEqualityComparer" arity="1" /> <type name="IList" arity="1" /> <type name="IListContract" arity="1" /> <type name="KeyNotFoundException" /> <type name="KeyValuePair" arity="2" /> <type name="List" arity="1"> <type name="Enumerator" /> <type name="SynchronizedList" /> </type> <type name="Mscorlib_CollectionDebugView" arity="1" /> <type name="Mscorlib_DictionaryDebugView" arity="2" /> <type name="Mscorlib_DictionaryKeyCollectionDebugView" arity="2" /> <type name="Mscorlib_DictionaryValueCollectionDebugView" arity="2" /> <type name="Mscorlib_KeyedCollectionDebugView" arity="2" /> <type name="NullableComparer" arity="1" /> <type name="NullableEqualityComparer" arity="1" /> <type name="ObjectComparer" arity="1" /> <type name="ObjectEqualityComparer" arity="1" /> </Generic> <ObjectModel> <type name="Collection" arity="1" /> <type name="KeyedCollection" arity="2" /> <type name="ReadOnlyCollection" arity="1" /> </ObjectModel> </Collections> <Configuration> <Assemblies> <type name="AssemblyHash" /> <type name="AssemblyHashAlgorithm" /> <type name="AssemblyVersionCompatibility" /> </Assemblies> </Configuration> <Deployment> <Internal> <type name="InternalActivationContextHelper" /> <type name="InternalApplicationIdentityHelper" /> <Isolation> <type name="BLOB" /> <type name="CATEGORY" /> <type name="CATEGORY_INSTANCE" /> <type name="CATEGORY_SUBCATEGORY" /> <type name="IActContext" /> <type name="IAppIdAuthority" /> <type name="IAPPIDAUTHORITY_ARE_DEFINITIONS_EQUAL_FLAGS" /> <type name="IAPPIDAUTHORITY_ARE_REFERENCES_EQUAL_FLAGS" /> <type name="ICDF" /> <type name="IDefinitionAppId" /> <type name="IDefinitionIdentity" /> <type name="IDENTITY_ATTRIBUTE" /> <type name="IEnumDefinitionIdentity" /> <type name="IEnumIDENTITY_ATTRIBUTE" /> <type name="IEnumReferenceIdentity" /> <type name="IEnumSTORE_ASSEMBLY" /> <type name="IEnumSTORE_ASSEMBLY_FILE" /> <type name="IEnumSTORE_ASSEMBLY_INSTALLATION_REFERENCE" /> <type name="IEnumSTORE_CATEGORY" /> <type name="IEnumSTORE_CATEGORY_INSTANCE" /> <type name="IEnumSTORE_CATEGORY_SUBCATEGORY" /> <type name="IEnumSTORE_DEPLOYMENT_METADATA" /> <type name="IEnumSTORE_DEPLOYMENT_METADATA_PROPERTY" /> <type name="IEnumUnknown" /> <type name="IIdentityAuthority" /> <type name="IIDENTITYAUTHORITY_DEFINITION_IDENTITY_TO_TEXT_FLAGS" /> <type name="IIDENTITYAUTHORITY_DOES_DEFINITION_MATCH_REFERENCE_FLAGS" /> <type name="IIDENTITYAUTHORITY_REFERENCE_IDENTITY_TO_TEXT_FLAGS" /> <type name="IManifestInformation" /> <type name="IManifestParseErrorCallback" /> <type name="IReferenceAppId" /> <type name="IReferenceIdentity" /> <type name="ISection" /> <type name="ISectionEntry" /> <type name="ISectionWithReferenceIdentityKey" /> <type name="ISectionWithStringKey" /> <type name="IsolationInterop"> <type name="CreateActContextParameters"> <type name="CreateFlags" /> </type> <type name="CreateActContextParametersSource"> <type name="SourceFlags" /> </type> <type name="CreateActContextParametersSourceDefinitionAppid" /> </type> <type name="IStateManager" /> <type name="IStore" /> <type name="IStore_BindingResult" /> <type name="IStore_BindingResult_BoundVersion" /> <type name="ISTORE_BIND_REFERENCE_TO_ASSEMBLY_FLAGS" /> <type name="ISTORE_ENUM_ASSEMBLIES_FLAGS" /> <type name="ISTORE_ENUM_FILES_FLAGS" /> <type name="StateManager_RunningState" /> <type name="Store"> <type name="EnumApplicationPrivateFiles" /> <type name="EnumAssembliesFlags" /> <type name="EnumAssemblyFilesFlags" /> <type name="EnumAssemblyInstallReferenceFlags" /> <type name="EnumCategoriesFlags" /> <type name="EnumCategoryInstancesFlags" /> <type name="EnumSubcategoriesFlags" /> <type name="GetPackagePropertyFlags" /> <type name="IPathLock" /> </type> <type name="StoreApplicationReference"> <type name="RefFlags" /> </type> <type name="StoreAssemblyEnumeration" /> <type name="StoreAssemblyFileEnumeration" /> <type name="StoreCategoryEnumeration" /> <type name="StoreCategoryInstanceEnumeration" /> <type name="StoreDeploymentMetadataEnumeration" /> <type name="StoreDeploymentMetadataPropertyEnumeration" /> <type name="StoreOperationInstallDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationMetadataProperty" /> <type name="StoreOperationPinDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationScavenge"> <type name="OpFlags" /> </type> <type name="StoreOperationSetCanonicalizationContext"> <type name="OpFlags" /> </type> <type name="StoreOperationSetDeploymentMetadata"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationStageComponent"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationStageComponentFile"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationUninstallDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreOperationUnpinDeployment"> <type name="Disposition" /> <type name="OpFlags" /> </type> <type name="StoreSubcategoryEnumeration" /> <type name="StoreTransaction" /> <type name="StoreTransactionData" /> <type name="StoreTransactionOperation" /> <type name="StoreTransactionOperationType" /> <type name="STORE_ASSEMBLY" /> <type name="STORE_ASSEMBLY_FILE" /> <type name="STORE_ASSEMBLY_FILE_STATUS_FLAGS" /> <type name="STORE_ASSEMBLY_STATUS_FLAGS" /> <type name="STORE_CATEGORY" /> <type name="STORE_CATEGORY_INSTANCE" /> <type name="STORE_CATEGORY_SUBCATEGORY" /> <Manifest> <type name="AssemblyReferenceDependentAssemblyEntry" /> <type name="AssemblyReferenceDependentAssemblyEntryFieldId" /> <type name="AssemblyReferenceEntry" /> <type name="AssemblyReferenceEntryFieldId" /> <type name="AssemblyRequestEntry" /> <type name="AssemblyRequestEntryFieldId" /> <type name="CategoryMembershipDataEntry" /> <type name="CategoryMembershipDataEntryFieldId" /> <type name="CategoryMembershipEntry" /> <type name="CategoryMembershipEntryFieldId" /> <type name="CLRSurrogateEntry" /> <type name="CLRSurrogateEntryFieldId" /> <type name="CMSSECTIONID" /> <type name="CmsUtils" /> <type name="CMS_ASSEMBLY_DEPLOYMENT_FLAG" /> <type name="CMS_ASSEMBLY_REFERENCE_DEPENDENT_ASSEMBLY_FLAG" /> <type name="CMS_ASSEMBLY_REFERENCE_FLAG" /> <type name="CMS_COM_SERVER_FLAG" /> <type name="CMS_ENTRY_POINT_FLAG" /> <type name="CMS_FILE_FLAG" /> <type name="CMS_FILE_HASH_ALGORITHM" /> <type name="CMS_FILE_WRITABLE_TYPE" /> <type name="CMS_HASH_DIGESTMETHOD" /> <type name="CMS_HASH_TRANSFORM" /> <type name="CMS_SCHEMA_VERSION" /> <type name="CMS_TIME_UNIT_TYPE" /> <type name="CMS_USAGE_PATTERN" /> <type name="CompatibleFrameworksMetadataEntry" /> <type name="CompatibleFrameworksMetadataEntryFieldId" /> <type name="COMServerEntry" /> <type name="COMServerEntryFieldId" /> <type name="DependentOSMetadataEntry" /> <type name="DependentOSMetadataEntryFieldId" /> <type name="DeploymentMetadataEntry" /> <type name="DeploymentMetadataEntryFieldId" /> <type name="DescriptionMetadataEntry" /> <type name="DescriptionMetadataEntryFieldId" /> <type name="EntryPointEntry" /> <type name="EntryPointEntryFieldId" /> <type name="FileAssociationEntry" /> <type name="FileAssociationEntryFieldId" /> <type name="FileEntry" /> <type name="FileEntryFieldId" /> <type name="HashElementEntry" /> <type name="HashElementEntryFieldId" /> <type name="IAssemblyReferenceDependentAssemblyEntry" /> <type name="IAssemblyReferenceEntry" /> <type name="IAssemblyRequestEntry" /> <type name="ICategoryMembershipDataEntry" /> <type name="ICategoryMembershipEntry" /> <type name="ICLRSurrogateEntry" /> <type name="ICMS" /> <type name="ICompatibleFrameworksMetadataEntry" /> <type name="ICOMServerEntry" /> <type name="IDependentOSMetadataEntry" /> <type name="IDeploymentMetadataEntry" /> <type name="IDescriptionMetadataEntry" /> <type name="IEntryPointEntry" /> <type name="IFileAssociationEntry" /> <type name="IFileEntry" /> <type name="IHashElementEntry" /> <type name="IMetadataSectionEntry" /> <type name="IMuiResourceIdLookupMapEntry" /> <type name="IMuiResourceMapEntry" /> <type name="IMuiResourceTypeIdIntEntry" /> <type name="IMuiResourceTypeIdStringEntry" /> <type name="IPermissionSetEntry" /> <type name="IProgIdRedirectionEntry" /> <type name="IResourceTableMappingEntry" /> <type name="ISubcategoryMembershipEntry" /> <type name="IWindowClassEntry" /> <type name="MetadataSectionEntry" /> <type name="MetadataSectionEntryFieldId" /> <type name="MuiResourceIdLookupMapEntry" /> <type name="MuiResourceIdLookupMapEntryFieldId" /> <type name="MuiResourceMapEntry" /> <type name="MuiResourceMapEntryFieldId" /> <type name="MuiResourceTypeIdIntEntry" /> <type name="MuiResourceTypeIdIntEntryFieldId" /> <type name="MuiResourceTypeIdStringEntry" /> <type name="MuiResourceTypeIdStringEntryFieldId" /> <type name="PermissionSetEntry" /> <type name="PermissionSetEntryFieldId" /> <type name="ProgIdRedirectionEntry" /> <type name="ProgIdRedirectionEntryFieldId" /> <type name="ResourceTableMappingEntry" /> <type name="ResourceTableMappingEntryFieldId" /> <type name="SubcategoryMembershipEntry" /> <type name="SubcategoryMembershipEntryFieldId" /> <type name="WindowClassEntry" /> <type name="WindowClassEntryFieldId" /> </Manifest> </Isolation> </Internal> </Deployment> <Diagnostics> <type name="Assert" /> <type name="AssertFilter" /> <type name="AssertFilters" /> <type name="ConditionalAttribute" /> <type name="DebuggableAttribute"> <type name="DebuggingModes" /> </type> <type name="Debugger" /> <type name="DebuggerBrowsableAttribute" /> <type name="DebuggerBrowsableState" /> <type name="DebuggerDisplayAttribute" /> <type name="DebuggerHiddenAttribute" /> <type name="DebuggerNonUserCodeAttribute" /> <type name="DebuggerStepperBoundaryAttribute" /> <type name="DebuggerStepThroughAttribute" /> <type name="DebuggerTypeProxyAttribute" /> <type name="DebuggerVisualizerAttribute" /> <type name="DefaultFilter" /> <type name="EditAndContinueHelper" /> <type name="ICustomDebuggerNotification" /> <type name="Log" /> <type name="LoggingLevels" /> <type name="LogMessageEventHandler" /> <type name="LogSwitch" /> <type name="LogSwitchLevelHandler" /> <type name="StackFrame" /> <type name="StackFrameHelper" /> <type name="StackTrace"> <type name="TraceFormat" /> </type> <CodeAnalysis> <type name="SuppressMessageAttribute" /> </CodeAnalysis> <Contracts> <type name="Contract" /> <type name="ContractClassAttribute" /> <type name="ContractClassForAttribute" /> <type name="ContractException" /> <type name="ContractFailedEventArgs" /> <type name="ContractFailureKind" /> <type name="ContractInvariantMethodAttribute" /> <type name="ContractPublicPropertyNameAttribute" /> <type name="ContractReferenceAssemblyAttribute" /> <type name="ContractRuntimeIgnoredAttribute" /> <type name="ContractVerificationAttribute" /> <type name="PureAttribute" /> <Internal> <type name="ContractHelper" /> </Internal> </Contracts> <Eventing> <type name="ControllerCommand" /> <type name="EventAttribute" /> <type name="EventChannel" /> <type name="EventDescriptorInternal" /> <type name="EventKeywords" /> <type name="EventLevel" /> <type name="EventOpcode" /> <type name="EventProvider"> <type name="ClassicEtw"> <type name="ControlCallback" /> <type name="EVENT_HEADER" /> <type name="EVENT_TRACE_HEADER" /> <type name="TRACE_GUID_REGISTRATION" /> <type name="WMIDPREQUESTCODE" /> <type name="WNODE_HEADER" /> </type> <type name="EventData" /> <type name="ManifestEtw"> <type name="EtwEnableCallback" /> <type name="EVENT_FILTER_DESCRIPTOR" /> </type> <type name="WriteEventErrorCode" /> </type> <type name="EventProviderBase"> <type name="EventData" /> </type> <type name="EventProviderCreatedEventArgs" /> <type name="EventProviderDataStream" /> <type name="EventTask" /> <type name="EventWrittenEventArgs" /> <type name="FrameworkEventSource" /> <type name="ManifestBuilder" /> <type name="ManifestEnvelope"> <type name="ManifestFormats" /> </type> <type name="NonEventAttribute" /> </Eventing> <SymbolStore> <type name="ISymbolBinder" /> <type name="ISymbolBinder1" /> <type name="ISymbolDocument" /> <type name="ISymbolDocumentWriter" /> <type name="ISymbolMethod" /> <type name="ISymbolNamespace" /> <type name="ISymbolReader" /> <type name="ISymbolScope" /> <type name="ISymbolVariable" /> <type name="ISymbolWriter" /> <type name="SymAddressKind" /> <type name="SymbolToken" /> <type name="SymDocumentType" /> <type name="SymLanguageType" /> <type name="SymLanguageVendor" /> </SymbolStore> </Diagnostics> <Globalization> <type name="BidiCategory" /> <type name="Calendar" /> <type name="CalendarAlgorithmType" /> <type name="CalendarData" /> <type name="CalendarId" /> <type name="CalendarWeekRule" /> <type name="CharUnicodeInfo"> <type name="DigitValues" /> <type name="UnicodeDataHeader" /> </type> <type name="ChineseLunisolarCalendar" /> <type name="CodePageDataItem" /> <type name="CompareInfo" /> <type name="CompareOptions" /> <type name="CultureData" /> <type name="CultureInfo" /> <type name="CultureNotFoundException" /> <type name="CultureTypes" /> <type name="DateTimeFormatFlags" /> <type name="DateTimeFormatInfo" /> <type name="DateTimeFormatInfoScanner" /> <type name="DateTimeStyles" /> <type name="DaylightTime" /> <type name="DigitShapes" /> <type name="EastAsianLunisolarCalendar" /> <type name="EncodingTable" /> <type name="EraInfo" /> <type name="FORMATFLAGS" /> <type name="GlobalizationAssembly" /> <type name="GregorianCalendar" /> <type name="GregorianCalendarHelper" /> <type name="GregorianCalendarTypes" /> <type name="HebrewCalendar"> <type name="__DateBuffer" /> </type> <type name="HebrewNumber"> <type name="HS" /> </type> <type name="HebrewNumberParsingContext" /> <type name="HebrewNumberParsingState" /> <type name="HijriCalendar" /> <type name="IdnMapping" /> <type name="InternalCodePageDataItem" /> <type name="InternalEncodingDataItem" /> <type name="JapaneseCalendar" /> <type name="JapaneseLunisolarCalendar" /> <type name="JulianCalendar" /> <type name="KoreanCalendar" /> <type name="KoreanLunisolarCalendar" /> <type name="MonthNameStyles" /> <type name="NumberFormatInfo" /> <type name="NumberStyles" /> <type name="PersianCalendar" /> <type name="RegionInfo" /> <type name="SortKey" /> <type name="StringInfo" /> <type name="TaiwanCalendar" /> <type name="TaiwanLunisolarCalendar" /> <type name="TextElementEnumerator" /> <type name="TextInfo" /> <type name="ThaiBuddhistCalendar" /> <type name="TimeSpanFormat"> <type name="FormatLiterals" /> <type name="Pattern" /> </type> <type name="TimeSpanParse" /> <type name="TimeSpanStyles" /> <type name="TokenHashValue" /> <type name="UmAlQuraCalendar"> <type name="DateMapping" /> </type> <type name="UnicodeCategory" /> </Globalization> <IO> <type name="BinaryReader" /> <type name="BinaryWriter" /> <type name="BufferedStream" /> <type name="Directory"> <type name="SearchData" /> </type> <type name="DirectoryInfo" /> <type name="DirectoryInfoResultHandler" /> <type name="DirectoryNotFoundException" /> <type name="DriveInfo" /> <type name="DriveNotFoundException" /> <type name="DriveType" /> <type name="EndOfStreamException" /> <type name="File" /> <type name="FileAccess" /> <type name="FileAttributes" /> <type name="FileInfo" /> <type name="FileInfoResultHandler" /> <type name="FileLoadException" /> <type name="FileMode" /> <type name="FileNotFoundException" /> <type name="FileOptions" /> <type name="FileShare" /> <type name="FileStream" /> <type name="FileStreamAsyncResult" /> <type name="FileSystemEnumerableFactory" /> <type name="FileSystemEnumerableHelpers" /> <type name="FileSystemEnumerableIterator" arity="1" /> <type name="FileSystemInfo" /> <type name="FileSystemInfoResultHandler" /> <type name="IOException" /> <type name="Iterator" arity="1" /> <type name="LongPath" /> <type name="LongPathDirectory" /> <type name="LongPathFile" /> <type name="MdaHelper" /> <type name="MemoryStream" /> <type name="Path" /> <type name="PathHelper" /> <type name="PathTooLongException" /> <type name="PinnedBufferMemoryStream" /> <type name="SearchOption" /> <type name="SearchResult" /> <type name="SearchResultHandler" arity="1" /> <type name="SeekOrigin" /> <type name="Stream"> <type name="SyncStream" /> </type> <type name="StreamContract" /> <type name="StreamReader" /> <type name="StreamWriter" /> <type name="StringReader" /> <type name="StringResultHandler" /> <type name="StringWriter" /> <type name="TextReader"> <type name="SyncTextReader" /> </type> <type name="TextWriter"> <type name="SyncTextWriter" /> </type> <type name="UnmanagedMemoryAccessor" /> <type name="UnmanagedMemoryStream" /> <type name="UnmanagedMemoryStreamWrapper" /> <type name="__ConsoleStream" /> <type name="__Error" /> <type name="__HResults" /> <IsolatedStorage> <type name="INormalizeForIsolatedStorage" /> <type name="IsolatedStorage" /> <type name="IsolatedStorageException" /> <type name="IsolatedStorageFile" /> <type name="IsolatedStorageFileEnumerator" /> <type name="IsolatedStorageFileStream" /> <type name="IsolatedStorageScope" /> <type name="IsolatedStorageSecurityOptions" /> <type name="IsolatedStorageSecurityState" /> <type name="SafeIsolatedStorageFileHandle" /> <type name="TwoLevelFileEnumerator" /> <type name="TwoPaths" /> <type name="__HResults" /> </IsolatedStorage> </IO> <Reflection> <type name="AmbiguousMatchException" /> <type name="Assembly" /> <type name="AssemblyAlgorithmIdAttribute" /> <type name="AssemblyCompanyAttribute" /> <type name="AssemblyConfigurationAttribute" /> <type name="AssemblyCopyrightAttribute" /> <type name="AssemblyCultureAttribute" /> <type name="AssemblyDefaultAliasAttribute" /> <type name="AssemblyDelaySignAttribute" /> <type name="AssemblyDescriptionAttribute" /> <type name="AssemblyFileVersionAttribute" /> <type name="AssemblyFlagsAttribute" /> <type name="AssemblyInformationalVersionAttribute" /> <type name="AssemblyKeyFileAttribute" /> <type name="AssemblyKeyNameAttribute" /> <type name="AssemblyMetadata" /> <type name="AssemblyName" /> <type name="AssemblyNameFlags" /> <type name="AssemblyNameProxy" /> <type name="AssemblyProductAttribute" /> <type name="AssemblyTitleAttribute" /> <type name="AssemblyTrademarkAttribute" /> <type name="AssemblyVersionAttribute" /> <type name="AssociateRecord" /> <type name="Associates"> <type name="Attributes" /> </type> <type name="Binder" /> <type name="BindingFlags" /> <type name="CallingConventions" /> <type name="CerArrayList" arity="1" /> <type name="CerHashtable" arity="2" /> <type name="ConstArray" /> <type name="ConstructorInfo" /> <type name="CorElementType" /> <type name="CustomAttribute" /> <type name="CustomAttributeCtorParameter" /> <type name="CustomAttributeData" /> <type name="CustomAttributeEncodedArgument" /> <type name="CustomAttributeEncoding" /> <type name="CustomAttributeFormatException" /> <type name="CustomAttributeNamedArgument" /> <type name="CustomAttributeNamedParameter" /> <type name="CustomAttributeRecord" /> <type name="CustomAttributeType" /> <type name="CustomAttributeTypedArgument" /> <type name="DeclSecurityAttributes" /> <type name="DefaultMemberAttribute" /> <type name="EventAttributes" /> <type name="EventInfo" /> <type name="ExceptionHandlingClause" /> <type name="ExceptionHandlingClauseOptions" /> <type name="FieldAttributes" /> <type name="FieldInfo" /> <type name="GenericParameterAttributes" /> <type name="ICustomAttributeProvider" /> <type name="ImageFileMachine" /> <type name="InterfaceMapping" /> <type name="InvalidFilterCriteriaException" /> <type name="INVOCATION_FLAGS" /> <type name="IReflect" /> <type name="LoaderAllocator" /> <type name="LoaderAllocatorScout" /> <type name="LocalVariableInfo" /> <type name="ManifestResourceAttributes" /> <type name="ManifestResourceInfo" /> <type name="MdConstant" /> <type name="MdFieldInfo" /> <type name="MdSigCallingConvention" /> <type name="MemberFilter" /> <type name="MemberInfo" /> <type name="MemberInfoContracts" /> <type name="MemberInfoSerializationHolder" /> <type name="MemberListType" /> <type name="MemberTypes" /> <type name="MetadataArgs"> <type name="SkipAddresses" /> </type> <type name="MetadataCodedTokenType" /> <type name="MetadataColumn" /> <type name="MetadataColumnType" /> <type name="MetadataException" /> <type name="MetadataFieldOffset" /> <type name="MetadataFileAttributes" /> <type name="MetadataImport" /> <type name="MetadataTable" /> <type name="MetadataToken" /> <type name="MetadataTokenType" /> <type name="MethodAttributes" /> <type name="MethodBase" /> <type name="MethodBody" /> <type name="MethodImplAttributes" /> <type name="MethodInfo" /> <type name="MethodSemanticsAttributes" /> <type name="Missing" /> <type name="Module" /> <type name="ModuleResolveEventHandler" /> <type name="ObfuscateAssemblyAttribute" /> <type name="ObfuscationAttribute" /> <type name="ParameterAttributes" /> <type name="ParameterInfo" /> <type name="ParameterModifier" /> <type name="PInvokeAttributes" /> <type name="Pointer" /> <type name="PortableExecutableKinds" /> <type name="ProcessorArchitecture" /> <type name="PropertyAttributes" /> <type name="PropertyInfo" /> <type name="PseudoCustomAttribute" /> <type name="ReflectionTypeLoadException" /> <type name="ResourceAttributes" /> <type name="ResourceLocation" /> <type name="RtFieldInfo" /> <type name="RuntimeAssembly" /> <type name="RuntimeConstructorInfo" /> <type name="RuntimeEventInfo" /> <type name="RuntimeFieldInfo" /> <type name="RuntimeMethodInfo" /> <type name="RuntimeModule" /> <type name="RuntimeParameterInfo" /> <type name="RuntimePropertyInfo" /> <type name="SecurityContextFrame" /> <type name="StrongNameKeyPair" /> <type name="TargetException" /> <type name="TargetInvocationException" /> <type name="TargetParameterCountException" /> <type name="TypeAttributes" /> <type name="TypeDelegator" /> <type name="TypeFilter" /> <type name="__Filters" /> <Cache> <type name="CacheAction" /> <type name="CacheObjType" /> <type name="ClearCacheEventArgs" /> <type name="ClearCacheHandler" /> <type name="InternalCache" /> <type name="InternalCacheItem" /> <type name="TypeNameStruct" /> </Cache> <Emit> <type name="AssemblyBuilder" /> <type name="AssemblyBuilderAccess" /> <type name="AssemblyBuilderData" /> <type name="ConstructorBuilder" /> <type name="ConstructorOnTypeBuilderInstantiation" /> <type name="CustomAttributeBuilder" /> <type name="DynamicAssemblyFlags" /> <type name="DynamicILGenerator" /> <type name="DynamicILInfo" /> <type name="DynamicMethod"> <type name="RTDynamicMethod" /> </type> <type name="DynamicResolver"> <type name="SecurityControlFlags" /> </type> <type name="DynamicScope" /> <type name="EnumBuilder" /> <type name="EventBuilder" /> <type name="EventToken" /> <type name="FieldBuilder" /> <type name="FieldOnTypeBuilderInstantiation" /> <type name="FieldToken" /> <type name="FlowControl" /> <type name="GenericFieldInfo" /> <type name="GenericMethodInfo" /> <type name="GenericTypeParameterBuilder" /> <type name="ILGenerator" /> <type name="InternalAssemblyBuilder" /> <type name="InternalModuleBuilder" /> <type name="Label" /> <type name="LineNumberInfo" /> <type name="LocalBuilder" /> <type name="LocalSymInfo" /> <type name="MethodBuilder" /> <type name="MethodBuilderInstantiation" /> <type name="MethodOnTypeBuilderInstantiation" /> <type name="MethodRental" /> <type name="MethodToken" /> <type name="ModuleBuilder" /> <type name="ModuleBuilderData" /> <type name="NativeVersionInfo" /> <type name="OpCode" /> <type name="OpCodes" /> <type name="OpCodeType" /> <type name="OperandType" /> <type name="PackingSize" /> <type name="ParameterBuilder" /> <type name="ParameterToken" /> <type name="PEFileKinds" /> <type name="PropertyBuilder" /> <type name="PropertyToken" /> <type name="REDocument" /> <type name="ResWriterData" /> <type name="ScopeAction" /> <type name="ScopeTree" /> <type name="SignatureHelper" /> <type name="SignatureToken" /> <type name="StackBehaviour" /> <type name="StringToken" /> <type name="SymbolMethod" /> <type name="SymbolType" /> <type name="TypeBuilder"> <type name="CustAttr" /> </type> <type name="TypeBuilderInstantiation" /> <type name="TypeKind" /> <type name="TypeNameBuilder"> <type name="Format" /> </type> <type name="TypeToken" /> <type name="UnmanagedMarshal" /> <type name="VarArgMethod" /> <type name="__ExceptionInfo" /> <type name="__ExceptionInstance" /> <type name="__FixupData" /> </Emit> </Reflection> <Resources> <type name="FastResourceComparer" /> <type name="FileBasedResourceGroveler" /> <type name="IResourceGroveler" /> <type name="IResourceReader" /> <type name="IResourceWriter" /> <type name="ManifestBasedResourceGroveler" /> <type name="MissingManifestResourceException" /> <type name="MissingSatelliteAssemblyException" /> <type name="NeutralResourcesLanguageAttribute" /> <type name="ResourceFallbackManager" /> <type name="ResourceLocator" /> <type name="ResourceManager"> <type name="ResourceManagerMediator" /> </type> <type name="ResourceReader"> <type name="ResourceEnumerator" /> <type name="TypeLimitingDeserializationBinder" /> </type> <type name="ResourceSet" /> <type name="ResourceTypeCode" /> <type name="ResourceWriter" /> <type name="RuntimeResourceSet" /> <type name="SatelliteContractVersionAttribute" /> <type name="UltimateResourceFallbackLocation" /> </Resources> <Runtime> <type name="AssemblyTargetedPatchBandAttribute" /> <type name="ForceTokenStabilizationAttribute" /> <type name="GCLatencyMode" /> <type name="GCSettings" /> <type name="MemoryFailPoint" /> <type name="TargetedPatchingOptOutAttribute" /> <CompilerServices> <type name="AccessedThroughPropertyAttribute" /> <type name="AssemblyAttributesGoHere" /> <type name="AssemblyAttributesGoHereM" /> <type name="AssemblyAttributesGoHereS" /> <type name="AssemblyAttributesGoHereSM" /> <type name="CallConvCdecl" /> <type name="CallConvFastcall" /> <type name="CallConvStdcall" /> <type name="CallConvThiscall" /> <type name="CompilationRelaxations" /> <type name="CompilationRelaxationsAttribute" /> <type name="CompilerGeneratedAttribute" /> <type name="CompilerGlobalScopeAttribute" /> <type name="CompilerMarshalOverride" /> <type name="ConditionalWeakTable" arity="2"> <type name="CreateValueCallback" /> </type> <type name="CustomConstantAttribute" /> <type name="DateTimeConstantAttribute" /> <type name="DecimalConstantAttribute" /> <type name="DecoratedNameAttribute" /> <type name="DefaultDependencyAttribute" /> <type name="DependencyAttribute" /> <type name="DependentHandle" /> <type name="DiscardableAttribute" /> <type name="FixedAddressValueTypeAttribute" /> <type name="FixedBufferAttribute" /> <type name="FriendAccessAllowedAttribute" /> <type name="HasCopySemanticsAttribute" /> <type name="IDispatchConstantAttribute" /> <type name="IndexerNameAttribute" /> <type name="InternalsVisibleToAttribute" /> <type name="IsBoxed" /> <type name="IsByValue" /> <type name="IsConst" /> <type name="IsCopyConstructed" /> <type name="IsExplicitlyDereferenced" /> <type name="IsImplicitlyDereferenced" /> <type name="IsJitIntrinsic" /> <type name="IsLong" /> <type name="IsPinned" /> <type name="IsSignUnspecifiedByte" /> <type name="IsUdtReturn" /> <type name="IsVolatile" /> <type name="IUnknownConstantAttribute" /> <type name="JitHelpers" /> <type name="LoadHint" /> <type name="MethodCodeType" /> <type name="MethodImplAttribute" /> <type name="MethodImplOptions" /> <type name="NativeCppClassAttribute" /> <type name="ObjectHandleOnStack" /> <type name="PinningHelper" /> <type name="ReferenceAssemblyAttribute" /> <type name="RequiredAttributeAttribute" /> <type name="RuntimeCompatibilityAttribute" /> <type name="RuntimeHelpers"> <type name="CleanupCode" /> <type name="TryCode" /> </type> <type name="RuntimeWrappedException" /> <type name="ScopelessEnumAttribute" /> <type name="SpecialNameAttribute" /> <type name="StackCrawlMarkHandle" /> <type name="StringFreezingAttribute" /> <type name="StringHandleOnStack" /> <type name="SuppressIldasmAttribute" /> <type name="SuppressMergeCheckAttribute" /> <type name="TypeDependencyAttribute" /> <type name="TypeForwardedFromAttribute" /> <type name="TypeForwardedToAttribute" /> <type name="UnsafeValueTypeAttribute" /> </CompilerServices> <ConstrainedExecution> <type name="Cer" /> <type name="Consistency" /> <type name="CriticalFinalizerObject" /> <type name="PrePrepareMethodAttribute" /> <type name="ReliabilityContractAttribute" /> </ConstrainedExecution> <ExceptionServices> <type name="FirstChanceExceptionEventArgs" /> <type name="HandleProcessCorruptedStateExceptionsAttribute" /> </ExceptionServices> <Hosting> <type name="ActivationArguments" /> <type name="ApplicationActivator" /> <type name="ManifestRunner" /> </Hosting> <InteropServices> <type name="AllowReversePInvokeCallsAttribute" /> <type name="ArrayWithOffset" /> <type name="AssemblyRegistrationFlags" /> <type name="AutomationProxyAttribute" /> <type name="BestFitMappingAttribute" /> <type name="BINDPTR" /> <type name="BIND_OPTS" /> <type name="BStrWrapper" /> <type name="CALLCONV" /> <type name="CallingConvention" /> <type name="CharSet" /> <type name="ClassInterfaceAttribute" /> <type name="ClassInterfaceType" /> <type name="CoClassAttribute" /> <type name="ComAliasNameAttribute" /> <type name="ComCompatibleVersionAttribute" /> <type name="ComConversionLossAttribute" /> <type name="ComDefaultInterfaceAttribute" /> <type name="ComEventInterfaceAttribute" /> <type name="ComEventsHelper" /> <type name="ComEventsInfo" /> <type name="ComEventsMethod"> <type name="DelegateWrapper" /> </type> <type name="ComEventsSink" /> <type name="COMException" /> <type name="ComImportAttribute" /> <type name="ComInterfaceType" /> <type name="ComMemberType" /> <type name="ComRegisterFunctionAttribute" /> <type name="ComSourceInterfacesAttribute" /> <type name="ComUnregisterFunctionAttribute" /> <type name="ComVisibleAttribute" /> <type name="CONNECTDATA" /> <type name="CriticalHandle" /> <type name="CurrencyWrapper" /> <type name="CustomQueryInterfaceMode" /> <type name="CustomQueryInterfaceResult" /> <type name="DefaultCharSetAttribute" /> <type name="DESCKIND" /> <type name="DispatchWrapper" /> <type name="DispIdAttribute" /> <type name="DISPPARAMS" /> <type name="DllImportAttribute" /> <type name="ELEMDESC"> <type name="DESCUNION" /> </type> <type name="ErrorWrapper" /> <type name="EXCEPINFO" /> <type name="ExporterEventKind" /> <type name="ExtensibleClassFactory" /> <type name="ExternalException" /> <type name="FieldOffsetAttribute" /> <type name="FILETIME" /> <type name="FUNCDESC" /> <type name="FUNCFLAGS" /> <type name="FUNCKIND" /> <type name="GCHandle" /> <type name="GCHandleCookieTable" /> <type name="GCHandleType" /> <type name="GuidAttribute" /> <type name="HandleRef" /> <type name="ICustomAdapter" /> <type name="ICustomFactory" /> <type name="ICustomMarshaler" /> <type name="ICustomQueryInterface" /> <type name="IDispatchImplAttribute" /> <type name="IDispatchImplType" /> <type name="IDLDESC" /> <type name="IDLFLAG" /> <type name="IMPLTYPEFLAGS" /> <type name="ImportedFromTypeLibAttribute" /> <type name="ImporterCallback" /> <type name="ImporterEventKind" /> <type name="InAttribute" /> <type name="InterfaceTypeAttribute" /> <type name="InvalidComObjectException" /> <type name="InvalidOleVariantTypeException" /> <type name="INVOKEKIND" /> <type name="IRegistrationServices" /> <type name="ITypeLibConverter" /> <type name="ITypeLibExporterNameProvider" /> <type name="ITypeLibExporterNotifySink" /> <type name="ITypeLibImporterNotifySink" /> <type name="LayoutKind" /> <type name="LCIDConversionAttribute" /> <type name="LIBFLAGS" /> <type name="ManagedToNativeComInteropStubAttribute" /> <type name="Marshal" /> <type name="MarshalAsAttribute" /> <type name="MarshalDirectiveException" /> <type name="NativeMethods"> <type name="IDispatch" /> </type> <type name="ObjectCreationDelegate" /> <type name="OptionalAttribute" /> <type name="OutAttribute" /> <type name="PARAMDESC" /> <type name="PARAMFLAG" /> <type name="PInvokeMap" /> <type name="PreserveSigAttribute" /> <type name="PrimaryInteropAssemblyAttribute" /> <type name="ProgIdAttribute" /> <type name="RegistrationClassContext" /> <type name="RegistrationConnectionType" /> <type name="RegistrationServices" /> <type name="RuntimeEnvironment" /> <type name="SafeArrayRankMismatchException" /> <type name="SafeArrayTypeMismatchException" /> <type name="SafeBuffer" /> <type name="SafeHandle" /> <type name="SEHException" /> <type name="SetWin32ContextInIDispatchAttribute" /> <type name="STATSTG" /> <type name="StructLayoutAttribute" /> <type name="SYSKIND" /> <type name="TYPEATTR" /> <type name="TYPEDESC" /> <type name="TYPEFLAGS" /> <type name="TypeIdentifierAttribute" /> <type name="TYPEKIND" /> <type name="TYPELIBATTR" /> <type name="TypeLibConverter" /> <type name="TypeLibExporterFlags" /> <type name="TypeLibFuncAttribute" /> <type name="TypeLibFuncFlags" /> <type name="TypeLibImportClassAttribute" /> <type name="TypeLibImporterFlags" /> <type name="TypeLibTypeAttribute" /> <type name="TypeLibTypeFlags" /> <type name="TypeLibVarAttribute" /> <type name="TypeLibVarFlags" /> <type name="TypeLibVersionAttribute" /> <type name="UCOMIBindCtx" /> <type name="UCOMIConnectionPoint" /> <type name="UCOMIConnectionPointContainer" /> <type name="UCOMIEnumConnectionPoints" /> <type name="UCOMIEnumConnections" /> <type name="UCOMIEnumerable" /> <type name="UCOMIEnumerator" /> <type name="UCOMIEnumMoniker" /> <type name="UCOMIEnumString" /> <type name="UCOMIEnumVARIANT" /> <type name="UCOMIExpando" /> <type name="UCOMIMoniker" /> <type name="UCOMIPersistFile" /> <type name="UCOMIReflect" /> <type name="UCOMIRunningObjectTable" /> <type name="UCOMIStream" /> <type name="UCOMITypeComp" /> <type name="UCOMITypeInfo" /> <type name="UCOMITypeLib" /> <type name="UnknownWrapper" /> <type name="UnmanagedFunctionPointerAttribute" /> <type name="UnmanagedType" /> <type name="VARDESC"> <type name="DESCUNION" /> </type> <type name="VarEnum" /> <type name="VARFLAGS" /> <type name="Variant"> <type name="Record" /> <type name="TypeUnion" /> <type name="UnionTypes" /> </type> <type name="VariantWrapper" /> <type name="_Activator" /> <type name="_Assembly" /> <type name="_AssemblyBuilder" /> <type name="_AssemblyName" /> <type name="_Attribute" /> <type name="_ConstructorBuilder" /> <type name="_ConstructorInfo" /> <type name="_CustomAttributeBuilder" /> <type name="_EnumBuilder" /> <type name="_EventBuilder" /> <type name="_EventInfo" /> <type name="_Exception" /> <type name="_FieldBuilder" /> <type name="_FieldInfo" /> <type name="_ILGenerator" /> <type name="_LocalBuilder" /> <type name="_MemberInfo" /> <type name="_MethodBase" /> <type name="_MethodBuilder" /> <type name="_MethodInfo" /> <type name="_MethodRental" /> <type name="_Module" /> <type name="_ModuleBuilder" /> <type name="_ParameterBuilder" /> <type name="_ParameterInfo" /> <type name="_PropertyBuilder" /> <type name="_PropertyInfo" /> <type name="_SignatureHelper" /> <type name="_Thread" /> <type name="_Type" /> <type name="_TypeBuilder" /> <ComTypes> <type name="BINDPTR" /> <type name="BIND_OPTS" /> <type name="CALLCONV" /> <type name="CONNECTDATA" /> <type name="DESCKIND" /> <type name="DISPPARAMS" /> <type name="ELEMDESC"> <type name="DESCUNION" /> </type> <type name="EXCEPINFO" /> <type name="FILETIME" /> <type name="FUNCDESC" /> <type name="FUNCFLAGS" /> <type name="FUNCKIND" /> <type name="IBindCtx" /> <type name="IConnectionPoint" /> <type name="IConnectionPointContainer" /> <type name="IDLDESC" /> <type name="IDLFLAG" /> <type name="IEnumConnectionPoints" /> <type name="IEnumConnections" /> <type name="IEnumerable" /> <type name="IEnumerator" /> <type name="IEnumMoniker" /> <type name="IEnumString" /> <type name="IEnumVARIANT" /> <type name="IExpando" /> <type name="IMoniker" /> <type name="IMPLTYPEFLAGS" /> <type name="INVOKEKIND" /> <type name="IPersistFile" /> <type name="IReflect" /> <type name="IRunningObjectTable" /> <type name="IStream" /> <type name="ITypeComp" /> <type name="ITypeInfo" /> <type name="ITypeInfo2" /> <type name="ITypeLib" /> <type name="ITypeLib2" /> <type name="LIBFLAGS" /> <type name="PARAMDESC" /> <type name="PARAMFLAG" /> <type name="STATSTG" /> <type name="SYSKIND" /> <type name="TYPEATTR" /> <type name="TYPEDESC" /> <type name="TYPEFLAGS" /> <type name="TYPEKIND" /> <type name="TYPELIBATTR" /> <type name="VARDESC"> <type name="DESCUNION" /> </type> <type name="VARFLAGS" /> <type name="VARKIND" /> </ComTypes> <Expando> <type name="IExpando" /> </Expando> <TCEAdapterGen> <type name="EventItfInfo" /> <type name="EventProviderWriter" /> <type name="EventSinkHelperWriter" /> <type name="NameSpaceExtractor" /> <type name="TCEAdapterGenerator" /> </TCEAdapterGen> </InteropServices> <Remoting> <type name="ActivatedClientTypeEntry" /> <type name="ActivatedServiceTypeEntry" /> <type name="ChannelInfo" /> <type name="ComRedirectionProxy" /> <type name="CustomErrorsModes" /> <type name="DelayLoadClientChannelEntry" /> <type name="DomainSpecificRemotingData" /> <type name="DuplicateIdentityOption" /> <type name="DynamicTypeInfo" /> <type name="EnvoyInfo" /> <type name="IChannelInfo" /> <type name="Identity" /> <type name="IdentityHolder" /> <type name="IdOps" /> <type name="IEnvoyInfo" /> <type name="InternalRemotingServices" /> <type name="IObjectHandle" /> <type name="IRemotingTypeInfo" /> <type name="ObjectHandle" /> <type name="ObjRef" /> <type name="RedirectionProxy" /> <type name="RemoteAppEntry" /> <type name="RemotingConfigHandler"> <type name="RemotingConfigInfo" /> </type> <type name="RemotingConfiguration" /> <type name="RemotingException" /> <type name="RemotingServices" /> <type name="RemotingTimeoutException" /> <type name="ServerException" /> <type name="ServerIdentity" /> <type name="SoapServices" /> <type name="TypeEntry" /> <type name="TypeInfo" /> <type name="WellKnownClientTypeEntry" /> <type name="WellKnownObjectMode" /> <type name="WellKnownServiceTypeEntry" /> <type name="XmlNamespaceEncoder" /> <type name="__HResults" /> <Activation> <type name="ActivationAttributeStack" /> <type name="ActivationListener" /> <type name="ActivationServices" /> <type name="ActivatorLevel" /> <type name="AppDomainLevelActivator" /> <type name="ConstructionLevelActivator" /> <type name="ContextLevelActivator" /> <type name="IActivator" /> <type name="IConstructionCallMessage" /> <type name="IConstructionReturnMessage" /> <type name="LocalActivator" /> <type name="RemotePropertyHolderAttribute" /> <type name="RemotingXmlConfigFileData"> <type name="ChannelEntry" /> <type name="ClientWellKnownEntry" /> <type name="ContextAttributeEntry" /> <type name="CustomErrorsEntry" /> <type name="InteropXmlElementEntry" /> <type name="InteropXmlTypeEntry" /> <type name="LifetimeEntry" /> <type name="PreLoadEntry" /> <type name="RemoteAppEntry" /> <type name="ServerWellKnownEntry" /> <type name="SinkProviderEntry" /> <type name="TypeEntry" /> </type> <type name="RemotingXmlConfigFileParser" /> <type name="UrlAttribute" /> </Activation> <Channels> <type name="ADAsyncWorkItem" /> <type name="AggregateDictionary" /> <type name="AsyncMessageHelper" /> <type name="AsyncWorkItem" /> <type name="BaseChannelObjectWithProperties" /> <type name="BaseChannelSinkWithProperties" /> <type name="BaseChannelWithProperties" /> <type name="ChannelDataStore" /> <type name="ChannelServices" /> <type name="ChannelServicesData" /> <type name="ClientChannelSinkStack" /> <type name="CrossAppDomainChannel" /> <type name="CrossAppDomainData" /> <type name="CrossAppDomainSerializer" /> <type name="CrossAppDomainSink" /> <type name="CrossContextChannel" /> <type name="DictionaryEnumeratorByKeys" /> <type name="DispatchChannelSink" /> <type name="DispatchChannelSinkProvider" /> <type name="IChannel" /> <type name="IChannelDataStore" /> <type name="IChannelReceiver" /> <type name="IChannelReceiverHook" /> <type name="IChannelSender" /> <type name="IChannelSinkBase" /> <type name="IClientChannelSink" /> <type name="IClientChannelSinkProvider" /> <type name="IClientChannelSinkStack" /> <type name="IClientFormatterSink" /> <type name="IClientFormatterSinkProvider" /> <type name="IClientResponseChannelSinkStack" /> <type name="ISecurableChannel" /> <type name="IServerChannelSink" /> <type name="IServerChannelSinkProvider" /> <type name="IServerChannelSinkStack" /> <type name="IServerFormatterSinkProvider" /> <type name="IServerResponseChannelSinkStack" /> <type name="ITransportHeaders" /> <type name="Perf_Contexts" /> <type name="RegisteredChannel" /> <type name="RegisteredChannelList" /> <type name="RemotingProfilerEvent" /> <type name="ServerAsyncReplyTerminatorSink" /> <type name="ServerChannelSinkStack" /> <type name="ServerProcessing" /> <type name="SinkProviderData" /> <type name="TransportHeaders" /> </Channels> <Contexts> <type name="ArrayWithSize" /> <type name="CallBackHelper" /> <type name="Context" /> <type name="ContextAttribute" /> <type name="ContextProperty" /> <type name="CrossContextDelegate" /> <type name="DynamicPropertyHolder" /> <type name="IContextAttribute" /> <type name="IContextProperty" /> <type name="IContextPropertyActivator" /> <type name="IContributeClientContextSink" /> <type name="IContributeDynamicSink" /> <type name="IContributeEnvoySink" /> <type name="IContributeObjectSink" /> <type name="IContributeServerContextSink" /> <type name="IDynamicMessageSink" /> <type name="IDynamicProperty" /> <type name="SynchronizationAttribute" /> <type name="SynchronizedClientContextSink"> <type name="AsyncReplySink" /> </type> <type name="SynchronizedServerContextSink" /> <type name="WorkItem" /> </Contexts> <Lifetime> <type name="ClientSponsor" /> <type name="ILease" /> <type name="ISponsor" /> <type name="Lease"> <type name="AsyncRenewal" /> <type name="SponsorState" /> <type name="SponsorStateInfo" /> </type> <type name="LeaseLifeTimeServiceProperty" /> <type name="LeaseManager"> <type name="SponsorInfo" /> </type> <type name="LeaseSink" /> <type name="LeaseState" /> <type name="LifetimeServices" /> </Lifetime> <Messaging> <type name="ArgMapper" /> <type name="AsyncReplySink" /> <type name="AsyncResult" /> <type name="CallContext" /> <type name="CallContextRemotingData" /> <type name="CallContextSecurityData" /> <type name="CCMDictionary" /> <type name="ClientAsyncReplyTerminatorSink" /> <type name="ClientContextTerminatorSink" /> <type name="ConstructionCall" /> <type name="ConstructionResponse" /> <type name="ConstructorCallMessage" /> <type name="ConstructorReturnMessage" /> <type name="CRMDictionary" /> <type name="DisposeSink" /> <type name="EnvoyTerminatorSink" /> <type name="ErrorMessage" /> <type name="Header" /> <type name="HeaderHandler" /> <type name="IInternalMessage" /> <type name="IllogicalCallContext" /> <type name="ILogicalThreadAffinative" /> <type name="IMessage" /> <type name="IMessageCtrl" /> <type name="IMessageSink" /> <type name="IMethodCallMessage" /> <type name="IMethodMessage" /> <type name="IMethodReturnMessage" /> <type name="InternalMessageWrapper" /> <type name="InternalSink" /> <type name="IRemotingFormatter" /> <type name="ISerializationRootObject" /> <type name="LogicalCallContext" /> <type name="MCMDictionary" /> <type name="Message" /> <type name="MessageDictionary" /> <type name="MessageDictionaryEnumerator" /> <type name="MessageSmuggler"> <type name="SerializedArg" /> </type> <type name="MessageSurrogate" /> <type name="MessageSurrogateFilter" /> <type name="MethodCall" /> <type name="MethodCallMessageWrapper" /> <type name="MethodResponse" /> <type name="MethodReturnMessageWrapper" /> <type name="MRMDictionary" /> <type name="ObjRefSurrogate" /> <type name="OneWayAttribute" /> <type name="RemotingSurrogate" /> <type name="RemotingSurrogateSelector" /> <type name="ReturnMessage" /> <type name="SerializationMonkey" /> <type name="ServerContextTerminatorSink" /> <type name="ServerObjectTerminatorSink" /> <type name="SmuggledMethodCallMessage" /> <type name="SmuggledMethodReturnMessage" /> <type name="SmuggledObjRef" /> <type name="SoapMessageSurrogate" /> <type name="StackBasedReturnMessage" /> <type name="StackBuilderSink" /> <type name="TransitionCall" /> </Messaging> <Metadata> <type name="RemotingCachedData" /> <type name="RemotingMethodCachedData" /> <type name="RemotingTypeCachedData" /> <type name="SoapAttribute" /> <type name="SoapFieldAttribute" /> <type name="SoapMethodAttribute" /> <type name="SoapOption" /> <type name="SoapParameterAttribute" /> <type name="SoapTypeAttribute" /> <type name="XmlFieldOrderOption" /> <W3cXsd2001> <type name="ISoapXsd" /> <type name="SoapAnyUri" /> <type name="SoapBase64Binary" /> <type name="SoapDate" /> <type name="SoapDateTime" /> <type name="SoapDay" /> <type name="SoapDuration" /> <type name="SoapEntities" /> <type name="SoapEntity" /> <type name="SoapHexBinary" /> <type name="SoapId" /> <type name="SoapIdref" /> <type name="SoapIdrefs" /> <type name="SoapInteger" /> <type name="SoapLanguage" /> <type name="SoapMonth" /> <type name="SoapMonthDay" /> <type name="SoapName" /> <type name="SoapNcName" /> <type name="SoapNegativeInteger" /> <type name="SoapNmtoken" /> <type name="SoapNmtokens" /> <type name="SoapNonNegativeInteger" /> <type name="SoapNonPositiveInteger" /> <type name="SoapNormalizedString" /> <type name="SoapNotation" /> <type name="SoapPositiveInteger" /> <type name="SoapQName" /> <type name="SoapTime" /> <type name="SoapToken" /> <type name="SoapType" /> <type name="SoapYear" /> <type name="SoapYearMonth" /> </W3cXsd2001> </Metadata> <Proxies> <type name="AgileAsyncWorkerItem" /> <type name="CallType" /> <type name="MessageData" /> <type name="ProxyAttribute" /> <type name="RealProxy" /> <type name="RealProxyFlags" /> <type name="RemotingProxy" /> <type name="__TransparentProxy" /> </Proxies> <Services> <type name="EnterpriseServicesHelper" /> <type name="ITrackingHandler" /> <type name="TrackingServices" /> </Services> </Remoting> <Serialization> <type name="DeserializationEventHandler" /> <type name="FixupHolder" /> <type name="FixupHolderList" /> <type name="Formatter" /> <type name="FormatterConverter" /> <type name="FormatterServices" /> <type name="IDeserializationCallback" /> <type name="IFormatter" /> <type name="IFormatterConverter" /> <type name="IObjectReference" /> <type name="ISafeSerializationData" /> <type name="ISerializable" /> <type name="ISerializationSurrogate" /> <type name="ISurrogateSelector" /> <type name="LongList" /> <type name="MemberHolder" /> <type name="ObjectCloneHelper" /> <type name="ObjectHolder" /> <type name="ObjectHolderList" /> <type name="ObjectHolderListEnumerator" /> <type name="ObjectIDGenerator" /> <type name="ObjectManager" /> <type name="OnDeserializedAttribute" /> <type name="OnDeserializingAttribute" /> <type name="OnSerializedAttribute" /> <type name="OnSerializingAttribute" /> <type name="OptionalFieldAttribute" /> <type name="SafeSerializationEventArgs" /> <type name="SafeSerializationManager" /> <type name="SerializationBinder" /> <type name="SerializationEntry" /> <type name="SerializationEventHandler" /> <type name="SerializationEvents" /> <type name="SerializationEventsCache" /> <type name="SerializationException" /> <type name="SerializationFieldInfo" /> <type name="SerializationInfo" /> <type name="SerializationInfoEnumerator" /> <type name="SerializationObjectManager" /> <type name="StreamingContext" /> <type name="StreamingContextStates" /> <type name="SurrogateForCyclicalReference" /> <type name="SurrogateHashtable" /> <type name="SurrogateKey" /> <type name="SurrogateSelector" /> <type name="TypeLoadExceptionHolder" /> <type name="ValueTypeFixupInfo" /> <Formatters> <type name="FormatterAssemblyStyle" /> <type name="FormatterTypeStyle" /> <type name="IFieldInfo" /> <type name="InternalRM" /> <type name="InternalST" /> <type name="ISoapMessage" /> <type name="SerTrace" /> <type name="ServerFault" /> <type name="SoapFault" /> <type name="SoapMessage" /> <type name="TypeFilterLevel" /> <Binary> <type name="BinaryArray" /> <type name="BinaryArrayTypeEnum" /> <type name="BinaryAssembly" /> <type name="BinaryAssemblyInfo" /> <type name="BinaryConverter" /> <type name="BinaryCrossAppDomainAssembly" /> <type name="BinaryCrossAppDomainMap" /> <type name="BinaryCrossAppDomainString" /> <type name="BinaryFormatter" /> <type name="BinaryHeaderEnum" /> <type name="BinaryMethodCall" /> <type name="BinaryMethodCallMessage" /> <type name="BinaryMethodReturn" /> <type name="BinaryMethodReturnMessage" /> <type name="BinaryObject" /> <type name="BinaryObjectString" /> <type name="BinaryObjectWithMap" /> <type name="BinaryObjectWithMapTyped" /> <type name="BinaryTypeEnum" /> <type name="BinaryUtil" /> <type name="Converter" /> <type name="InternalArrayTypeE" /> <type name="InternalElementTypeE" /> <type name="InternalFE" /> <type name="InternalMemberTypeE" /> <type name="InternalMemberValueE" /> <type name="InternalNameSpaceE" /> <type name="InternalObjectPositionE" /> <type name="InternalObjectTypeE" /> <type name="InternalParseStateE" /> <type name="InternalParseTypeE" /> <type name="InternalPrimitiveTypeE" /> <type name="InternalSerializerTypeE" /> <type name="IntSizedArray" /> <type name="IOUtil" /> <type name="IStreamable" /> <type name="MemberPrimitiveTyped" /> <type name="MemberPrimitiveUnTyped" /> <type name="MemberReference" /> <type name="MessageEnd" /> <type name="MessageEnum" /> <type name="NameCache" /> <type name="NameInfo" /> <type name="ObjectMap" /> <type name="ObjectMapInfo" /> <type name="ObjectNull" /> <type name="ObjectProgress" /> <type name="ObjectReader"> <type name="TopLevelAssemblyTypeResolver" /> <type name="TypeNAssembly" /> </type> <type name="ObjectWriter" /> <type name="ParseRecord" /> <type name="PrimitiveArray" /> <type name="ReadObjectInfo" /> <type name="SerializationHeaderRecord" /> <type name="SerObjectInfoCache" /> <type name="SerObjectInfoInit" /> <type name="SerStack" /> <type name="SizedArray" /> <type name="SoapAttributeType" /> <type name="TypeInformation" /> <type name="ValueFixup" /> <type name="ValueFixupEnum" /> <type name="WriteObjectInfo" /> <type name="__BinaryParser" /> <type name="__BinaryWriter" /> </Binary> </Formatters> </Serialization> <Versioning> <type name="ComponentGuaranteesAttribute" /> <type name="ComponentGuaranteesOptions" /> <type name="MultitargetingHelpers" /> <type name="ResourceConsumptionAttribute" /> <type name="ResourceExposureAttribute" /> <type name="ResourceScope" /> <type name="SxSRequirements" /> <type name="TargetFrameworkAttribute" /> <type name="VersioningHelper" /> </Versioning> </Runtime> <Security> <type name="AllowPartiallyTrustedCallersAttribute" /> <type name="BuiltInPermissionSets" /> <type name="CodeAccessPermission" /> <type name="CodeAccessSecurityEngine" /> <type name="DynamicSecurityMethodAttribute" /> <type name="FrameSecurityDescriptor" /> <type name="HostProtectionException" /> <type name="HostSecurityManager" /> <type name="HostSecurityManagerOptions" /> <type name="IEvidenceFactory" /> <type name="IPermission" /> <type name="ISecurityElementFactory" /> <type name="ISecurityEncodable" /> <type name="ISecurityPolicyEncodable" /> <type name="IStackWalk" /> <type name="NamedPermissionSet" /> <type name="PartialTrustVisibilityLevel" /> <type name="PermissionListSet" /> <type name="PermissionSet"> <type name="IsSubsetOfType" /> </type> <type name="PermissionSetEnumerator" /> <type name="PermissionSetEnumeratorInternal" /> <type name="PermissionSetTriple" /> <type name="PermissionToken" /> <type name="PermissionTokenFactory" /> <type name="PermissionTokenKeyComparer" /> <type name="PermissionTokenType" /> <type name="PermissionType" /> <type name="PolicyLevelType" /> <type name="PolicyManager" /> <type name="ReadOnlyPermissionSet" /> <type name="ReadOnlyPermissionSetEnumerator" /> <type name="SafeBSTRHandle" /> <type name="SecureString" /> <type name="SecurityContext"> <type name="SecurityContextRunData" /> </type> <type name="SecurityContextDisableFlow" /> <type name="SecurityContextSource" /> <type name="SecurityContextSwitcher" /> <type name="SecurityCriticalAttribute" /> <type name="SecurityCriticalScope" /> <type name="SecurityDocument" /> <type name="SecurityDocumentElement" /> <type name="SecurityElement" /> <type name="SecurityElementType" /> <type name="SecurityException" /> <type name="SecurityManager" /> <type name="SecurityRulesAttribute" /> <type name="SecurityRuleSet" /> <type name="SecurityRuntime" /> <type name="SecuritySafeCriticalAttribute" /> <type name="SecurityState" /> <type name="SecurityTransparentAttribute" /> <type name="SecurityTreatAsSafeAttribute" /> <type name="SecurityZone" /> <type name="SpecialPermissionSetFlag" /> <type name="SuppressUnmanagedCodeSecurityAttribute" /> <type name="UnverifiableCodeAttribute" /> <type name="VerificationException" /> <type name="WindowsImpersonationFlowMode" /> <type name="XmlSyntaxException" /> <AccessControl> <type name="AccessControlActions" /> <type name="AccessControlModification" /> <type name="AccessControlSections" /> <type name="AccessControlType" /> <type name="AccessRule" /> <type name="AccessRule" arity="1" /> <type name="AceEnumerator" /> <type name="AceFlags" /> <type name="AceQualifier" /> <type name="AceType" /> <type name="AuditFlags" /> <type name="AuditRule" /> <type name="AuditRule" arity="1" /> <type name="AuthorizationRule" /> <type name="AuthorizationRuleCollection" /> <type name="CommonAce" /> <type name="CommonAcl" /> <type name="CommonObjectSecurity" /> <type name="CommonSecurityDescriptor" /> <type name="CompoundAce" /> <type name="CompoundAceType" /> <type name="ControlFlags" /> <type name="CryptoKeyAccessRule" /> <type name="CryptoKeyAuditRule" /> <type name="CryptoKeyRights" /> <type name="CryptoKeySecurity" /> <type name="CustomAce" /> <type name="DirectoryObjectSecurity" /> <type name="DirectorySecurity" /> <type name="DiscretionaryAcl" /> <type name="EventWaitHandleAccessRule" /> <type name="EventWaitHandleAuditRule" /> <type name="EventWaitHandleRights" /> <type name="EventWaitHandleSecurity" /> <type name="FileSecurity" /> <type name="FileSystemAccessRule" /> <type name="FileSystemAuditRule" /> <type name="FileSystemRights" /> <type name="FileSystemSecurity" /> <type name="GenericAce" /> <type name="GenericAcl" /> <type name="GenericSecurityDescriptor" /> <type name="InheritanceFlags" /> <type name="KnownAce" /> <type name="MutexAccessRule" /> <type name="MutexAuditRule" /> <type name="MutexRights" /> <type name="MutexSecurity" /> <type name="NativeObjectSecurity"> <type name="ExceptionFromErrorCode" /> </type> <type name="ObjectAccessRule" /> <type name="ObjectAce" /> <type name="ObjectAceFlags" /> <type name="ObjectAuditRule" /> <type name="ObjectSecurity" /> <type name="ObjectSecurity" arity="1" /> <type name="Privilege" /> <type name="PrivilegeNotHeldException" /> <type name="PropagationFlags" /> <type name="QualifiedAce" /> <type name="RawAcl" /> <type name="RawSecurityDescriptor" /> <type name="RegistryAccessRule" /> <type name="RegistryAuditRule" /> <type name="RegistryRights" /> <type name="RegistrySecurity" /> <type name="ResourceType" /> <type name="SecurityInfos" /> <type name="SystemAcl" /> <type name="Win32" /> </AccessControl> <Cryptography> <type name="Aes" /> <type name="AsymmetricAlgorithm" /> <type name="AsymmetricKeyExchangeDeformatter" /> <type name="AsymmetricKeyExchangeFormatter" /> <type name="AsymmetricSignatureDeformatter" /> <type name="AsymmetricSignatureFormatter" /> <type name="CipherMode" /> <type name="Constants" /> <type name="CryptoAPITransform" /> <type name="CryptoAPITransformMode" /> <type name="CryptoConfig" /> <type name="CryptographicException" /> <type name="CryptographicUnexpectedOperationException" /> <type name="CryptoStream" /> <type name="CryptoStreamMode" /> <type name="CspAlgorithmType" /> <type name="CspKeyContainerInfo" /> <type name="CspParameters" /> <type name="CspProviderFlags" /> <type name="DeriveBytes" /> <type name="DES" /> <type name="DESCryptoServiceProvider" /> <type name="DSA" /> <type name="DSACryptoServiceProvider" /> <type name="DSACspObject" /> <type name="DSAParameters" /> <type name="DSASignatureDeformatter" /> <type name="DSASignatureDescription" /> <type name="DSASignatureFormatter" /> <type name="FromBase64Transform" /> <type name="FromBase64TransformMode" /> <type name="HashAlgorithm" /> <type name="HMAC" /> <type name="HMACMD5" /> <type name="HMACRIPEMD160" /> <type name="HMACSHA1" /> <type name="HMACSHA256" /> <type name="HMACSHA384" /> <type name="HMACSHA512" /> <type name="ICryptoTransform" /> <type name="ICspAsymmetricAlgorithm" /> <type name="KeyedHashAlgorithm" /> <type name="KeyNumber" /> <type name="KeySizes" /> <type name="MACTripleDES" /> <type name="MaskGenerationMethod" /> <type name="MD5" /> <type name="MD5CryptoServiceProvider" /> <type name="PaddingMode" /> <type name="PasswordDeriveBytes" /> <type name="PKCS1MaskGenerationMethod" /> <type name="RandomNumberGenerator" /> <type name="RC2" /> <type name="RC2CryptoServiceProvider" /> <type name="Rfc2898DeriveBytes" /> <type name="Rijndael" /> <type name="RijndaelManaged" /> <type name="RijndaelManagedTransform" /> <type name="RijndaelManagedTransformMode" /> <type name="RIPEMD160" /> <type name="RIPEMD160Managed" /> <type name="RNGCryptoServiceProvider" /> <type name="RSA" /> <type name="RSACryptoServiceProvider" /> <type name="RSACspObject" /> <type name="RSAOAEPKeyExchangeDeformatter" /> <type name="RSAOAEPKeyExchangeFormatter" /> <type name="RSAParameters" /> <type name="RSAPKCS1KeyExchangeDeformatter" /> <type name="RSAPKCS1KeyExchangeFormatter" /> <type name="RSAPKCS1SHA1SignatureDescription" /> <type name="RSAPKCS1SignatureDeformatter" /> <type name="RSAPKCS1SignatureFormatter" /> <type name="SafeHashHandle" /> <type name="SafeKeyHandle" /> <type name="SafeProvHandle" /> <type name="SHA1" /> <type name="SHA1CryptoServiceProvider" /> <type name="SHA1Managed" /> <type name="SHA256" /> <type name="SHA256Managed" /> <type name="SHA384" /> <type name="SHA384Managed" /> <type name="SHA512" /> <type name="SHA512Managed" /> <type name="SignatureDescription" /> <type name="SymmetricAlgorithm" /> <type name="TailStream" /> <type name="ToBase64Transform" /> <type name="TripleDES" /> <type name="TripleDESCryptoServiceProvider" /> <type name="Utils" /> <X509Certificates> <type name="SafeCertContextHandle" /> <type name="SafeCertStoreHandle" /> <type name="X509Certificate" /> <type name="X509Constants" /> <type name="X509ContentType" /> <type name="X509KeyStorageFlags" /> <type name="X509Utils" /> </X509Certificates> </Cryptography> <Permissions> <type name="BuiltInPermissionFlag" /> <type name="BuiltInPermissionIndex" /> <type name="CodeAccessSecurityAttribute" /> <type name="EnvironmentPermission" /> <type name="EnvironmentPermissionAccess" /> <type name="EnvironmentPermissionAttribute" /> <type name="EnvironmentStringExpressionSet" /> <type name="FileDialogPermission" /> <type name="FileDialogPermissionAccess" /> <type name="FileDialogPermissionAttribute" /> <type name="FileIOAccess" /> <type name="FileIOPermission" /> <type name="FileIOPermissionAccess" /> <type name="FileIOPermissionAttribute" /> <type name="GacIdentityPermission" /> <type name="GacIdentityPermissionAttribute" /> <type name="HostProtectionAttribute" /> <type name="HostProtectionPermission" /> <type name="HostProtectionResource" /> <type name="IBuiltInPermission" /> <type name="IDRole" /> <type name="IsolatedStorageContainment" /> <type name="IsolatedStorageFilePermission" /> <type name="IsolatedStorageFilePermissionAttribute" /> <type name="IsolatedStoragePermission" /> <type name="IsolatedStoragePermissionAttribute" /> <type name="IUnrestrictedPermission" /> <type name="KeyContainerPermission" /> <type name="KeyContainerPermissionAccessEntry" /> <type name="KeyContainerPermissionAccessEntryCollection" /> <type name="KeyContainerPermissionAccessEntryEnumerator" /> <type name="KeyContainerPermissionAttribute" /> <type name="KeyContainerPermissionFlags" /> <type name="PermissionSetAttribute" /> <type name="PermissionState" /> <type name="PrincipalPermission" /> <type name="PrincipalPermissionAttribute" /> <type name="PublisherIdentityPermission" /> <type name="PublisherIdentityPermissionAttribute" /> <type name="ReflectionPermission" /> <type name="ReflectionPermissionAttribute" /> <type name="ReflectionPermissionFlag" /> <type name="RegistryPermission" /> <type name="RegistryPermissionAccess" /> <type name="RegistryPermissionAttribute" /> <type name="SecurityAction" /> <type name="SecurityAttribute" /> <type name="SecurityPermission" /> <type name="SecurityPermissionAttribute" /> <type name="SecurityPermissionFlag" /> <type name="SiteIdentityPermission" /> <type name="SiteIdentityPermissionAttribute" /> <type name="StrongName2" /> <type name="StrongNameIdentityPermission" /> <type name="StrongNameIdentityPermissionAttribute" /> <type name="StrongNamePublicKeyBlob" /> <type name="UIPermission" /> <type name="UIPermissionAttribute" /> <type name="UIPermissionClipboard" /> <type name="UIPermissionWindow" /> <type name="UrlIdentityPermission" /> <type name="UrlIdentityPermissionAttribute" /> <type name="ZoneIdentityPermission" /> <type name="ZoneIdentityPermissionAttribute" /> </Permissions> <Policy> <type name="AllMembershipCondition" /> <type name="AppDomainEvidenceFactory" /> <type name="ApplicationDirectory" /> <type name="ApplicationDirectoryMembershipCondition" /> <type name="ApplicationSecurityInfo" /> <type name="ApplicationSecurityManager" /> <type name="ApplicationTrust" /> <type name="ApplicationTrustCollection" /> <type name="ApplicationTrustEnumerator" /> <type name="ApplicationVersionMatch" /> <type name="AssemblyEvidenceFactory" /> <type name="CodeConnectAccess" /> <type name="CodeGroup" /> <type name="CodeGroupPositionMarker" /> <type name="CodeGroupStack" /> <type name="CodeGroupStackFrame" /> <type name="ConfigId" /> <type name="Evidence"> <type name="RawEvidenceEnumerator" /> </type> <type name="EvidenceBase" /> <type name="EvidenceTypeDescriptor" /> <type name="EvidenceTypeGenerated" /> <type name="FileCodeGroup" /> <type name="FirstMatchCodeGroup" /> <type name="GacInstalled" /> <type name="GacMembershipCondition" /> <type name="Hash" /> <type name="HashMembershipCondition" /> <type name="IApplicationTrustManager" /> <type name="IConstantMembershipCondition" /> <type name="IDelayEvaluatedEvidence" /> <type name="IIdentityPermissionFactory" /> <type name="ILegacyEvidenceAdapter" /> <type name="IMembershipCondition" /> <type name="IReportMatchMembershipCondition" /> <type name="IRuntimeEvidenceFactory" /> <type name="IUnionSemanticCodeGroup" /> <type name="LegacyEvidenceList" /> <type name="LegacyEvidenceWrapper" /> <type name="NetCodeGroup" /> <type name="PEFileEvidenceFactory" /> <type name="PermissionRequestEvidence" /> <type name="PolicyException" /> <type name="PolicyLevel" /> <type name="PolicyStatement" /> <type name="PolicyStatementAttribute" /> <type name="Publisher" /> <type name="PublisherMembershipCondition" /> <type name="Site" /> <type name="SiteMembershipCondition" /> <type name="StrongName" /> <type name="StrongNameMembershipCondition" /> <type name="TrustManagerContext" /> <type name="TrustManagerUIContext" /> <type name="UnionCodeGroup" /> <type name="Url" /> <type name="UrlMembershipCondition" /> <type name="Zone" /> <type name="ZoneMembershipCondition" /> </Policy> <Principal> <type name="GenericIdentity" /> <type name="GenericPrincipal" /> <type name="IdentifierAuthority" /> <type name="IdentityNotMappedException" /> <type name="IdentityReference" /> <type name="IdentityReferenceCollection" /> <type name="IdentityReferenceEnumerator" /> <type name="IIdentity" /> <type name="ImpersonationQueryResult" /> <type name="IPrincipal" /> <type name="KerbLogonSubmitType" /> <type name="NTAccount" /> <type name="PolicyRights" /> <type name="PrincipalPolicy" /> <type name="SecurityIdentifier" /> <type name="SecurityLogonType" /> <type name="SidNameUse" /> <type name="TokenAccessLevels" /> <type name="TokenImpersonationLevel" /> <type name="TokenInformationClass" /> <type name="TokenType" /> <type name="WellKnownSidType" /> <type name="Win32" /> <type name="WindowsAccountType" /> <type name="WindowsBuiltInRole" /> <type name="WindowsIdentity" /> <type name="WindowsImpersonationContext" /> <type name="WindowsPrincipal" /> <type name="WinSecurityContext" /> </Principal> <Util> <type name="Config" /> <type name="DirectoryString" /> <type name="Hex" /> <type name="LocalSiteString" /> <type name="Parser" /> <type name="QuickCacheEntryType" /> <type name="SiteString" /> <type name="StringExpressionSet" /> <type name="TokenBasedSet" /> <type name="TokenBasedSetEnumerator" /> <type name="Tokenizer"> <type name="ByteTokenEncoding" /> <type name="ITokenReader" /> <type name="StreamTokenReader" /> <type name="StringMaker" /> </type> <type name="TokenizerShortBlock" /> <type name="TokenizerStream" /> <type name="TokenizerStringBlock" /> <type name="URLString" /> <type name="XMLUtil" /> </Util> </Security> <StubHelpers> <type name="AnsiBSTRMarshaler" /> <type name="AnsiCharMarshaler" /> <type name="AsAnyMarshaler"> <type name="BackPropAction" /> </type> <type name="BSTRMarshaler" /> <type name="CleanupWorkList" /> <type name="CleanupWorkListElement" /> <type name="CopyCtorStubCookie" /> <type name="CopyCtorStubDesc" /> <type name="CSTRMarshaler" /> <type name="DateMarshaler" /> <type name="InterfaceMarshaler" /> <type name="MngdNativeArrayMarshaler" /> <type name="MngdRefCustomMarshaler" /> <type name="MngdSafeArrayMarshaler" /> <type name="NativeVariant" /> <type name="ObjectMarshaler" /> <type name="StubHelpers" /> <type name="ValueClassMarshaler" /> <type name="VBByValStrMarshaler" /> <type name="WSTRBufferMarshaler" /> </StubHelpers> <Text> <type name="ASCIIEncoding" /> <type name="BaseCodePageEncoding"> <type name="CodePageDataFileHeader" /> <type name="CodePageHeader" /> <type name="CodePageIndex" /> </type> <type name="CodePageEncoding"> <type name="Decoder" /> </type> <type name="DBCSCodePageEncoding"> <type name="DBCSDecoder" /> </type> <type name="Decoder" /> <type name="DecoderExceptionFallback" /> <type name="DecoderExceptionFallbackBuffer" /> <type name="DecoderFallback" /> <type name="DecoderFallbackBuffer" /> <type name="DecoderFallbackException" /> <type name="DecoderNLS" /> <type name="DecoderReplacementFallback" /> <type name="DecoderReplacementFallbackBuffer" /> <type name="Encoder" /> <type name="EncoderExceptionFallback" /> <type name="EncoderExceptionFallbackBuffer" /> <type name="EncoderFallback" /> <type name="EncoderFallbackBuffer" /> <type name="EncoderFallbackException" /> <type name="EncoderNLS" /> <type name="EncoderReplacementFallback" /> <type name="EncoderReplacementFallbackBuffer" /> <type name="Encoding"> <type name="DefaultDecoder" /> <type name="DefaultEncoder" /> <type name="EncodingByteBuffer" /> <type name="EncodingCharBuffer" /> </type> <type name="EncodingInfo" /> <type name="EncodingNLS" /> <type name="EUCJPEncoding" /> <type name="ExtendedNormalizationForms" /> <type name="GB18030Encoding"> <type name="GB18030Decoder" /> </type> <type name="InternalDecoderBestFitFallback" /> <type name="InternalDecoderBestFitFallbackBuffer" /> <type name="InternalEncoderBestFitFallback" /> <type name="InternalEncoderBestFitFallbackBuffer" /> <type name="ISCIIEncoding"> <type name="ISCIIDecoder" /> <type name="ISCIIEncoder" /> </type> <type name="ISO2022Encoding"> <type name="ISO2022Decoder" /> <type name="ISO2022Encoder" /> <type name="ISO2022Modes" /> </type> <type name="Latin1Encoding" /> <type name="MLangCodePageEncoding"> <type name="MLangDecoder" /> <type name="MLangEncoder" /> </type> <type name="Normalization" /> <type name="NormalizationForm" /> <type name="SBCSCodePageEncoding" /> <type name="StringBuilder" /> <type name="SurrogateEncoder" /> <type name="UnicodeEncoding" /> <type name="UTF32Encoding"> <type name="UTF32Decoder" /> </type> <type name="UTF7Encoding"> <type name="DecoderUTF7Fallback" /> <type name="DecoderUTF7FallbackBuffer" /> </type> <type name="UTF8Encoding"> <type name="UTF8Decoder" /> <type name="UTF8Encoder" /> </type> </Text> <Threading> <type name="AbandonedMutexException" /> <type name="ApartmentState" /> <type name="AsyncFlowControl" /> <type name="AutoResetEvent" /> <type name="CancellationCallbackCoreWorkArguments" /> <type name="CancellationCallbackInfo" /> <type name="CancellationToken" /> <type name="CancellationTokenRegistration" /> <type name="CancellationTokenSource" /> <type name="CdsSyncEtwBCLProvider" /> <type name="CompressedStack"> <type name="CompressedStackRunData" /> </type> <type name="CompressedStackSwitcher" /> <type name="ContextCallback" /> <type name="CountdownEvent" /> <type name="DomainCompressedStack" /> <type name="EventResetMode" /> <type name="EventWaitHandle" /> <type name="ExceptionType" /> <type name="ExecutionContext"> <type name="CaptureOptions" /> <type name="ExecutionContextRunData" /> </type> <type name="ExecutionContextSwitcher" /> <type name="HostExecutionContext" /> <type name="HostExecutionContextManager" /> <type name="HostExecutionContextSwitcher" /> <type name="Interlocked" /> <type name="InternalCrossContextDelegate" /> <type name="IOCompletionCallback" /> <type name="IThreadPoolWorkItem" /> <type name="IUnknownSafeHandle" /> <type name="LazyInitializer" /> <type name="LazyThreadSafetyMode" /> <type name="LockCookie" /> <type name="LockRecursionException" /> <type name="ManualResetEvent" /> <type name="ManualResetEventSlim" /> <type name="Monitor" /> <type name="Mutex"> <type name="MutexCleanupInfo" /> <type name="MutexTryCodeHelper" /> </type> <type name="NativeOverlapped" /> <type name="Overlapped" /> <type name="OverlappedData" /> <type name="OverlappedDataCache" /> <type name="OverlappedDataCacheLine" /> <type name="ParameterizedThreadStart" /> <type name="PlatformHelper" /> <type name="QueueUserWorkItemCallback" /> <type name="ReaderWriterLock" /> <type name="RegisteredWaitHandle" /> <type name="RegisteredWaitHandleSafe" /> <type name="SafeCompressedStackHandle" /> <type name="SemaphoreFullException" /> <type name="SemaphoreSlim" /> <type name="SendOrPostCallback" /> <type name="SparselyPopulatedArray" arity="1" /> <type name="SparselyPopulatedArrayAddInfo" arity="1" /> <type name="SparselyPopulatedArrayFragment" arity="1" /> <type name="SpinLock"> <type name="SystemThreading_SpinLockDebugView" /> </type> <type name="SpinWait" /> <type name="StackCrawlMark" /> <type name="SynchronizationContext" /> <type name="SynchronizationContextProperties" /> <type name="SynchronizationContextSwitcher" /> <type name="SynchronizationLockException" /> <type name="SystemThreading_ThreadLocalDebugView" arity="1" /> <type name="Thread" /> <type name="ThreadAbortException" /> <type name="ThreadHandle" /> <type name="ThreadHelper" /> <type name="ThreadInterruptedException" /> <type name="ThreadLocal" arity="1" /> <type name="ThreadLocalGlobalCounter" /> <type name="ThreadPool" /> <type name="ThreadPoolGlobals" /> <type name="ThreadPoolRequestQueue" /> <type name="ThreadPoolWorkQueue"> <type name="QueueSegment" /> <type name="SparseArray" arity="1" /> <type name="WorkStealingQueue" /> </type> <type name="ThreadPoolWorkQueueThreadLocals" /> <type name="ThreadPriority" /> <type name="ThreadStart" /> <type name="ThreadStartException" /> <type name="ThreadState" /> <type name="ThreadStateException" /> <type name="Timeout" /> <type name="Timer" /> <type name="TimerBase" /> <type name="TimerCallback" /> <type name="TplEtwProvider"> <type name="ForkJoinOperationType" /> </type> <type name="WaitCallback" /> <type name="WaitDelegate" /> <type name="WaitHandle" /> <type name="WaitHandleCannotBeOpenedException" /> <type name="WaitOrTimerCallback" /> <type name="_IOCompletionCallback" /> <type name="_ThreadPoolWaitCallback" /> <type name="_ThreadPoolWaitOrTimerCallback" /> <type name="_TimerCallback" /> <Tasks> <type name="IndexRange" /> <type name="InternalTaskOptions" /> <type name="Parallel"> <type name="LoopTimer" /> </type> <type name="ParallelForReplicaTask" /> <type name="ParallelForReplicatingTask" /> <type name="ParallelLoopResult" /> <type name="ParallelLoopState" /> <type name="ParallelLoopState32" /> <type name="ParallelLoopState64" /> <type name="ParallelLoopStateFlags" /> <type name="ParallelLoopStateFlags32" /> <type name="ParallelLoopStateFlags64" /> <type name="ParallelOptions" /> <type name="RangeManager" /> <type name="RangeWorker" /> <type name="Shared" arity="1" /> <type name="StackGuard" /> <type name="SynchronizationContextTaskScheduler" /> <type name="SystemThreadingTasks_FutureDebugView" arity="1" /> <type name="SystemThreadingTasks_TaskDebugView" /> <type name="Task"> <type name="ContingentProperties" /> <type name="TaskContinuation" /> </type> <type name="Task" arity="1" /> <type name="TaskCanceledException" /> <type name="TaskCompletionSource" arity="1" /> <type name="TaskContinuationOptions" /> <type name="TaskCreationOptions" /> <type name="TaskExceptionHolder" /> <type name="TaskFactory" /> <type name="TaskFactory" arity="1" /> <type name="TaskScheduler"> <type name="SystemThreadingTasks_TaskSchedulerDebugView" /> </type> <type name="TaskSchedulerException" /> <type name="TaskStatus" /> <type name="ThreadPoolTaskScheduler" /> <type name="UnobservedTaskExceptionEventArgs" /> </Tasks> </Threading> </System> </Global>
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Core/CodeAnalysisTest/CachingLookupTests.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 Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { /// <summary> /// Tests for CachingLookup. /// </summary> public class CachingLookupTests { private readonly Random _randomCaseGenerator = new Random(17); private int[] RandomNumbers(int length, int seed) { Random rand = new Random(seed); int[] result = new int[length]; for (int i = 0; i < length; ++i) { result[i] = rand.Next(100, ((length / 10) + 4) * 100); } return result; } private HashSet<string> Keys(int[] numbers, bool randomCase, IEqualityComparer<string> comparer) { var keys = new HashSet<string>(comparer); foreach (var n in numbers) { keys.Add(GetKey(n, randomCase)); } return keys; } private string GetKey(int number, bool randomCase) { if (randomCase) { bool upper = _randomCaseGenerator.Next(2) == 0; return (upper ? "AA" : "aa") + Right2Chars(number.ToString()); } else { return "AA" + Right2Chars(number.ToString()); } } private ImmutableArray<int> Values(string key, int[] numbers, bool ignoreCase) { return (from n in numbers where string.Equals(GetKey(n, ignoreCase), key, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) select n).ToArray().AsImmutableOrNull(); } private ILookup<string, int> CreateLookup(int[] numbers, bool randomCase) { if (randomCase) { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.OrdinalIgnoreCase); } else { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.Ordinal); } } private string Right2Chars(string s) { return s.Substring(s.Length - 2); } private void CheckEqualEnumerable<T>(IEnumerable<T> e1, IEnumerable<T> e2) { List<T> l1 = e1.ToList(); List<T> l2 = e2.ToList(); Assert.Equal(l1.Count, l2.Count); foreach (T item in l1) { Assert.Contains(item, l2); } foreach (T item in l2) { Assert.Contains(item, l1); } } private void CompareLookups1(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in keys) { Assert.Equal(look1.Contains(k), look2.Contains(k)); CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in new string[] { "goo", "bar", "banana", "flibber" }) { Assert.False(look1.Contains(k)); Assert.False(look2.Contains(k)); Assert.Empty(look1[k]); Assert.Empty(look2[k]); } } private void CompareLookups2(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } private void CompareLookups2(CachingDictionary<string, int> look1, ILookup<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } [Fact] public void CachingLookupCorrectResults() { StringComparer comparer = StringComparer.Ordinal; int[] numbers = RandomNumbers(200, 11234); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, false); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); } [Fact] public void CachingLookupCaseInsensitive() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(300, 719); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } [Fact] public void CachingLookupCaseInsensitiveNoCacheMissingKeys() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } // Ensure that we are called back exactly once per key. [Fact] public void CallExactlyOncePerKey() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } HashSet<string> lookedUp = new HashSet<string>(comparer); bool askedForKeys = false; var look1 = new CachingDictionary<string, int>(s => { Assert.False(lookedUp.Contains(s)); lookedUp.Add(s); return dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(); }, (c) => { Assert.False(askedForKeys); askedForKeys = true; return Keys(numbers, true, comparer: c); }, comparer); string key1 = GetKey(numbers[0], false); string key2 = GetKey(numbers[1], false); string key3 = GetKey(numbers[2], false); ImmutableArray<int> retval; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; } } }
// 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 Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { /// <summary> /// Tests for CachingLookup. /// </summary> public class CachingLookupTests { private readonly Random _randomCaseGenerator = new Random(17); private int[] RandomNumbers(int length, int seed) { Random rand = new Random(seed); int[] result = new int[length]; for (int i = 0; i < length; ++i) { result[i] = rand.Next(100, ((length / 10) + 4) * 100); } return result; } private HashSet<string> Keys(int[] numbers, bool randomCase, IEqualityComparer<string> comparer) { var keys = new HashSet<string>(comparer); foreach (var n in numbers) { keys.Add(GetKey(n, randomCase)); } return keys; } private string GetKey(int number, bool randomCase) { if (randomCase) { bool upper = _randomCaseGenerator.Next(2) == 0; return (upper ? "AA" : "aa") + Right2Chars(number.ToString()); } else { return "AA" + Right2Chars(number.ToString()); } } private ImmutableArray<int> Values(string key, int[] numbers, bool ignoreCase) { return (from n in numbers where string.Equals(GetKey(n, ignoreCase), key, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) select n).ToArray().AsImmutableOrNull(); } private ILookup<string, int> CreateLookup(int[] numbers, bool randomCase) { if (randomCase) { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.OrdinalIgnoreCase); } else { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.Ordinal); } } private string Right2Chars(string s) { return s.Substring(s.Length - 2); } private void CheckEqualEnumerable<T>(IEnumerable<T> e1, IEnumerable<T> e2) { List<T> l1 = e1.ToList(); List<T> l2 = e2.ToList(); Assert.Equal(l1.Count, l2.Count); foreach (T item in l1) { Assert.Contains(item, l2); } foreach (T item in l2) { Assert.Contains(item, l1); } } private void CompareLookups1(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in keys) { Assert.Equal(look1.Contains(k), look2.Contains(k)); CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in new string[] { "goo", "bar", "banana", "flibber" }) { Assert.False(look1.Contains(k)); Assert.False(look2.Contains(k)); Assert.Empty(look1[k]); Assert.Empty(look2[k]); } } private void CompareLookups2(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } private void CompareLookups2(CachingDictionary<string, int> look1, ILookup<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } [Fact] public void CachingLookupCorrectResults() { StringComparer comparer = StringComparer.Ordinal; int[] numbers = RandomNumbers(200, 11234); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, false); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); } [Fact] public void CachingLookupCaseInsensitive() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(300, 719); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } [Fact] public void CachingLookupCaseInsensitiveNoCacheMissingKeys() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } // Ensure that we are called back exactly once per key. [Fact] public void CallExactlyOncePerKey() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } HashSet<string> lookedUp = new HashSet<string>(comparer); bool askedForKeys = false; var look1 = new CachingDictionary<string, int>(s => { Assert.False(lookedUp.Contains(s)); lookedUp.Add(s); return dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(); }, (c) => { Assert.False(askedForKeys); askedForKeys = true; return Keys(numbers, true, comparer: c); }, comparer); string key1 = GetKey(numbers[0], false); string key2 = GetKey(numbers[1], false); string key3 = GetKey(numbers[2], false); ImmutableArray<int> retval; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Tools/AnalyzerRunner/AssemblyLoader.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.Reflection; using Microsoft.CodeAnalysis; namespace AnalyzerRunner { internal class AssemblyLoader : IAnalyzerAssemblyLoader { public static AssemblyLoader Instance = new AssemblyLoader(); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { return Assembly.LoadFrom(fullPath); } } }
// 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.Reflection; using Microsoft.CodeAnalysis; namespace AnalyzerRunner { internal class AssemblyLoader : IAnalyzerAssemblyLoader { public static AssemblyLoader Instance = new AssemblyLoader(); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { return Assembly.LoadFrom(fullPath); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation`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. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Specifies that an option should be read from an .editorconfig file. /// </summary> internal sealed class EditorConfigStorageLocation<T> : OptionStorageLocation2, IEditorConfigStorageLocation2 { public string KeyName { get; } private readonly Func<string, Type, Optional<T>> _parseValue; private readonly Func<T, OptionSet, string?> _getEditorConfigStringForValue; public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(value)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<OptionSet, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(optionSet)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, OptionSet, string> getEditorConfigStringForValue) { if (parseValue == null) { throw new ArgumentNullException(nameof(parseValue)); } KeyName = keyName ?? throw new ArgumentNullException(nameof(keyName)); // If we're explicitly given a parsing function we can throw away the type when parsing _parseValue = (s, type) => parseValue(s); _getEditorConfigStringForValue = getEditorConfigStringForValue ?? throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? result) { if (rawOptions.TryGetValue(KeyName, out var value) && value is object) { var ret = TryGetOption(value, type, out var typedResult); result = typedResult; return ret; } result = null; return false; } internal bool TryGetOption(string value, Type type, [MaybeNullWhen(false)] out T result) { var optionalValue = _parseValue(value, type); if (optionalValue.HasValue) { result = optionalValue.Value; return result != null; } else { result = default!; return false; } } /// <summary> /// Gets the editorconfig string representation for this storage location. /// </summary> public string GetEditorConfigStringValue(T value, OptionSet optionSet) { var editorConfigStringForValue = _getEditorConfigStringForValue(value, optionSet); RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(editorConfigStringForValue)); Debug.Assert(editorConfigStringForValue.All(ch => !(char.IsWhiteSpace(ch) || char.IsUpper(ch)))); return editorConfigStringForValue; } string IEditorConfigStorageLocation2.GetEditorConfigString(object? value, OptionSet optionSet) => $"{KeyName} = {((IEditorConfigStorageLocation2)this).GetEditorConfigStringValue(value, optionSet)}"; string IEditorConfigStorageLocation2.GetEditorConfigStringValue(object? value, OptionSet optionSet) { T typedValue; if (value is ICodeStyleOption codeStyleOption) { typedValue = (T)codeStyleOption.AsCodeStyleOption<T>(); } else { typedValue = (T)value!; } return GetEditorConfigStringValue(typedValue, optionSet); } } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Specifies that an option should be read from an .editorconfig file. /// </summary> internal sealed class EditorConfigStorageLocation<T> : OptionStorageLocation2, IEditorConfigStorageLocation2 { public string KeyName { get; } private readonly Func<string, Type, Optional<T>> _parseValue; private readonly Func<T, OptionSet, string?> _getEditorConfigStringForValue; public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(value)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<OptionSet, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(optionSet)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, OptionSet, string> getEditorConfigStringForValue) { if (parseValue == null) { throw new ArgumentNullException(nameof(parseValue)); } KeyName = keyName ?? throw new ArgumentNullException(nameof(keyName)); // If we're explicitly given a parsing function we can throw away the type when parsing _parseValue = (s, type) => parseValue(s); _getEditorConfigStringForValue = getEditorConfigStringForValue ?? throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? result) { if (rawOptions.TryGetValue(KeyName, out var value) && value is object) { var ret = TryGetOption(value, type, out var typedResult); result = typedResult; return ret; } result = null; return false; } internal bool TryGetOption(string value, Type type, [MaybeNullWhen(false)] out T result) { var optionalValue = _parseValue(value, type); if (optionalValue.HasValue) { result = optionalValue.Value; return result != null; } else { result = default!; return false; } } /// <summary> /// Gets the editorconfig string representation for this storage location. /// </summary> public string GetEditorConfigStringValue(T value, OptionSet optionSet) { var editorConfigStringForValue = _getEditorConfigStringForValue(value, optionSet); RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(editorConfigStringForValue)); Debug.Assert(editorConfigStringForValue.All(ch => !(char.IsWhiteSpace(ch) || char.IsUpper(ch)))); return editorConfigStringForValue; } string IEditorConfigStorageLocation2.GetEditorConfigString(object? value, OptionSet optionSet) => $"{KeyName} = {((IEditorConfigStorageLocation2)this).GetEditorConfigStringValue(value, optionSet)}"; string IEditorConfigStorageLocation2.GetEditorConfigStringValue(object? value, OptionSet optionSet) { T typedValue; if (value is ICodeStyleOption codeStyleOption) { typedValue = (T)codeStyleOption.AsCodeStyleOption<T>(); } else { typedValue = (T)value!; } return GetEditorConfigStringValue(typedValue, optionSet); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Shared/RuntimeOptions.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.Options; namespace Microsoft.CodeAnalysis.Shared.Options { /// <summary> /// Options that aren't persisted. options here will be reset to default on new process. /// </summary> internal static class RuntimeOptions { public static readonly Option<bool> BackgroundAnalysisSuspendedInfoBarShown = new(nameof(RuntimeOptions), "FullSolutionAnalysisInfoBarShown", defaultValue: 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 Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Options { /// <summary> /// Options that aren't persisted. options here will be reset to default on new process. /// </summary> internal static class RuntimeOptions { public static readonly Option<bool> BackgroundAnalysisSuspendedInfoBarShown = new(nameof(RuntimeOptions), "FullSolutionAnalysisInfoBarShown", defaultValue: false); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Contains methods related to synthesizing bound nodes in initial binding /// form that needs lowering, primarily method bodies for compiler-generated methods. /// </summary> internal static class MethodBodySynthesizer { internal static ImmutableArray<BoundStatement> ConstructScriptConstructorBody( BoundStatement loweredBody, MethodSymbol constructor, SynthesizedSubmissionFields previousSubmissionFields, CSharpCompilation compilation) { // Script field initializers have to be emitted after the call to the base constructor because they can refer to "this" instance. // // Unlike regular field initializers, initializers of global script variables can access "this" instance. // If the base class had a constructor that initializes its state a global variable would access partially initialized object. // For this reason Script class must always derive directly from a class that has no state (System.Object). SyntaxNode syntax = loweredBody.Syntax; // base constructor call: Debug.Assert((object)constructor.ContainingType.BaseTypeNoUseSiteDiagnostics == null || constructor.ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); var objectType = constructor.ContainingAssembly.GetSpecialType(SpecialType.System_Object); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; BoundStatement baseConstructorCall = new BoundExpressionStatement(syntax, new BoundCall(syntax, receiverOpt: receiver, method: objectType.InstanceConstructors[0], arguments: ImmutableArray<BoundExpression>.Empty, argumentNamesOpt: ImmutableArray<string>.Empty, argumentRefKindsOpt: ImmutableArray<RefKind>.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: BitVector.Empty, resultKind: LookupResultKind.Viable, type: objectType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; var statements = ArrayBuilder<BoundStatement>.GetInstance(); statements.Add(baseConstructorCall); if (constructor.IsSubmissionConstructor) { // submission initialization: MakeSubmissionInitialization(statements, syntax, constructor, previousSubmissionFields, compilation); } statements.Add(loweredBody); return statements.ToImmutableAndFree(); } /// <summary> /// Generates a submission initialization part of a Script type constructor that represents an interactive submission. /// </summary> /// <remarks> /// The constructor takes a parameter of type Microsoft.CodeAnalysis.Scripting.Session - the session reference. /// It adds the object being constructed into the session by calling Microsoft.CSharp.RuntimeHelpers.SessionHelpers.SetSubmission, /// and retrieves strongly typed references on all previous submission script classes whose members are referenced by this submission. /// The references are stored to fields of the submission (<paramref name="synthesizedFields"/>). /// </remarks> private static void MakeSubmissionInitialization( ArrayBuilder<BoundStatement> statements, SyntaxNode syntax, MethodSymbol submissionConstructor, SynthesizedSubmissionFields synthesizedFields, CSharpCompilation compilation) { Debug.Assert(submissionConstructor.ParameterCount == 1); var submissionArrayReference = new BoundParameter(syntax, submissionConstructor.Parameters[0]) { WasCompilerGenerated = true }; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var thisReference = new BoundThisReference(syntax, submissionConstructor.ContainingType) { WasCompilerGenerated = true }; var slotIndex = compilation.GetSubmissionSlotIndex(); Debug.Assert(slotIndex >= 0); // <submission_array>[<slot_index] = this; statements.Add(new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(slotIndex), intType) { WasCompilerGenerated = true }), objectType) { WasCompilerGenerated = true }, thisReference, false, thisReference.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); var hostObjectField = synthesizedFields.GetHostObjectField(); if ((object)hostObjectField != null) { // <host_object> = (<host_object_type>)<submission_array>[0] statements.Add( new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, thisReference, hostObjectField, ConstantValue.NotAvailable) { WasCompilerGenerated = true }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(0), intType) { WasCompilerGenerated = true }), objectType), Conversion.ExplicitReference, false, explicitCastInCode: true, conversionGroupOpt: null, ConstantValue.NotAvailable, hostObjectField.Type ), hostObjectField.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); } foreach (var field in synthesizedFields.FieldSymbols) { var targetScriptType = (ImplicitNamedTypeSymbol)field.Type; var targetSubmissionIndex = targetScriptType.DeclaringCompilation.GetSubmissionSlotIndex(); Debug.Assert(targetSubmissionIndex >= 0); // this.<field> = (<target_script_type>)<submission_array>[<target_submission_index>]; statements.Add( new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(targetSubmissionIndex), intType) { WasCompilerGenerated = true }), objectType) { WasCompilerGenerated = true }, Conversion.ExplicitReference, false, explicitCastInCode: true, conversionGroupOpt: null, ConstantValue.NotAvailable, targetScriptType ), targetScriptType ) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); } } /// <summary> /// Construct a body for an auto-property accessor (updating or returning the backing field). /// </summary> internal static BoundBlock ConstructAutoPropertyAccessorBody(SourceMemberMethodSymbol accessor) { Debug.Assert(accessor.MethodKind == MethodKind.PropertyGet || accessor.MethodKind == MethodKind.PropertySet); var property = (SourcePropertySymbolBase)accessor.AssociatedSymbol; CSharpSyntaxNode syntax = property.CSharpSyntaxNode; BoundExpression thisReference = null; if (!accessor.IsStatic) { var thisSymbol = accessor.ThisParameter; thisReference = new BoundThisReference(syntax, thisSymbol.Type) { WasCompilerGenerated = true }; } var field = property.BackingField; var fieldAccess = new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; BoundStatement statement; if (accessor.MethodKind == MethodKind.PropertyGet) { statement = new BoundReturnStatement(accessor.SyntaxNode, RefKind.None, fieldAccess); } else { Debug.Assert(accessor.MethodKind == MethodKind.PropertySet); var parameter = accessor.Parameters[0]; statement = new BoundExpressionStatement( accessor.SyntaxNode, new BoundAssignmentOperator( syntax, fieldAccess, new BoundParameter(syntax, parameter) { WasCompilerGenerated = true }, property.Type) { WasCompilerGenerated = true }); } return BoundBlock.SynthesizedNoLocals(syntax, statement); } /// <summary> /// Generate an accessor for a field-like event. /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(eventSymbol.HasAssociatedField); return eventSymbol.IsWindowsRuntimeEvent ? ConstructFieldLikeEventAccessorBody_WinRT(eventSymbol, isAddMethod, compilation, diagnostics) : ConstructFieldLikeEventAccessorBody_Regular(eventSymbol, isAddMethod, compilation, diagnostics); } /// <summary> /// Generate a thread-safe accessor for a WinRT field-like event. /// /// Add: /// return EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddEventHandler(value); /// /// Remove: /// EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveEventHandler(value); /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody_WinRT(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode; MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; Debug.Assert((object)accessor != null); FieldSymbol field = eventSymbol.AssociatedField; Debug.Assert((object)field != null); NamedTypeSymbol fieldType = (NamedTypeSymbol)field.Type; Debug.Assert(fieldType.Name == "EventRegistrationTokenTable"); MethodSymbol getOrCreateMethod = (MethodSymbol)Binder.GetWellKnownTypeMember( compilation, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, diagnostics, syntax: syntax); if ((object)getOrCreateMethod == null) { Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); return null; } getOrCreateMethod = getOrCreateMethod.AsMember(fieldType); WellKnownMember processHandlerMember = isAddMethod ? WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler : WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler; MethodSymbol processHandlerMethod = (MethodSymbol)Binder.GetWellKnownTypeMember( compilation, processHandlerMember, diagnostics, syntax: syntax); if ((object)processHandlerMethod == null) { Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); return null; } processHandlerMethod = processHandlerMethod.AsMember(fieldType); // _tokenTable BoundFieldAccess fieldAccess = new BoundFieldAccess( syntax, field.IsStatic ? null : new BoundThisReference(syntax, accessor.ThisParameter.Type), field, constantValueOpt: null) { WasCompilerGenerated = true }; // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable) BoundCall getOrCreateCall = BoundCall.Synthesized( syntax, receiverOpt: null, method: getOrCreateMethod, arg0: fieldAccess); // value BoundParameter parameterAccess = new BoundParameter( syntax, accessor.Parameters[0]); // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value) // or RemoveHandler BoundCall processHandlerCall = BoundCall.Synthesized( syntax, receiverOpt: getOrCreateCall, method: processHandlerMethod, arg0: parameterAccess); if (isAddMethod) { // { // return EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value); // } BoundStatement returnStatement = BoundReturnStatement.Synthesized(syntax, RefKind.None, processHandlerCall); return BoundBlock.SynthesizedNoLocals(syntax, returnStatement); } else { // { // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveHandler(value); // return; // } BoundStatement callStatement = new BoundExpressionStatement(syntax, processHandlerCall); BoundStatement returnStatement = new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null); return BoundBlock.SynthesizedNoLocals(syntax, callStatement, returnStatement); } } /// <summary> /// Generate a thread-safe accessor for a regular field-like event. /// /// DelegateType tmp0 = _event; //backing field /// DelegateType tmp1; /// DelegateType tmp2; /// do { /// tmp1 = tmp0; /// tmp2 = (DelegateType)Delegate.Combine(tmp1, value); //Remove for -= /// tmp0 = Interlocked.CompareExchange&lt;DelegateType&gt;(ref _event, tmp2, tmp1); /// } while ((object)tmp0 != (object)tmp1); /// /// Note, if System.Threading.Interlocked.CompareExchange&lt;T&gt; is not available, /// we emit the following code and mark the method Synchronized (unless it is a struct). /// /// _event = (DelegateType)Delegate.Combine(_event, value); //Remove for -= /// /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody_Regular(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode; TypeSymbol delegateType = eventSymbol.Type; MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; ParameterSymbol thisParameter = accessor.ThisParameter; TypeSymbol boolType = compilation.GetSpecialType(SpecialType.System_Boolean); SpecialMember updateMethodId = isAddMethod ? SpecialMember.System_Delegate__Combine : SpecialMember.System_Delegate__Remove; MethodSymbol updateMethod = (MethodSymbol)compilation.GetSpecialTypeMember(updateMethodId); BoundStatement @return = new BoundReturnStatement(syntax, refKind: RefKind.None, expressionOpt: null) { WasCompilerGenerated = true }; if (updateMethod == null) { MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(updateMethodId); diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), syntax.Location)); return BoundBlock.SynthesizedNoLocals(syntax, @return); } Binder.ReportUseSite(updateMethod, diagnostics, syntax); BoundThisReference fieldReceiver = eventSymbol.IsStatic ? null : new BoundThisReference(syntax, thisParameter.Type) { WasCompilerGenerated = true }; BoundFieldAccess boundBackingField = new BoundFieldAccess(syntax, receiver: fieldReceiver, fieldSymbol: eventSymbol.AssociatedField, constantValueOpt: null) { WasCompilerGenerated = true }; BoundParameter boundParameter = new BoundParameter(syntax, parameterSymbol: accessor.Parameters[0]) { WasCompilerGenerated = true }; BoundExpression delegateUpdate; MethodSymbol compareExchangeMethod = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T); if ((object)compareExchangeMethod == null) { // (DelegateType)Delegate.Combine(_event, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // _event = (DelegateType)Delegate.Combine(_event, value); BoundStatement eventUpdate = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundBackingField, right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; return BoundBlock.SynthesizedNoLocals(syntax, statements: ImmutableArray.Create<BoundStatement>( eventUpdate, @return)); } compareExchangeMethod = compareExchangeMethod.Construct(ImmutableArray.Create<TypeSymbol>(delegateType)); Binder.ReportUseSite(compareExchangeMethod, diagnostics, syntax); GeneratedLabelSymbol loopLabel = new GeneratedLabelSymbol("loop"); const int numTemps = 3; LocalSymbol[] tmps = new LocalSymbol[numTemps]; BoundLocal[] boundTmps = new BoundLocal[numTemps]; for (int i = 0; i < numTemps; i++) { tmps[i] = new SynthesizedLocal(accessor, TypeWithAnnotations.Create(delegateType), SynthesizedLocalKind.LoweringTemp); boundTmps[i] = new BoundLocal(syntax, tmps[i], null, delegateType) { WasCompilerGenerated = true }; } // tmp0 = _event; BoundStatement tmp0Init = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: boundBackingField, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // LOOP: BoundStatement loopStart = new BoundLabelStatement(syntax, label: loopLabel) { WasCompilerGenerated = true }; // tmp1 = tmp0; BoundStatement tmp1Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[1], right: boundTmps[0], type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // (DelegateType)Delegate.Combine(tmp1, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundTmps[1], boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // tmp2 = (DelegateType)Delegate.Combine(tmp1, value); BoundStatement tmp2Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[2], right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1) BoundExpression compareExchange = BoundCall.Synthesized(syntax, receiverOpt: null, method: compareExchangeMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundTmps[2], boundTmps[1])); // tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1); BoundStatement tmp0Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: compareExchange, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // tmp0 == tmp1 // i.e. exit when they are equal, jump to start otherwise BoundExpression loopExitCondition = new BoundBinaryOperator(syntax, operatorKind: BinaryOperatorKind.ObjectEqual, left: boundTmps[0], right: boundTmps[1], constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: boolType) { WasCompilerGenerated = true }; // branchfalse (tmp0 == tmp1) LOOP BoundStatement loopEnd = new BoundConditionalGoto(syntax, condition: loopExitCondition, jumpIfTrue: false, label: loopLabel) { WasCompilerGenerated = true }; return new BoundBlock(syntax, locals: tmps.AsImmutable(), statements: ImmutableArray.Create<BoundStatement>( tmp0Init, loopStart, tmp1Update, tmp2Update, tmp0Update, loopEnd, @return)) { WasCompilerGenerated = true }; } internal static BoundBlock ConstructDestructorBody(MethodSymbol method, BoundBlock block) { var syntax = block.Syntax; Debug.Assert(method.MethodKind == MethodKind.Destructor); Debug.Assert(syntax.Kind() == SyntaxKind.Block || syntax.Kind() == SyntaxKind.ArrowExpressionClause); // If this is a destructor and a base type has a Finalize method (see GetBaseTypeFinalizeMethod for exact // requirements), then we need to call that method in a finally block. Otherwise, just return block as-is. // NOTE: the Finalize method need not be a destructor or be overridden by the current method. MethodSymbol baseTypeFinalize = GetBaseTypeFinalizeMethod(method); if ((object)baseTypeFinalize != null) { BoundStatement baseFinalizeCall = new BoundExpressionStatement( syntax, BoundCall.Synthesized( syntax, new BoundBaseReference( syntax, method.ContainingType) { WasCompilerGenerated = true }, baseTypeFinalize)) { WasCompilerGenerated = true }; if (syntax.Kind() == SyntaxKind.Block) { //sequence point to mimic Dev10 baseFinalizeCall = new BoundSequencePointWithSpan( syntax, baseFinalizeCall, ((BlockSyntax)syntax).CloseBraceToken.Span); } return new BoundBlock( syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundStatement>( new BoundTryStatement( syntax, block, ImmutableArray<BoundCatchBlock>.Empty, new BoundBlock( syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundStatement>( baseFinalizeCall) ) { WasCompilerGenerated = true } ) { WasCompilerGenerated = true })); } return block; } /// <summary> /// Look for a base type method named "Finalize" that is protected (or protected internal), has no parameters, /// and returns void. It doesn't need to be virtual or a destructor. /// </summary> /// <remarks> /// You may assume that this would share code and logic with PEMethodSymbol.OverridesRuntimeFinalizer, /// but FUNCBRECCS::bindDestructor has its own loop that performs these checks (differently). /// </remarks> private static MethodSymbol GetBaseTypeFinalizeMethod(MethodSymbol method) { NamedTypeSymbol baseType = method.ContainingType.BaseTypeNoUseSiteDiagnostics; while ((object)baseType != null) { foreach (Symbol member in baseType.GetMembers(WellKnownMemberNames.DestructorName)) { if (member.Kind == SymbolKind.Method) { MethodSymbol baseTypeMethod = (MethodSymbol)member; Accessibility accessibility = baseTypeMethod.DeclaredAccessibility; if ((accessibility == Accessibility.ProtectedOrInternal || accessibility == Accessibility.Protected) && baseTypeMethod.ParameterCount == 0 && baseTypeMethod.Arity == 0 && // NOTE: the native compiler doesn't check this, so it broken IL. baseTypeMethod.ReturnsVoid) // NOTE: not checking for virtual { return baseTypeMethod; } } } baseType = baseType.BaseTypeNoUseSiteDiagnostics; } return null; } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Contains methods related to synthesizing bound nodes in initial binding /// form that needs lowering, primarily method bodies for compiler-generated methods. /// </summary> internal static class MethodBodySynthesizer { internal static ImmutableArray<BoundStatement> ConstructScriptConstructorBody( BoundStatement loweredBody, MethodSymbol constructor, SynthesizedSubmissionFields previousSubmissionFields, CSharpCompilation compilation) { // Script field initializers have to be emitted after the call to the base constructor because they can refer to "this" instance. // // Unlike regular field initializers, initializers of global script variables can access "this" instance. // If the base class had a constructor that initializes its state a global variable would access partially initialized object. // For this reason Script class must always derive directly from a class that has no state (System.Object). SyntaxNode syntax = loweredBody.Syntax; // base constructor call: Debug.Assert((object)constructor.ContainingType.BaseTypeNoUseSiteDiagnostics == null || constructor.ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); var objectType = constructor.ContainingAssembly.GetSpecialType(SpecialType.System_Object); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; BoundStatement baseConstructorCall = new BoundExpressionStatement(syntax, new BoundCall(syntax, receiverOpt: receiver, method: objectType.InstanceConstructors[0], arguments: ImmutableArray<BoundExpression>.Empty, argumentNamesOpt: ImmutableArray<string>.Empty, argumentRefKindsOpt: ImmutableArray<RefKind>.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: BitVector.Empty, resultKind: LookupResultKind.Viable, type: objectType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; var statements = ArrayBuilder<BoundStatement>.GetInstance(); statements.Add(baseConstructorCall); if (constructor.IsSubmissionConstructor) { // submission initialization: MakeSubmissionInitialization(statements, syntax, constructor, previousSubmissionFields, compilation); } statements.Add(loweredBody); return statements.ToImmutableAndFree(); } /// <summary> /// Generates a submission initialization part of a Script type constructor that represents an interactive submission. /// </summary> /// <remarks> /// The constructor takes a parameter of type Microsoft.CodeAnalysis.Scripting.Session - the session reference. /// It adds the object being constructed into the session by calling Microsoft.CSharp.RuntimeHelpers.SessionHelpers.SetSubmission, /// and retrieves strongly typed references on all previous submission script classes whose members are referenced by this submission. /// The references are stored to fields of the submission (<paramref name="synthesizedFields"/>). /// </remarks> private static void MakeSubmissionInitialization( ArrayBuilder<BoundStatement> statements, SyntaxNode syntax, MethodSymbol submissionConstructor, SynthesizedSubmissionFields synthesizedFields, CSharpCompilation compilation) { Debug.Assert(submissionConstructor.ParameterCount == 1); var submissionArrayReference = new BoundParameter(syntax, submissionConstructor.Parameters[0]) { WasCompilerGenerated = true }; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var thisReference = new BoundThisReference(syntax, submissionConstructor.ContainingType) { WasCompilerGenerated = true }; var slotIndex = compilation.GetSubmissionSlotIndex(); Debug.Assert(slotIndex >= 0); // <submission_array>[<slot_index] = this; statements.Add(new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(slotIndex), intType) { WasCompilerGenerated = true }), objectType) { WasCompilerGenerated = true }, thisReference, false, thisReference.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); var hostObjectField = synthesizedFields.GetHostObjectField(); if ((object)hostObjectField != null) { // <host_object> = (<host_object_type>)<submission_array>[0] statements.Add( new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, thisReference, hostObjectField, ConstantValue.NotAvailable) { WasCompilerGenerated = true }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(0), intType) { WasCompilerGenerated = true }), objectType), Conversion.ExplicitReference, false, explicitCastInCode: true, conversionGroupOpt: null, ConstantValue.NotAvailable, hostObjectField.Type ), hostObjectField.Type) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); } foreach (var field in synthesizedFields.FieldSymbols) { var targetScriptType = (ImplicitNamedTypeSymbol)field.Type; var targetSubmissionIndex = targetScriptType.DeclaringCompilation.GetSubmissionSlotIndex(); Debug.Assert(targetSubmissionIndex >= 0); // this.<field> = (<target_script_type>)<submission_array>[<target_submission_index>]; statements.Add( new BoundExpressionStatement(syntax, new BoundAssignmentOperator(syntax, new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true }, BoundConversion.Synthesized(syntax, new BoundArrayAccess(syntax, submissionArrayReference, ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(targetSubmissionIndex), intType) { WasCompilerGenerated = true }), objectType) { WasCompilerGenerated = true }, Conversion.ExplicitReference, false, explicitCastInCode: true, conversionGroupOpt: null, ConstantValue.NotAvailable, targetScriptType ), targetScriptType ) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }); } } /// <summary> /// Construct a body for an auto-property accessor (updating or returning the backing field). /// </summary> internal static BoundBlock ConstructAutoPropertyAccessorBody(SourceMemberMethodSymbol accessor) { Debug.Assert(accessor.MethodKind == MethodKind.PropertyGet || accessor.MethodKind == MethodKind.PropertySet); var property = (SourcePropertySymbolBase)accessor.AssociatedSymbol; CSharpSyntaxNode syntax = property.CSharpSyntaxNode; BoundExpression thisReference = null; if (!accessor.IsStatic) { var thisSymbol = accessor.ThisParameter; thisReference = new BoundThisReference(syntax, thisSymbol.Type) { WasCompilerGenerated = true }; } var field = property.BackingField; var fieldAccess = new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; BoundStatement statement; if (accessor.MethodKind == MethodKind.PropertyGet) { statement = new BoundReturnStatement(accessor.SyntaxNode, RefKind.None, fieldAccess); } else { Debug.Assert(accessor.MethodKind == MethodKind.PropertySet); var parameter = accessor.Parameters[0]; statement = new BoundExpressionStatement( accessor.SyntaxNode, new BoundAssignmentOperator( syntax, fieldAccess, new BoundParameter(syntax, parameter) { WasCompilerGenerated = true }, property.Type) { WasCompilerGenerated = true }); } return BoundBlock.SynthesizedNoLocals(syntax, statement); } /// <summary> /// Generate an accessor for a field-like event. /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(eventSymbol.HasAssociatedField); return eventSymbol.IsWindowsRuntimeEvent ? ConstructFieldLikeEventAccessorBody_WinRT(eventSymbol, isAddMethod, compilation, diagnostics) : ConstructFieldLikeEventAccessorBody_Regular(eventSymbol, isAddMethod, compilation, diagnostics); } /// <summary> /// Generate a thread-safe accessor for a WinRT field-like event. /// /// Add: /// return EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddEventHandler(value); /// /// Remove: /// EventRegistrationTokenTable&lt;Event&gt;.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveEventHandler(value); /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody_WinRT(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode; MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; Debug.Assert((object)accessor != null); FieldSymbol field = eventSymbol.AssociatedField; Debug.Assert((object)field != null); NamedTypeSymbol fieldType = (NamedTypeSymbol)field.Type; Debug.Assert(fieldType.Name == "EventRegistrationTokenTable"); MethodSymbol getOrCreateMethod = (MethodSymbol)Binder.GetWellKnownTypeMember( compilation, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, diagnostics, syntax: syntax); if ((object)getOrCreateMethod == null) { Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); return null; } getOrCreateMethod = getOrCreateMethod.AsMember(fieldType); WellKnownMember processHandlerMember = isAddMethod ? WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler : WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler; MethodSymbol processHandlerMethod = (MethodSymbol)Binder.GetWellKnownTypeMember( compilation, processHandlerMember, diagnostics, syntax: syntax); if ((object)processHandlerMethod == null) { Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); return null; } processHandlerMethod = processHandlerMethod.AsMember(fieldType); // _tokenTable BoundFieldAccess fieldAccess = new BoundFieldAccess( syntax, field.IsStatic ? null : new BoundThisReference(syntax, accessor.ThisParameter.Type), field, constantValueOpt: null) { WasCompilerGenerated = true }; // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable) BoundCall getOrCreateCall = BoundCall.Synthesized( syntax, receiverOpt: null, method: getOrCreateMethod, arg0: fieldAccess); // value BoundParameter parameterAccess = new BoundParameter( syntax, accessor.Parameters[0]); // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value) // or RemoveHandler BoundCall processHandlerCall = BoundCall.Synthesized( syntax, receiverOpt: getOrCreateCall, method: processHandlerMethod, arg0: parameterAccess); if (isAddMethod) { // { // return EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value); // } BoundStatement returnStatement = BoundReturnStatement.Synthesized(syntax, RefKind.None, processHandlerCall); return BoundBlock.SynthesizedNoLocals(syntax, returnStatement); } else { // { // EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveHandler(value); // return; // } BoundStatement callStatement = new BoundExpressionStatement(syntax, processHandlerCall); BoundStatement returnStatement = new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null); return BoundBlock.SynthesizedNoLocals(syntax, callStatement, returnStatement); } } /// <summary> /// Generate a thread-safe accessor for a regular field-like event. /// /// DelegateType tmp0 = _event; //backing field /// DelegateType tmp1; /// DelegateType tmp2; /// do { /// tmp1 = tmp0; /// tmp2 = (DelegateType)Delegate.Combine(tmp1, value); //Remove for -= /// tmp0 = Interlocked.CompareExchange&lt;DelegateType&gt;(ref _event, tmp2, tmp1); /// } while ((object)tmp0 != (object)tmp1); /// /// Note, if System.Threading.Interlocked.CompareExchange&lt;T&gt; is not available, /// we emit the following code and mark the method Synchronized (unless it is a struct). /// /// _event = (DelegateType)Delegate.Combine(_event, value); //Remove for -= /// /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody_Regular(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode; TypeSymbol delegateType = eventSymbol.Type; MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; ParameterSymbol thisParameter = accessor.ThisParameter; TypeSymbol boolType = compilation.GetSpecialType(SpecialType.System_Boolean); SpecialMember updateMethodId = isAddMethod ? SpecialMember.System_Delegate__Combine : SpecialMember.System_Delegate__Remove; MethodSymbol updateMethod = (MethodSymbol)compilation.GetSpecialTypeMember(updateMethodId); BoundStatement @return = new BoundReturnStatement(syntax, refKind: RefKind.None, expressionOpt: null) { WasCompilerGenerated = true }; if (updateMethod == null) { MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(updateMethodId); diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), syntax.Location)); return BoundBlock.SynthesizedNoLocals(syntax, @return); } Binder.ReportUseSite(updateMethod, diagnostics, syntax); BoundThisReference fieldReceiver = eventSymbol.IsStatic ? null : new BoundThisReference(syntax, thisParameter.Type) { WasCompilerGenerated = true }; BoundFieldAccess boundBackingField = new BoundFieldAccess(syntax, receiver: fieldReceiver, fieldSymbol: eventSymbol.AssociatedField, constantValueOpt: null) { WasCompilerGenerated = true }; BoundParameter boundParameter = new BoundParameter(syntax, parameterSymbol: accessor.Parameters[0]) { WasCompilerGenerated = true }; BoundExpression delegateUpdate; MethodSymbol compareExchangeMethod = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T); if ((object)compareExchangeMethod == null) { // (DelegateType)Delegate.Combine(_event, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // _event = (DelegateType)Delegate.Combine(_event, value); BoundStatement eventUpdate = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundBackingField, right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; return BoundBlock.SynthesizedNoLocals(syntax, statements: ImmutableArray.Create<BoundStatement>( eventUpdate, @return)); } compareExchangeMethod = compareExchangeMethod.Construct(ImmutableArray.Create<TypeSymbol>(delegateType)); Binder.ReportUseSite(compareExchangeMethod, diagnostics, syntax); GeneratedLabelSymbol loopLabel = new GeneratedLabelSymbol("loop"); const int numTemps = 3; LocalSymbol[] tmps = new LocalSymbol[numTemps]; BoundLocal[] boundTmps = new BoundLocal[numTemps]; for (int i = 0; i < numTemps; i++) { tmps[i] = new SynthesizedLocal(accessor, TypeWithAnnotations.Create(delegateType), SynthesizedLocalKind.LoweringTemp); boundTmps[i] = new BoundLocal(syntax, tmps[i], null, delegateType) { WasCompilerGenerated = true }; } // tmp0 = _event; BoundStatement tmp0Init = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: boundBackingField, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // LOOP: BoundStatement loopStart = new BoundLabelStatement(syntax, label: loopLabel) { WasCompilerGenerated = true }; // tmp1 = tmp0; BoundStatement tmp1Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[1], right: boundTmps[0], type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // (DelegateType)Delegate.Combine(tmp1, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundTmps[1], boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // tmp2 = (DelegateType)Delegate.Combine(tmp1, value); BoundStatement tmp2Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[2], right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1) BoundExpression compareExchange = BoundCall.Synthesized(syntax, receiverOpt: null, method: compareExchangeMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundTmps[2], boundTmps[1])); // tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1); BoundStatement tmp0Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: compareExchange, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // tmp0 == tmp1 // i.e. exit when they are equal, jump to start otherwise BoundExpression loopExitCondition = new BoundBinaryOperator(syntax, operatorKind: BinaryOperatorKind.ObjectEqual, left: boundTmps[0], right: boundTmps[1], constantValueOpt: null, methodOpt: null, constrainedToTypeOpt: null, resultKind: LookupResultKind.Viable, type: boolType) { WasCompilerGenerated = true }; // branchfalse (tmp0 == tmp1) LOOP BoundStatement loopEnd = new BoundConditionalGoto(syntax, condition: loopExitCondition, jumpIfTrue: false, label: loopLabel) { WasCompilerGenerated = true }; return new BoundBlock(syntax, locals: tmps.AsImmutable(), statements: ImmutableArray.Create<BoundStatement>( tmp0Init, loopStart, tmp1Update, tmp2Update, tmp0Update, loopEnd, @return)) { WasCompilerGenerated = true }; } internal static BoundBlock ConstructDestructorBody(MethodSymbol method, BoundBlock block) { var syntax = block.Syntax; Debug.Assert(method.MethodKind == MethodKind.Destructor); Debug.Assert(syntax.Kind() == SyntaxKind.Block || syntax.Kind() == SyntaxKind.ArrowExpressionClause); // If this is a destructor and a base type has a Finalize method (see GetBaseTypeFinalizeMethod for exact // requirements), then we need to call that method in a finally block. Otherwise, just return block as-is. // NOTE: the Finalize method need not be a destructor or be overridden by the current method. MethodSymbol baseTypeFinalize = GetBaseTypeFinalizeMethod(method); if ((object)baseTypeFinalize != null) { BoundStatement baseFinalizeCall = new BoundExpressionStatement( syntax, BoundCall.Synthesized( syntax, new BoundBaseReference( syntax, method.ContainingType) { WasCompilerGenerated = true }, baseTypeFinalize)) { WasCompilerGenerated = true }; if (syntax.Kind() == SyntaxKind.Block) { //sequence point to mimic Dev10 baseFinalizeCall = new BoundSequencePointWithSpan( syntax, baseFinalizeCall, ((BlockSyntax)syntax).CloseBraceToken.Span); } return new BoundBlock( syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundStatement>( new BoundTryStatement( syntax, block, ImmutableArray<BoundCatchBlock>.Empty, new BoundBlock( syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundStatement>( baseFinalizeCall) ) { WasCompilerGenerated = true } ) { WasCompilerGenerated = true })); } return block; } /// <summary> /// Look for a base type method named "Finalize" that is protected (or protected internal), has no parameters, /// and returns void. It doesn't need to be virtual or a destructor. /// </summary> /// <remarks> /// You may assume that this would share code and logic with PEMethodSymbol.OverridesRuntimeFinalizer, /// but FUNCBRECCS::bindDestructor has its own loop that performs these checks (differently). /// </remarks> private static MethodSymbol GetBaseTypeFinalizeMethod(MethodSymbol method) { NamedTypeSymbol baseType = method.ContainingType.BaseTypeNoUseSiteDiagnostics; while ((object)baseType != null) { foreach (Symbol member in baseType.GetMembers(WellKnownMemberNames.DestructorName)) { if (member.Kind == SymbolKind.Method) { MethodSymbol baseTypeMethod = (MethodSymbol)member; Accessibility accessibility = baseTypeMethod.DeclaredAccessibility; if ((accessibility == Accessibility.ProtectedOrInternal || accessibility == Accessibility.Protected) && baseTypeMethod.ParameterCount == 0 && baseTypeMethod.Arity == 0 && // NOTE: the native compiler doesn't check this, so it broken IL. baseTypeMethod.ReturnsVoid) // NOTE: not checking for virtual { return baseTypeMethod; } } } baseType = baseType.BaseTypeNoUseSiteDiagnostics; } return null; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.ExtractMethod.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.ExtractMethod; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int ExtractMethod_AllowBestEffort { get { return GetBooleanOption(ExtractMethodOptions.AllowBestEffort); } set { SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, 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. using Microsoft.CodeAnalysis.ExtractMethod; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int ExtractMethod_AllowBestEffort { get { return GetBooleanOption(ExtractMethodOptions.AllowBestEffort); } set { SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Test/Syntax/Parsing/NameAttributeValueParsingTests.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.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Compilers.CSharp.UnitTests { public class NameAttributeValueParsingTests : ParsingTests { public NameAttributeValueParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <param name=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlNameAttributeSyntax>().Single(); return attr.Identifier; } [Fact] public void Identifier() { UsingNode("A"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Keyword() { UsingNode("int"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Empty() { UsingNode(""); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Whitespace() { UsingNode(" "); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Qualified() { // Everything after the first identifier is skipped. UsingNode("A.B"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Generic() { // Everything after the first identifier is skipped. UsingNode("A{T}"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Punctuation() { // A missing identifier is inserted and everything is skipped. UsingNode("."); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } } }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Compilers.CSharp.UnitTests { public class NameAttributeValueParsingTests : ParsingTests { public NameAttributeValueParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <param name=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlNameAttributeSyntax>().Single(); return attr.Identifier; } [Fact] public void Identifier() { UsingNode("A"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Keyword() { UsingNode("int"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Empty() { UsingNode(""); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Whitespace() { UsingNode(" "); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Qualified() { // Everything after the first identifier is skipped. UsingNode("A.B"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Generic() { // Everything after the first identifier is skipped. UsingNode("A{T}"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Punctuation() { // A missing identifier is inserted and everything is skipped. UsingNode("."); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementation.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. //csc /target:library interface Interface { void Method(); } class Class : Interface { void Interface.Method() { } } interface IGeneric<T> { void Method<U, Z>(T t, U u); //wrong number of type parameters void Method<U>(T t); //wrong number of parameters void Method<U>(U u, T t); //wrong parameter types void Method<U>(T t, ref U u); //wrong parameter refness T Method<U>(T t1, T t2); //wrong return type void Method<U>(T t, U u); //match } class Generic<S> : IGeneric<S> { void IGeneric<S>.Method<U, Z>(S s, U u) { } void IGeneric<S>.Method<U>(S s) { } void IGeneric<S>.Method<U>(U u, S s) { } void IGeneric<S>.Method<U>(S s, ref U u) { } S IGeneric<S>.Method<U>(S s1, S s2) { return s1; } void IGeneric<S>.Method<V>(S s, V v) { } } class Constructed : IGeneric<int> { void IGeneric<int>.Method<U, Z>(int i, U u) { } void IGeneric<int>.Method<U>(int i) { } void IGeneric<int>.Method<U>(U u, int i) { } void IGeneric<int>.Method<U>(int i, ref U u) { } int IGeneric<int>.Method<U>(int i1, int i2) { return i1; } void IGeneric<int>.Method<W>(int i, W w) { } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { void Interface.Method() { } } interface IGeneric2<T> { void Method(T t); } class Outer<T> { internal interface IInner<U> { void Method(U u); } internal class Inner1<A> : IGeneric2<A> //outer interface, inner type param { void IGeneric2<A>.Method(A a) { } } internal class Inner2<B> : IGeneric2<T> //outer interface, outer type param { void IGeneric2<T>.Method(T t) { } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { void IInner<C>.Method(C b) { } } internal class Inner4<D> : IInner<T> //inner interface, outer type param { void IInner<T>.Method(T t) { } } }
// 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. //csc /target:library interface Interface { void Method(); } class Class : Interface { void Interface.Method() { } } interface IGeneric<T> { void Method<U, Z>(T t, U u); //wrong number of type parameters void Method<U>(T t); //wrong number of parameters void Method<U>(U u, T t); //wrong parameter types void Method<U>(T t, ref U u); //wrong parameter refness T Method<U>(T t1, T t2); //wrong return type void Method<U>(T t, U u); //match } class Generic<S> : IGeneric<S> { void IGeneric<S>.Method<U, Z>(S s, U u) { } void IGeneric<S>.Method<U>(S s) { } void IGeneric<S>.Method<U>(U u, S s) { } void IGeneric<S>.Method<U>(S s, ref U u) { } S IGeneric<S>.Method<U>(S s1, S s2) { return s1; } void IGeneric<S>.Method<V>(S s, V v) { } } class Constructed : IGeneric<int> { void IGeneric<int>.Method<U, Z>(int i, U u) { } void IGeneric<int>.Method<U>(int i) { } void IGeneric<int>.Method<U>(U u, int i) { } void IGeneric<int>.Method<U>(int i, ref U u) { } int IGeneric<int>.Method<U>(int i1, int i2) { return i1; } void IGeneric<int>.Method<W>(int i, W w) { } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { void Interface.Method() { } } interface IGeneric2<T> { void Method(T t); } class Outer<T> { internal interface IInner<U> { void Method(U u); } internal class Inner1<A> : IGeneric2<A> //outer interface, inner type param { void IGeneric2<A>.Method(A a) { } } internal class Inner2<B> : IGeneric2<T> //outer interface, outer type param { void IGeneric2<T>.Method(T t) { } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { void IInner<C>.Method(C b) { } } internal class Inner4<D> : IInner<T> //inner interface, outer type param { void IInner<T>.Method(T t) { } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/VisualBasicTest/Recommendations/Queries/AggregateKeywordRecommenderTests.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.Queries Public Class AggregateKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample1Test() VerifyRecommendationsContain( <MethodBody> Dim orderTotals = _ From cust In Customers _ Where cust.State = "WA" _ | </MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample2Test() VerifyRecommendationsContain( <MethodBody> Dim ordersTotal = _ | </MethodBody>, "Aggregate") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Aggregate") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Aggregate") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Aggregate") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Aggregate") End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, "Aggregate") 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.Queries Public Class AggregateKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample1Test() VerifyRecommendationsContain( <MethodBody> Dim orderTotals = _ From cust In Customers _ Where cust.State = "WA" _ | </MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample2Test() VerifyRecommendationsContain( <MethodBody> Dim ordersTotal = _ | </MethodBody>, "Aggregate") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Aggregate") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Aggregate") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Aggregate") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Aggregate") End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, "Aggregate") End Sub End Class End Namespace
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/VisualBasic/Portable/Compilation/DocumentationComments/DocWriter.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.Diagnostics Imports System.IO Imports System.Text Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Private Structure DocWriter Private ReadOnly _writer As TextWriter Private _indentDepth As Integer Private _temporaryStringBuilders As Stack(Of TemporaryStringBuilder) Public Sub New(writer As TextWriter) Me._writer = writer Me._indentDepth = 0 Me._temporaryStringBuilders = Nothing End Sub Public ReadOnly Property IsSpecified As Boolean Get Return Me._writer IsNot Nothing End Get End Property Public ReadOnly Property IndentDepth As Integer Get Return Me._indentDepth End Get End Property Public Sub Indent() ' NOTE: Dev11 does not seem to try pretty-indenting of the document tags ' which is reasonable because we don't want to add extra indents in XML 'Me._indentDepth += 1 End Sub Public Sub Unindent() ' NOTE: Dev11 does not seem to try pretty-indenting of the document tags ' which is reasonable because we don't want to add extra indents in XML 'Me._indentDepth -= 1 Debug.Assert(Me._indentDepth >= 0) End Sub Public Sub WriteLine(message As String) If IsSpecified Then If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(Me._indentDepth)) builder.AppendLine(message) ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(Me._indentDepth)) Me._writer.WriteLine(message) End If End If End Sub Public Sub Write(message As String) If IsSpecified Then If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(Me._indentDepth)) builder.Append(message) ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(Me._indentDepth)) Me._writer.Write(message) End If End If End Sub Public Sub WriteSubString(message As String, start As Integer, length As Integer, Optional appendNewLine As Boolean = True) If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(IndentDepth)) builder.Append(message, start, length) If appendNewLine Then builder.AppendLine() End If ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(IndentDepth)) For i = 0 To length - 1 Me._writer.Write(message(start + i)) Next If appendNewLine Then Me._writer.WriteLine() End If End If End Sub Public Function GetAndEndTemporaryString() As String Dim t As TemporaryStringBuilder = Me._temporaryStringBuilders.Pop() Debug.Assert(Me._indentDepth = t.InitialIndentDepth, String.Format("Temporary strings should be indent-neutral (was {0}, is {1})", t.InitialIndentDepth, Me._indentDepth)) Me._indentDepth = t.InitialIndentDepth Return t.Pooled.ToStringAndFree() End Function Private Shared Function MakeIndent(depth As Integer) As String Debug.Assert(depth >= 0) ' Since we know a lot about the structure of the output, we should ' be able to do this without constructing any new string objects. Select Case depth Case 0 : Return "" Case 1 : Return " " Case 2 : Return " " Case 3 : Return " " Case Else Debug.Assert(False, "Didn't expect nesting to reach depth " & depth) Return New String(" "c, depth * 4) End Select End Function Public Sub BeginTemporaryString() If Me._temporaryStringBuilders Is Nothing Then Me._temporaryStringBuilders = New Stack(Of TemporaryStringBuilder)() End If Me._temporaryStringBuilders.Push(New TemporaryStringBuilder(Me._indentDepth)) End Sub Private Structure TemporaryStringBuilder Public ReadOnly Pooled As PooledStringBuilder Public ReadOnly InitialIndentDepth As Integer Public Sub New(indentDepth As Integer) Me.InitialIndentDepth = indentDepth Me.Pooled = PooledStringBuilder.GetInstance() End Sub End Structure End Structure 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 Imports System.Collections.Generic Imports System.Diagnostics Imports System.IO Imports System.Text Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Private Structure DocWriter Private ReadOnly _writer As TextWriter Private _indentDepth As Integer Private _temporaryStringBuilders As Stack(Of TemporaryStringBuilder) Public Sub New(writer As TextWriter) Me._writer = writer Me._indentDepth = 0 Me._temporaryStringBuilders = Nothing End Sub Public ReadOnly Property IsSpecified As Boolean Get Return Me._writer IsNot Nothing End Get End Property Public ReadOnly Property IndentDepth As Integer Get Return Me._indentDepth End Get End Property Public Sub Indent() ' NOTE: Dev11 does not seem to try pretty-indenting of the document tags ' which is reasonable because we don't want to add extra indents in XML 'Me._indentDepth += 1 End Sub Public Sub Unindent() ' NOTE: Dev11 does not seem to try pretty-indenting of the document tags ' which is reasonable because we don't want to add extra indents in XML 'Me._indentDepth -= 1 Debug.Assert(Me._indentDepth >= 0) End Sub Public Sub WriteLine(message As String) If IsSpecified Then If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(Me._indentDepth)) builder.AppendLine(message) ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(Me._indentDepth)) Me._writer.WriteLine(message) End If End If End Sub Public Sub Write(message As String) If IsSpecified Then If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(Me._indentDepth)) builder.Append(message) ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(Me._indentDepth)) Me._writer.Write(message) End If End If End Sub Public Sub WriteSubString(message As String, start As Integer, length As Integer, Optional appendNewLine As Boolean = True) If Me._temporaryStringBuilders IsNot Nothing AndAlso Me._temporaryStringBuilders.Count > 0 Then Dim builder As StringBuilder = Me._temporaryStringBuilders.Peek().Pooled.Builder builder.Append(MakeIndent(IndentDepth)) builder.Append(message, start, length) If appendNewLine Then builder.AppendLine() End If ElseIf Me._writer IsNot Nothing Then Me._writer.Write(MakeIndent(IndentDepth)) For i = 0 To length - 1 Me._writer.Write(message(start + i)) Next If appendNewLine Then Me._writer.WriteLine() End If End If End Sub Public Function GetAndEndTemporaryString() As String Dim t As TemporaryStringBuilder = Me._temporaryStringBuilders.Pop() Debug.Assert(Me._indentDepth = t.InitialIndentDepth, String.Format("Temporary strings should be indent-neutral (was {0}, is {1})", t.InitialIndentDepth, Me._indentDepth)) Me._indentDepth = t.InitialIndentDepth Return t.Pooled.ToStringAndFree() End Function Private Shared Function MakeIndent(depth As Integer) As String Debug.Assert(depth >= 0) ' Since we know a lot about the structure of the output, we should ' be able to do this without constructing any new string objects. Select Case depth Case 0 : Return "" Case 1 : Return " " Case 2 : Return " " Case 3 : Return " " Case Else Debug.Assert(False, "Didn't expect nesting to reach depth " & depth) Return New String(" "c, depth * 4) End Select End Function Public Sub BeginTemporaryString() If Me._temporaryStringBuilders Is Nothing Then Me._temporaryStringBuilders = New Stack(Of TemporaryStringBuilder)() End If Me._temporaryStringBuilders.Push(New TemporaryStringBuilder(Me._indentDepth)) End Sub Private Structure TemporaryStringBuilder Public ReadOnly Pooled As PooledStringBuilder Public ReadOnly InitialIndentDepth As Integer Public Sub New(indentDepth As Integer) Me.InitialIndentDepth = indentDepth Me.Pooled = PooledStringBuilder.GetInstance() End Sub End Structure End Structure End Class End Class End Namespace
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTestBase.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.CSharp.UnitTests; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class OverloadResolutionTestBase : CompilingTestBase { internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? Array.Empty<MetadataReference>()); var compilation = CreateEmptyCompilation(source, references, TestOptions.ReleaseDll); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3)) .ToArray()); AssertEx.EqualOrDiff(expected, results); } } }
// 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.CSharp.UnitTests; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class OverloadResolutionTestBase : CompilingTestBase { internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? Array.Empty<MetadataReference>()); var compilation = CreateEmptyCompilation(source, references, TestOptions.ReleaseDll); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3)) .ToArray()); AssertEx.EqualOrDiff(expected, results); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Workspace/Host/Caching/ICachedObjectOwner.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 namespace Microsoft.CodeAnalysis.Host { internal interface ICachedObjectOwner { object CachedObject { get; set; } } }
// 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 namespace Microsoft.CodeAnalysis.Host { internal interface ICachedObjectOwner { object CachedObject { get; set; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/VisualBasic/Test/Semantic/Binding/GenericsTests.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.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GenericsTests Inherits BasicTestBase <WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")> <WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")> <Fact()> Public Sub WrongNumberOfGenericArgumentsTest() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="WrongNumberOfGenericArguments"> <file name="a.vb"> Namespace GenArity200 Public Class vbCls5 (Of T) Structure vbStrA (Of X, Y) Dim i As Integer Public Readonly Property rp () As String Get Return "vbCls5 (Of T) vbStrA (Of X, Y)" End Get End Property End Structure End Class Class Problem Sub GenArity200() Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer) End Sub End Class End Namespace </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'vbCls5(Of UInteger()()).vbStrA(Of X, Y)'. Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543706")> <Fact()> Public Sub TestNestedGenericTypeInference() Dim vbCompilation = CreateVisualBasicCompilation("TestNestedGenericTypeInference", <![CDATA[Imports System Public Module Program Sub goo(Of U, T)(ByVal x As cls1(Of U).cls2(Of T)) Console.WriteLine(GetType(U).ToString()) Console.WriteLine(GetType(T).ToString()) End Sub Class cls1(Of X) Class cls2(Of Y) End Class End Class Sub Main() Dim x = New cls1(Of Integer).cls2(Of Long) goo(x) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[System.Int32 System.Int64]]>).VerifyDiagnostics() End Sub <WorkItem(543783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543783")> <Fact()> Public Sub ImportNestedGenericTypeWithErrors() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String) Namespace GenImpClassOpenErrors Module Module1 Public Class GenClassA(Of T) Public Class GenClassB(Of U) Public Class GenClassC(Of V) End Class End Class End Class End Module End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'Module1.GenClassA(Of String).GenClassB(Of U)'. Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543850")> <Fact()> Public Sub ConflictingNakedConstraint() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Class c2 End Class Class c3 End Class Class C6(Of T As {c2, c3}) 'COMPILEERROR: BC32110, "c3", BC32110, "c3" Interface I1(Of S As {U, c3}, U As {c3, T}) End Interface End Class End Module </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC32047: Type parameter 'T' can only have one constraint that is a class. Class C6(Of T As {c2, c3}) ~~ BC32111: Indirect constraint 'Class c2' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class c3'. Interface I1(Of S As {U, c3}, U As {c3, T}) ~ BC32110: Constraint 'Class c3' conflicts with the indirect constraint 'Class c2' obtained from the type parameter constraint 'T'. Interface I1(Of S As {U, c3}, U As {c3, T}) ~~ </expected>) End Sub <WorkItem(11887, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WideningNullableConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Gen1E(Of T, V As Structure)(ByVal c As Func(Of V?, T)) Dim k = New V c(k) End Sub End Module </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")> <Fact()> Public Sub NarrowingConversionNoReturn() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Class C6 Public Shared Narrowing Operator CType(ByVal arg As C6) As Exception Return Nothing End Operator End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")> <Fact()> Public Sub NarrowingConversionNoReturn2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Class c2 Public Shared Narrowing Operator CType(ByVal arg As c2) As Integer Return Nothing End Operator End Class End Namespace </file> </compilation> ) compilation.AssertNoDiagnostics() End Sub <WorkItem(543902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543902")> <Fact()> Public Sub ConversionOperatorShouldBePublic() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace Program Class CScen5 Shared Narrowing Operator CType(ByVal src As CScen5b) As CScen5 str = "scen5" Return New CScen5 End Operator Public Shared str = "" End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "CScen5b").WithArguments("CScen5b")) End Sub <Fact(), WorkItem(529249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529249")> Public Sub ArrayOfRuntimeArgumentHandle() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub goo(ByRef x As RuntimeArgumentHandle()) ReDim x(100) End Sub End Module </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "RuntimeArgumentHandle()").WithArguments("System.RuntimeArgumentHandle")) End Sub <WorkItem(543909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543909")> <Fact()> Public Sub StructureContainsItself() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Structure s2 Dim list As Collections.Generic.List(Of s2) 'COMPILEERROR: BC30294, "Collections.Generic.List(Of s2).Enumerator" Dim enumerator As Collections.Generic.List(Of s2).Enumerator End Structure End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RecordCycle2, "enumerator").WithArguments("s2", Environment.NewLine & " 's2' contains 'List(Of s2).Enumerator' (variable 'enumerator')." & Environment.NewLine & " 'List(Of s2).Enumerator' contains 's2' (variable 'current').")) End Sub <WorkItem(543921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543921")> <Fact()> Public Sub GenericConstraintInheritanceWithEvent() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace GenClass7105 Interface I1 Event e() Property p1() As String Sub rEvent() End Interface Class CI1 Implements I1 Private s1 As String Public Event e() Implements I1.e Public Sub rEvent() Implements I1.rEvent RaiseEvent e() End Sub Public Property p1() As String Implements I1.p1 Get Return s1 End Get Set(ByVal value As String) s1 = value End Set End Property Sub eHandler() Handles Me.e Me.s1 = Me.s1 &amp; "eHandler" End Sub End Class Class CI2 Inherits CI1 End Class Class Cls1a(Of T1 As {I1, Class}, T2 As T1) Public WithEvents x1 As T1 'This error is actually correct now as the Class Constraint Change which was made. Class can be a Class (OR INTERFACE) on a structure. 'This testcase has changed to reflect the new behavior and this constraint change will also be caught. 'COMPILEERROR: BC30413, "T2" Public WithEvents x2 As T2 Public Function Test(ByVal i As Integer) As String x2.p1 = "x2_" Call x2.rEvent() Return x2.p1 End Function End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_WithEventsAsStruct, "x2")) End Sub <WorkItem(529287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529287")> <Fact()> Public Sub ProtectedMemberGenericClass() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class c1(Of T) 'COMPILEERROR: BC30508, "c1(Of Integer).c2" Protected x As c1(Of Integer).c2 Protected Class c2 End Class End Class </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(544122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544122")> <Fact()> Public Sub BoxAlreadyBoxed() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Scen4(Of T As U, U As Class)(ByVal p As T) Dim x As T x = TryCast(p, U) If x Is Nothing Then Console.WriteLine("fail") End If End Sub Sub Main(args As String()) End Sub End Module </file> </compilation> ) End Sub <WorkItem(531075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531075")> <Fact()> Public Sub Bug17530() Dim vbCompilation = CreateVisualBasicCompilation("Bug17530", <![CDATA[ Imports Tuple = System.Tuple Public Module Program Sub Main() Dim x As Object = Nothing Dim y = TryCast(x, Tuple(Of Integer, Integer, String)) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, globalImports:=GlobalImport.Parse({"System"}))) CompileAndVerify(vbCompilation).VerifyDiagnostics( Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports Tuple = System.Tuple")) 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.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GenericsTests Inherits BasicTestBase <WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")> <WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")> <Fact()> Public Sub WrongNumberOfGenericArgumentsTest() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="WrongNumberOfGenericArguments"> <file name="a.vb"> Namespace GenArity200 Public Class vbCls5 (Of T) Structure vbStrA (Of X, Y) Dim i As Integer Public Readonly Property rp () As String Get Return "vbCls5 (Of T) vbStrA (Of X, Y)" End Get End Property End Structure End Class Class Problem Sub GenArity200() Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer) End Sub End Class End Namespace </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'vbCls5(Of UInteger()()).vbStrA(Of X, Y)'. Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543706")> <Fact()> Public Sub TestNestedGenericTypeInference() Dim vbCompilation = CreateVisualBasicCompilation("TestNestedGenericTypeInference", <![CDATA[Imports System Public Module Program Sub goo(Of U, T)(ByVal x As cls1(Of U).cls2(Of T)) Console.WriteLine(GetType(U).ToString()) Console.WriteLine(GetType(T).ToString()) End Sub Class cls1(Of X) Class cls2(Of Y) End Class End Class Sub Main() Dim x = New cls1(Of Integer).cls2(Of Long) goo(x) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[System.Int32 System.Int64]]>).VerifyDiagnostics() End Sub <WorkItem(543783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543783")> <Fact()> Public Sub ImportNestedGenericTypeWithErrors() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String) Namespace GenImpClassOpenErrors Module Module1 Public Class GenClassA(Of T) Public Class GenClassB(Of U) Public Class GenClassC(Of V) End Class End Class End Class End Module End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'Module1.GenClassA(Of String).GenClassB(Of U)'. Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543850")> <Fact()> Public Sub ConflictingNakedConstraint() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Program Class c2 End Class Class c3 End Class Class C6(Of T As {c2, c3}) 'COMPILEERROR: BC32110, "c3", BC32110, "c3" Interface I1(Of S As {U, c3}, U As {c3, T}) End Interface End Class End Module </file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC32047: Type parameter 'T' can only have one constraint that is a class. Class C6(Of T As {c2, c3}) ~~ BC32111: Indirect constraint 'Class c2' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class c3'. Interface I1(Of S As {U, c3}, U As {c3, T}) ~ BC32110: Constraint 'Class c3' conflicts with the indirect constraint 'Class c2' obtained from the type parameter constraint 'T'. Interface I1(Of S As {U, c3}, U As {c3, T}) ~~ </expected>) End Sub <WorkItem(11887, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub WideningNullableConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Gen1E(Of T, V As Structure)(ByVal c As Func(Of V?, T)) Dim k = New V c(k) End Sub End Module </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")> <Fact()> Public Sub NarrowingConversionNoReturn() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Class C6 Public Shared Narrowing Operator CType(ByVal arg As C6) As Exception Return Nothing End Operator End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")> <Fact()> Public Sub NarrowingConversionNoReturn2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Class c2 Public Shared Narrowing Operator CType(ByVal arg As c2) As Integer Return Nothing End Operator End Class End Namespace </file> </compilation> ) compilation.AssertNoDiagnostics() End Sub <WorkItem(543902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543902")> <Fact()> Public Sub ConversionOperatorShouldBePublic() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace Program Class CScen5 Shared Narrowing Operator CType(ByVal src As CScen5b) As CScen5 str = "scen5" Return New CScen5 End Operator Public Shared str = "" End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "CScen5b").WithArguments("CScen5b")) End Sub <Fact(), WorkItem(529249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529249")> Public Sub ArrayOfRuntimeArgumentHandle() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub goo(ByRef x As RuntimeArgumentHandle()) ReDim x(100) End Sub End Module </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "RuntimeArgumentHandle()").WithArguments("System.RuntimeArgumentHandle")) End Sub <WorkItem(543909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543909")> <Fact()> Public Sub StructureContainsItself() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Namespace Program Structure s2 Dim list As Collections.Generic.List(Of s2) 'COMPILEERROR: BC30294, "Collections.Generic.List(Of s2).Enumerator" Dim enumerator As Collections.Generic.List(Of s2).Enumerator End Structure End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RecordCycle2, "enumerator").WithArguments("s2", Environment.NewLine & " 's2' contains 'List(Of s2).Enumerator' (variable 'enumerator')." & Environment.NewLine & " 'List(Of s2).Enumerator' contains 's2' (variable 'current').")) End Sub <WorkItem(543921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543921")> <Fact()> Public Sub GenericConstraintInheritanceWithEvent() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Namespace GenClass7105 Interface I1 Event e() Property p1() As String Sub rEvent() End Interface Class CI1 Implements I1 Private s1 As String Public Event e() Implements I1.e Public Sub rEvent() Implements I1.rEvent RaiseEvent e() End Sub Public Property p1() As String Implements I1.p1 Get Return s1 End Get Set(ByVal value As String) s1 = value End Set End Property Sub eHandler() Handles Me.e Me.s1 = Me.s1 &amp; "eHandler" End Sub End Class Class CI2 Inherits CI1 End Class Class Cls1a(Of T1 As {I1, Class}, T2 As T1) Public WithEvents x1 As T1 'This error is actually correct now as the Class Constraint Change which was made. Class can be a Class (OR INTERFACE) on a structure. 'This testcase has changed to reflect the new behavior and this constraint change will also be caught. 'COMPILEERROR: BC30413, "T2" Public WithEvents x2 As T2 Public Function Test(ByVal i As Integer) As String x2.p1 = "x2_" Call x2.rEvent() Return x2.p1 End Function End Class End Namespace </file> </compilation> ) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_WithEventsAsStruct, "x2")) End Sub <WorkItem(529287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529287")> <Fact()> Public Sub ProtectedMemberGenericClass() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class c1(Of T) 'COMPILEERROR: BC30508, "c1(Of Integer).c2" Protected x As c1(Of Integer).c2 Protected Class c2 End Class End Class </file> </compilation> ) compilation.VerifyDiagnostics() End Sub <WorkItem(544122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544122")> <Fact()> Public Sub BoxAlreadyBoxed() Dim compilation = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Scen4(Of T As U, U As Class)(ByVal p As T) Dim x As T x = TryCast(p, U) If x Is Nothing Then Console.WriteLine("fail") End If End Sub Sub Main(args As String()) End Sub End Module </file> </compilation> ) End Sub <WorkItem(531075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531075")> <Fact()> Public Sub Bug17530() Dim vbCompilation = CreateVisualBasicCompilation("Bug17530", <![CDATA[ Imports Tuple = System.Tuple Public Module Program Sub Main() Dim x As Object = Nothing Dim y = TryCast(x, Tuple(Of Integer, Integer, String)) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, globalImports:=GlobalImport.Parse({"System"}))) CompileAndVerify(vbCompilation).VerifyDiagnostics( Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports Tuple = System.Tuple")) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of method/property invocation is implemented in this part. Partial Friend Class Binder Private Function CreateBoundMethodGroup( node As SyntaxNode, lookupResult As LookupResult, lookupOptionsUsed As LookupOptions, withDependencies As Boolean, receiver As BoundExpression, typeArgumentsOpt As BoundTypeArguments, qualKind As QualificationKind, Optional hasError As Boolean = False ) As BoundMethodGroup Dim pendingExtensionMethods As ExtensionMethodGroup = Nothing Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) ' Name lookup does not look for extension methods if it found a suitable ' instance method. So, if the first symbol we have is not a reduced extension ' method, we might need to look for extension methods later, on demand. Debug.Assert((lookupOptionsUsed And LookupOptions.EagerlyLookupExtensionMethods) = 0) If lookupResult.IsGood AndAlso Not lookupResult.Symbols(0).IsReducedExtensionMethod() Then pendingExtensionMethods = New ExtensionMethodGroup(Me, lookupOptionsUsed, withDependencies) End If Return New BoundMethodGroup( node, typeArgumentsOpt, lookupResult.Symbols.ToDowncastedImmutable(Of MethodSymbol), pendingExtensionMethods, lookupResult.Kind, receiver, qualKind, hasErrors:=hasError) End Function ''' <summary> ''' Returns if all the rules for a "Me.New" or "MyBase.New" constructor call are satisfied: ''' a) In instance constructor body ''' b) First statement of that constructor ''' c) "Me", "MyClass", or "MyBase" is the receiver. ''' </summary> Private Function IsConstructorCallAllowed(invocationExpression As InvocationExpressionSyntax, boundMemberGroup As BoundMethodOrPropertyGroup) As Boolean If Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.Constructor Then ' (a) we are in an instance constructor body Dim node As VisualBasicSyntaxNode = invocationExpression.Parent If node Is Nothing OrElse (node.Kind <> SyntaxKind.CallStatement AndAlso node.Kind <> SyntaxKind.ExpressionStatement) Then Return False End If Dim nodeParent As VisualBasicSyntaxNode = node.Parent If nodeParent Is Nothing OrElse nodeParent.Kind <> SyntaxKind.ConstructorBlock Then Return False End If If DirectCast(nodeParent, ConstructorBlockSyntax).Statements(0) Is node Then ' (b) call statement we are binding is 'the first' statement of the constructor Dim receiver As BoundExpression = boundMemberGroup.ReceiverOpt If receiver IsNot Nothing AndAlso (receiver.Kind = BoundKind.MeReference OrElse receiver.Kind = BoundKind.MyBaseReference OrElse receiver.Kind = BoundKind.MyClassReference) Then ' (c) receiver is 'Me'/'MyClass'/'MyBase' Return True End If End If End If Return False End Function Friend Class ConstructorCallArgumentsBinder Inherits Binder Public Sub New(containingBinder As Binder) MyBase.New(containingBinder) End Sub Protected Overrides ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return True End Get End Property End Class ''' <summary> ''' Bind a Me.New(...), MyBase.New (...), MyClass.New(...) constructor call. ''' (NOT a normal constructor call like New Type(...)). ''' </summary> Private Function BindDirectConstructorCall(node As InvocationExpressionSyntax, group As BoundMethodGroup, diagnostics As BindingDiagnosticBag) As BoundExpression Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Dim argumentList As ArgumentListSyntax = node.ArgumentList Debug.Assert(IsGroupOfConstructors(group)) ' Direct constructor call is only allowed if: (a) we are in an instance constructor body, ' and (b) call statement we are binding is 'the first' statement of the constructor, ' and (c) receiver is 'Me'/'MyClass'/'MyBase' If IsConstructorCallAllowed(node, group) Then ' Bind arguments with special binder that prevents use of Me. Dim argumentsBinder As Binder = New ConstructorCallArgumentsBinder(Me) argumentsBinder.BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, errors will be generated if needed Return BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, diagnostics, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) Else ' Error case -- constructor call in wrong location. ' Report error BC30282 about invalid constructor call ' For semantic model / IDE purposes, we still bind it even if in a location that wasn't allowed. If Not group.HasErrors Then ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall) End If BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, ignore errors by putting into discarded bag. Dim expr = BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) If expr.Kind = BoundKind.Call Then ' Set HasErrors to prevent cascading errors. Dim callExpr = DirectCast(expr, BoundCall) expr = New BoundCall( callExpr.Syntax, callExpr.Method, callExpr.MethodGroupOpt, callExpr.ReceiverOpt, callExpr.Arguments, callExpr.DefaultArguments, callExpr.ConstantValueOpt, isLValue:=False, suppressObjectClone:=False, type:=callExpr.Type, hasErrors:=True) End If Return expr End If End Function Private Function BindInvocationExpression(node As InvocationExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression ' Set "IsInvocationsOrAddressOf" to prevent binding to return value variable. Dim target As BoundExpression If node.Expression Is Nothing Then ' Must be conditional case Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then target = GetConditionalAccessReceiver(conditionalAccess) Else target = ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_Syntax).MakeCompilerGenerated() End If Else target = BindExpression(node.Expression, diagnostics:=diagnostics, isInvocationOrAddressOf:=True, isOperandOfConditionalBranch:=False, eventContext:=False) End If ' If 'target' is a bound constructor group, we need to do special checks and special processing of arguments. If target.Kind = BoundKind.MethodGroup Then Dim group = DirectCast(target, BoundMethodGroup) If IsGroupOfConstructors(group) Then Return BindDirectConstructorCall(node, group, diagnostics) End If End If Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Me.BindArgumentsAndNames(node.ArgumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) If target.Kind = BoundKind.MethodGroup OrElse target.Kind = BoundKind.PropertyGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, ExtractTypeCharacter(node.Expression), DirectCast(target, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, diagnostics:=diagnostics) End If If target.Kind = BoundKind.NamespaceExpression Then Dim namespaceExp As BoundNamespaceExpression = DirectCast(target, BoundNamespaceExpression) Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_NamespaceNotExpression1, namespaceExp.NamespaceSymbol) ReportDiagnostic(diagnostics, node.Expression, diagInfo) ElseIf target.Kind = BoundKind.TypeExpression Then Dim typeExp As BoundTypeExpression = DirectCast(target, BoundTypeExpression) If Not IsCallStatementContext(node) Then ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(typeExp, diagnostics) If instance IsNot Nothing Then Return BindIndexedInvocationExpression( node, instance, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=False, diagnostics:=diagnostics) End If End If Dim diagInfo = ErrorFactory.ErrorInfo(GetTypeNotExpressionErrorId(typeExp.Type), typeExp.Type) ReportDiagnostic(diagnostics, node.Expression, diagInfo) Else Return BindIndexedInvocationExpression( node, target, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, hasIndexableTarget:=False, diagnostics:=diagnostics) End If Return GenerateBadExpression(node, target, boundArguments) End Function ''' <summary> ''' Bind an invocation expression representing an array access, ''' delegate invocation, or default member. ''' </summary> Private Function BindIndexedInvocationExpression( node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, <Out()> ByRef hasIndexableTarget As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(target.Kind <> BoundKind.NamespaceExpression) Debug.Assert(target.Kind <> BoundKind.TypeExpression) Debug.Assert(target.Kind <> BoundKind.MethodGroup) Debug.Assert(target.Kind <> BoundKind.PropertyGroup) hasIndexableTarget = False If Not target.IsLValue AndAlso target.Kind <> BoundKind.LateMemberAccess Then target = MakeRValue(target, diagnostics) End If Dim targetType As TypeSymbol = target.Type ' there are values or variables like "Nothing" which have no type If targetType IsNot Nothing Then ' this method is also called for e.g. Arrays because they are also InvocationExpressions ' if target is an array, then call BindArrayAccess only if target is not a direct successor ' of a call statement If targetType.IsArrayType Then hasIndexableTarget = True ' only bind to an array if this method was called outside of a call statement context If Not IsCallStatementContext(node) Then Return BindArrayAccess(node, target, boundArguments, argumentNames, diagnostics) End If ElseIf targetType.Kind = SymbolKind.NamedType AndAlso targetType.TypeKind = TypeKind.Delegate Then hasIndexableTarget = True ' an invocation of a delegate actually calls the delegate's Invoke method. Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod If delegateInvoke Is Nothing Then If Not target.HasErrors Then ReportDiagnostic(diagnostics, target.Syntax, ERRID.ERR_DelegateNoInvoke1, target.Type) End If ElseIf ReportDelegateInvokeUseSite(diagnostics, target.Syntax, targetType, delegateInvoke) Then delegateInvoke = Nothing End If If delegateInvoke IsNot Nothing Then Dim methodGroup = New BoundMethodGroup( If(node.Expression, node), Nothing, ImmutableArray.Create(Of MethodSymbol)(delegateInvoke), LookupResultKind.Good, target, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() Return BindInvocationExpression( node, If(node.Expression, node), ExtractTypeCharacter(node.Expression), methodGroup, boundArguments, argumentNames, diagnostics, callerInfoOpt:=node, representCandidateInDiagnosticsOpt:=targetType) Else Dim badExpressionChildren = ArrayBuilder(Of BoundExpression).GetInstance() badExpressionChildren.Add(target) badExpressionChildren.AddRange(boundArguments) Return BadExpression(node, badExpressionChildren.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType) End If End If End If If target.Kind = BoundKind.BadExpression Then ' Error already reported for a bad expression, so don't report another error ElseIf Not IsCallStatementContext(node) Then ' If the invocation is outside of a call statement ' context, bind to the default property group if any. If target.Type.SpecialType = SpecialType.System_Object OrElse target.Type.SpecialType = SpecialType.System_Array Then hasIndexableTarget = True Return BindLateBoundInvocation(node, Nothing, target, boundArguments, argumentNames, diagnostics, suppressLateBindingResolutionDiagnostics:=(target.Kind = BoundKind.LateMemberAccess)) End If If Not target.HasErrors Then ' Bind to the default property group. Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(If(node.Expression, node), target, diagnostics) If defaultPropertyGroup IsNot Nothing Then Debug.Assert(defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors) hasIndexableTarget = True If defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, TypeCharacter.None, DirectCast(defaultPropertyGroup, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments, diagnostics) End If Else ReportNoDefaultProperty(target, diagnostics) End If End If ElseIf target.Kind = BoundKind.LateMemberAccess Then hasIndexableTarget = True Dim lateMember = DirectCast(target, BoundLateMemberAccess) Return BindLateBoundInvocation(node, Nothing, lateMember, boundArguments, argumentNames, diagnostics) ElseIf Not target.HasErrors Then ' "Expression is not a method." Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedProcedure) ReportDiagnostic(diagnostics, If(node.Expression, node), diagInfo) End If Return GenerateBadExpression(node, target, boundArguments) End Function Private Function BindInvocationExpressionPossiblyWithoutArguments( node As InvocationExpressionSyntax, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression ' Spec §11.8 Invocation Expressions ' ... ' If the method group only contains one accessible method, including both instance and ' extension methods, and that method takes no arguments and is a function, then the method ' group is interpreted as an invocation expression with an empty argument list and the result ' is used as the target of an invocation expression with the provided argument list(s). If allowBindingWithoutArguments AndAlso boundArguments.Length > 0 AndAlso Not IsCallStatementContext(node) AndAlso ShouldBindWithoutArguments(node, group, diagnostics) Then Dim tmpDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) Dim result As BoundExpression = Nothing Debug.Assert(node.Expression IsNot Nothing) ' NOTE: when binding without arguments, we pass node.Expression as the first parameter ' so that the new bound node references it instead of invocation expression Dim withoutArgs = BindInvocationExpression( node.Expression, node.Expression, typeChar, group, ImmutableArray(Of BoundExpression).Empty, Nothing, tmpDiagnostics, callerInfoOpt:=group.Syntax) If withoutArgs.Kind = BoundKind.Call OrElse withoutArgs.Kind = BoundKind.PropertyAccess Then ' We were able to bind the method group or property access without arguments, ' possibly with some diagnostic. diagnostics.AddRange(tmpDiagnostics) tmpDiagnostics.Clear() If withoutArgs.Kind = BoundKind.PropertyAccess Then Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundPropertyAccess).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If withoutArgs = MakeRValue(withoutArgs, diagnostics) Else Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundCall).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If End If If withoutArgs.Kind = BoundKind.BadExpression Then result = GenerateBadExpression(node, withoutArgs, boundArguments) Else Dim hasIndexableTarget = False ' Bind the invocation with arguments as an indexed invocation. Dim withArgs = BindIndexedInvocationExpression( node, withoutArgs, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=hasIndexableTarget, diagnostics:=tmpDiagnostics) If hasIndexableTarget Then diagnostics.AddRange(tmpDiagnostics) result = withArgs Else ' Report BC32016 if something wrong. ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_FunctionResultCannotBeIndexed1, withoutArgs.ExpressionSymbol) ' If result of binding with no args was not indexable after all, then instead ' of just producing a bad expression, bind the invocation expression normally, ' but without reporting any more diagnostics. This produces more accurate ' bound nodes for semantic model questions and may allow the type of the ' expression to be computed, thus leading to fewer errors later. result = BindInvocationExpression( node, node.Expression, typeChar, group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, callerInfoOpt:=group.Syntax) End If End If End If tmpDiagnostics.Free() If result IsNot Nothing Then Return result End If End If Return BindInvocationExpression( node, If(node.Expression, group.Syntax), typeChar, group, boundArguments, argumentNames, diagnostics, callerInfoOpt:=group.Syntax) End Function ''' <summary> ''' Returns a BoundPropertyGroup if the expression represents a valid ''' default property access. If there is a default property but the property ''' access is invalid, a BoundBadExpression is returned. If there is no ''' default property for the expression type, Nothing is returned. ''' ''' Note, that default Query Indexer may be a method, not a property. ''' </summary> Private Function BindDefaultPropertyGroup(node As VisualBasicSyntaxNode, target As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression Dim result = LookupResult.GetInstance() Dim defaultMemberGroup As BoundExpression = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) MemberLookup.LookupDefaultProperty(result, target.Type, Me, useSiteInfo) ' We're not reporting any diagnostic if there are no symbols. Debug.Assert(result.HasSymbol OrElse Not result.HasDiagnostic) If result.HasSymbol Then defaultMemberGroup = BindSymbolAccess(node, result, LookupOptions.Default, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) Debug.Assert(defaultMemberGroup IsNot Nothing) Debug.Assert((defaultMemberGroup.Kind = BoundKind.BadExpression) OrElse (defaultMemberGroup.Kind = BoundKind.PropertyGroup)) Else ' All queryable sources have default indexer, which maps to an ElementAtOrDefault method or property on the source. Dim tempDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) target = MakeRValue(target, tempDiagnostics) Dim controlVariableType As TypeSymbol = Nothing target = ConvertToQueryableType(target, tempDiagnostics, controlVariableType) If controlVariableType IsNot Nothing Then result.Clear() Const options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity. LookupMember(result, target.Type, StringConstants.ElementAtMethod, 0, options, useSiteInfo) If result.IsGood Then Dim kind As SymbolKind = result.Symbols(0).Kind If kind = SymbolKind.Method OrElse kind = SymbolKind.Property Then diagnostics.AddRange(tempDiagnostics) defaultMemberGroup = BindSymbolAccess(node, result, options, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) End If End If End If tempDiagnostics.Free() End If diagnostics.Add(node, useSiteInfo) result.Free() ' We don't want the default property GROUP to override the meaning of the item it's being ' accessed off of, so mark it as compiler generated. If defaultMemberGroup IsNot Nothing Then defaultMemberGroup.SetWasCompilerGenerated() End If Return defaultMemberGroup End Function ''' <summary> ''' Tests whether or not the method or property group should be bound without arguments. ''' In case of method group it may also update the group by filtering out all subs ''' </summary> Private Function ShouldBindWithoutArguments(node As VisualBasicSyntaxNode, ByRef group As BoundMethodOrPropertyGroup, diagnostics As BindingDiagnosticBag) As Boolean Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim result = ShouldBindWithoutArguments(group, useSiteInfo) diagnostics.Add(node, useSiteInfo) Return result End Function Private Function ShouldBindWithoutArguments(ByRef group As BoundMethodOrPropertyGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim newMethods As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() ' check method group members Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) ' any sub should be removed from a group in case we try binding without arguments Dim shouldUpdateGroup As Boolean = False Dim atLeastOneFunction As Boolean = False ' Dev10 behavior: ' For instance methods - ' Check if all functions from the group (ignoring subs) ' have the same arity as specified in the call and 0 parameters. ' However, the part that handles arity check is rather inconsistent between methods ' overloaded within the same type and in derived type. Also, language spec doesn't mention ' any restrictions for arity. So, we will not try to duplicate Dev10 logic around arity ' because the logic is close to impossible to match and behavior change will not be a breaking ' change. ' In presence of extension methods the rules are more constrained- ' If group contains an extension method, it must be the only method in the group, ' it must have no parameters, must have no type parameters and must be a Function. ' Note, we should avoid requesting AdditionalExtensionMethods whenever possible because ' lookup of extension methods might be very expensive. Dim extensionMethod As MethodSymbol = Nothing For Each method In methodGroup.Methods If method.IsReducedExtensionMethod Then extensionMethod = method Exit For End If If (method.IsSub) Then If method.CanBeCalledWithNoParameters() Then ' If its a sub that could be called parameterlessly, it might hide the function. So it is included ' in the group for further processing in overload resolution (which will process possible hiding). ' If overload resolution does select the Sub, we'll get an error about return type not indexable. ' See Roslyn bug 14019 for example. newMethods.Add(method) Else ' ignore other subs entirely shouldUpdateGroup = True End If ElseIf method.ParameterCount > 0 Then ' any function with more than 0 parameters newMethods.Free() Return False Else newMethods.Add(method) atLeastOneFunction = True End If Next If extensionMethod Is Nothing Then Dim additionalExtensionMethods As ImmutableArray(Of MethodSymbol) = methodGroup.AdditionalExtensionMethods(useSiteInfo) If additionalExtensionMethods.Length > 0 Then Debug.Assert(methodGroup.Methods.Length > 0) ' We have at least one extension method in the group and it is not the only one method in the ' group. Cannot apply default property transformation. newMethods.Free() Return False End If Else newMethods.Free() Debug.Assert(extensionMethod IsNot Nothing) ' This method must have no parameters, must have no type parameters and must not be a Sub. Return methodGroup.Methods.Length = 1 AndAlso methodGroup.TypeArgumentsOpt Is Nothing AndAlso extensionMethod.ParameterCount = 0 AndAlso extensionMethod.Arity = 0 AndAlso Not extensionMethod.IsSub AndAlso methodGroup.AdditionalExtensionMethods(useSiteInfo).Length = 0 End If If Not atLeastOneFunction Then newMethods.Free() Return False End If If shouldUpdateGroup Then ' at least one sub was removed If newMethods.IsEmpty Then ' no functions left newMethods.Free() Return False End If ' there are some functions, update the group group = methodGroup.Update(methodGroup.TypeArgumentsOpt, newMethods.ToImmutable(), Nothing, methodGroup.ResultKind, methodGroup.ReceiverOpt, methodGroup.QualificationKind) End If newMethods.Free() Return True Else ' check property group members Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Debug.Assert(propertyGroup.Properties.Length > 0) For Each prop In propertyGroup.Properties If (prop.ParameterCount > 0) Then Return False End If Next ' assuming property group was not empty Return True End If End Function Private Shared Function IsGroupOfConstructors(group As BoundMethodOrPropertyGroup) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) Return methodGroup.Methods(0).MethodKind = MethodKind.Constructor End If Return False End Function Friend Function BindInvocationExpression( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional allowConstructorCall As Boolean = False, Optional suppressAbstractCallDiagnostics As Boolean = False, Optional isDefaultMemberAccess As Boolean = False, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional forceExpandedForm As Boolean = False ) As BoundExpression Debug.Assert(group IsNot Nothing) Debug.Assert(allowConstructorCall OrElse Not IsGroupOfConstructors(group)) Debug.Assert(group.ResultKind = LookupResultKind.Good OrElse group.ResultKind = LookupResultKind.Inaccessible) ' It is possible to get here with method group with ResultKind = LookupResultKind.Inaccessible. ' When this happens, it is worth trying to do overload resolution on the "bad" set ' to report better errors. Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, callerInfoOpt, useSiteInfo, forceExpandedForm:=forceExpandedForm) If diagnostics.Add(node, useSiteInfo) Then If group.ResultKind <> LookupResultKind.Inaccessible Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If End If If Not results.BestResult.HasValue Then If results.ResolutionIsLateBound Then Debug.Assert(OptionStrict <> VisualBasic.OptionStrict.On) ' Did we have extension methods among candidates? If group.Kind = BoundKind.MethodGroup Then Dim haveAnExtensionMethod As Boolean = False Dim methodGroup = DirectCast(group, BoundMethodGroup) For Each method As MethodSymbol In methodGroup.Methods If method.ReducedFrom IsNot Nothing Then haveAnExtensionMethod = True Exit For End If Next If Not haveAnExtensionMethod Then useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) haveAnExtensionMethod = Not methodGroup.AdditionalExtensionMethods(useSiteInfo).IsEmpty diagnostics.Add(node, useSiteInfo) End If If haveAnExtensionMethod Then ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, group), ERRID.ERR_ExtensionMethodCannotBeLateBound) Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() builder.Add(group) If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If Return New BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, builder.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If End If Return BindLateBoundInvocation(node, group, isDefaultMemberAccess, boundArguments, argumentNames, diagnostics) End If ' Create and report the diagnostic. If results.Candidates.Length = 0 Then results = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, includeEliminatedCandidates:=True, callerInfoOpt:=callerInfoOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded, forceExpandedForm:=forceExpandedForm) End If Return ReportOverloadResolutionFailureAndProduceBoundNode(node, group, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else Return CreateBoundCallOrPropertyAccess( node, target, typeChar, group, boundArguments, results.BestResult.Value, results.AsyncLambdaSubToFunctionMismatch, diagnostics, suppressAbstractCallDiagnostics) End If End Function Private Function CreateBoundCallOrPropertyAccess( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), bestResult As OverloadResolution.CandidateAnalysisResult, asyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag, Optional suppressAbstractCallDiagnostics As Boolean = False ) As BoundExpression Dim candidate = bestResult.Candidate Dim methodOrProperty = candidate.UnderlyingSymbol Dim returnType = candidate.ReturnType If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, target, GetInaccessibleErrorInfo(bestResult.Candidate.UnderlyingSymbol)) Else Debug.Assert(group.ResultKind = LookupResultKind.Good) CheckMemberTypeAccessibility(diagnostics, node, methodOrProperty) End If If bestResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(bestResult.TypeArgumentInferenceDiagnosticsOpt) End If Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bestResult, boundArguments, diagnostics) boundArguments = argumentInfo.Arguments Debug.Assert(Not boundArguments.IsDefault) Dim hasErrors As Boolean = False Dim receiver As BoundExpression = group.ReceiverOpt If group.ResultKind = LookupResultKind.Good Then hasErrors = CheckSharedSymbolAccess(target, methodOrProperty.IsShared, receiver, group.QualificationKind, diagnostics) ' give diagnostics if sharedness is wrong. End If ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, methodOrProperty, node) hasErrors = hasErrors Or group.HasErrors If Not returnType.IsErrorType() Then VerifyTypeCharacterConsistency(node, returnType, typeChar, diagnostics) End If Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing If receiver IsNot Nothing AndAlso Not hasErrors Then receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, methodOrProperty.IsShared, diagnostics, resolvedTypeOrValueReceiver) End If If Not suppressAbstractCallDiagnostics AndAlso receiver IsNot Nothing AndAlso (receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then If methodOrProperty.IsMustOverride Then ' Generate an error, but continue processing ReportDiagnostic(diagnostics, group.Syntax, If(receiver.IsMyBaseReference, ERRID.ERR_MyBaseAbstractCall1, ERRID.ERR_MyClassAbstractCall1), methodOrProperty) End If End If If Not asyncLambdaSubToFunctionMismatch.IsEmpty Then For Each lambda In asyncLambdaSubToFunctionMismatch Dim errorLocation As SyntaxNode = lambda.Syntax Dim lambdaNode = TryCast(errorLocation, LambdaExpressionSyntax) If lambdaNode IsNot Nothing Then errorLocation = lambdaNode.SubOrFunctionHeader End If ReportDiagnostic(diagnostics, errorLocation, ERRID.WRN_AsyncSubCouldBeFunction) Next End If If methodOrProperty.Kind = SymbolKind.Method Then Dim method = DirectCast(methodOrProperty, MethodSymbol) Dim reducedFrom = method.ReducedFrom Dim constantValue As ConstantValue = Nothing If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If If method.IsUserDefinedOperator() AndAlso Me.ContainingMember Is method Then ReportDiagnostic(diagnostics, target, ERRID.WRN_RecursiveOperatorCall, method) End If ' replace call with literal if possible (Chr, ChrW, Asc, AscW) constantValue = OptimizeLibraryCall(method, boundArguments, node, hasErrors, diagnostics) Else ' We are calling an extension method, prepare the receiver to be ' passed as the first parameter. receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, method.ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the method group ' NOTE: we only remove it if we pass it to a new BoundCall node, ' otherwise we keep it in the group to support semantic queries Dim methodGroup = DirectCast(group, BoundMethodGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, methodGroup.ReceiverOpt)) methodGroup = methodGroup.Update(methodGroup.TypeArgumentsOpt, methodGroup.Methods, methodGroup.PendingExtensionMethodsOpt, methodGroup.ResultKind, newReceiver, methodGroup.QualificationKind) Return New BoundCall( node, method, methodGroup, receiver, boundArguments, constantValue, returnType, suppressObjectClone:=False, hasErrors:=hasErrors, defaultArguments:=argumentInfo.DefaultArguments) Else Dim [property] = DirectCast(methodOrProperty, PropertySymbol) Dim reducedFrom = [property].ReducedFromDefinition Debug.Assert(Not boundArguments.Any(Function(a) a.Kind = BoundKind.ByRefArgumentWithCopyBack)) If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Else receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, [property].ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the property group ' NOTE: we only remove it if we pass it to a new BoundPropertyAccess node, ' otherwise we keep it in the group to support semantic queries Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, propertyGroup.ReceiverOpt)) propertyGroup = propertyGroup.Update(propertyGroup.Properties, propertyGroup.ResultKind, newReceiver, propertyGroup.QualificationKind) Return New BoundPropertyAccess( node, [property], propertyGroup, PropertyAccessKind.Unknown, [property].IsWritable(receiver, Me, isKnownTargetOfObjectMemberInitializer:=False), receiver, boundArguments, argumentInfo.DefaultArguments, hasErrors:=hasErrors) End If End Function Friend Sub WarnOnRecursiveAccess(propertyAccess As BoundPropertyAccess, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Dim [property] As PropertySymbol = propertyAccess.PropertySymbol If [property].ReducedFromDefinition Is Nothing AndAlso [property].ParameterCount = 0 AndAlso ([property].IsShared OrElse (propertyAccess.ReceiverOpt IsNot Nothing AndAlso propertyAccess.ReceiverOpt.Kind = BoundKind.MeReference)) Then Dim reportRecursiveCall As Boolean = False If [property].GetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Get) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Get) = 0 Then reportRecursiveCall = True End If ElseIf [property].SetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Set) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Set) = 0 Then reportRecursiveCall = True End If End If If reportRecursiveCall Then ReportDiagnostic(diagnostics, propertyAccess.Syntax, ERRID.WRN_RecursivePropertyCall, [property]) End If End If End Sub Friend Sub WarnOnRecursiveAccess(node As BoundExpression, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Select Case node.Kind Case BoundKind.XmlMemberAccess ' Nothing to do Case BoundKind.PropertyAccess WarnOnRecursiveAccess(DirectCast(node, BoundPropertyAccess), accessKind, diagnostics) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Sub Private Function UpdateReceiverForExtensionMethodOrPropertyGroup( receiver As BoundExpression, targetType As TypeSymbol, thisParameterDefinition As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression If receiver IsNot Nothing AndAlso receiver.IsValue AndAlso Not targetType.IsErrorType() AndAlso Not receiver.Type.IsErrorType() Then Dim oldReceiver As BoundExpression = receiver Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) receiver = PassArgument(receiver, Conversions.ClassifyConversion(receiver, targetType, Me, useSiteInfo), False, Conversions.ClassifyConversion(targetType, receiver.Type, useSiteInfo), targetType, thisParameterDefinition, diagnostics) diagnostics.Add(receiver, useSiteInfo) If oldReceiver.WasCompilerGenerated AndAlso receiver IsNot oldReceiver Then Select Case oldReceiver.Kind Case BoundKind.MeReference, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder receiver.SetWasCompilerGenerated() End Select End If End If Return receiver End Function Private Function IsWellKnownTypeMember(memberId As WellKnownMember, method As MethodSymbol) As Boolean Return Compilation.GetWellKnownTypeMember(memberId) Is method End Function ''' <summary> ''' Optimizes some runtime library calls through replacing them with a literal if possible. ''' VB Spec 11.2 defines the following runtime functions as being constant: ''' - Microsoft.VisualBasic.Strings.ChrW ''' - Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ''' - Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ''' - Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ''' </summary> ''' <param name="method">The method.</param> ''' <param name="arguments">The arguments of the method call.</param> ''' <param name="syntax">The syntax node for report errors.</param> ''' <param name="diagnostics">The diagnostics.</param> ''' <param name="hasErrors">Set to true if there are conversion errors (e.g. Asc("")). Otherwise it's not written to.</param> ''' <returns>The constant value that replaces this node, or nothing.</returns> Private Function OptimizeLibraryCall( method As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), syntax As SyntaxNode, ByRef hasErrors As Boolean, diagnostics As BindingDiagnosticBag ) As ConstantValue ' cheapest way to filter out methods that do not match If arguments.Length = 1 AndAlso arguments(0).IsConstant AndAlso Not arguments(0).ConstantValueOpt.IsBad Then ' only continue checking if containing type is Microsoft.VisualBasic.Strings If Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Strings) IsNot method.ContainingType Then Return Nothing End If ' AscW(char) / AscW(String) ' all values can be optimized as a literal, except an empty string that produces a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWStringInt32, method) Then Dim argumentConstantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If argumentConstantValue.IsNull Then argumentValue = String.Empty ElseIf argumentConstantValue.IsChar Then argumentValue = argumentConstantValue.CharValue Else Debug.Assert(argumentConstantValue.IsString()) argumentValue = argumentConstantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(AscW(argumentValue)) End If ' ChrW ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(ChrW(argumentValue)) End If ' Asc(Char) / Asc(String) ' all values from 0 to 127 can be optimized to a literal. If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, method) Then Dim constantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If constantValue.IsNull Then argumentValue = String.Empty ElseIf constantValue.IsChar Then argumentValue = constantValue.CharValue Else Debug.Assert(constantValue.IsString()) argumentValue = constantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If ' we are only folding 7bit ASCII chars, so it's ok to use AscW here, although this is the Asc folding. Dim charValue = AscW(argumentValue) If charValue < 128 Then Return ConstantValue.Create(charValue) End If Return Nothing End If ' Chr ' values from 0 to 127 can be optimized as a literal ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue >= 0 AndAlso argumentValue < 128 Then Return ConstantValue.Create(ChrW(argumentValue)) ElseIf argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If End If End If Return Nothing End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, group, overrideCommonReturnType, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance() Dim bestSymbols = ImmutableArray(Of Symbol).Empty Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(results, bestCandidates, bestSymbols) If overrideCommonReturnType IsNot Nothing Then commonReturnType = overrideCommonReturnType End If Dim result As BoundExpression = ReportOverloadResolutionFailureAndProduceBoundNode( node, lookupResult, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, groupOpt, Nothing, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) bestCandidates.Free() Return result End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, group, delegateSymbol, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt) End Function Public Shared Function GetLocationForOverloadResolutionDiagnostic(node As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing) As Location Dim result As SyntaxNode If groupOpt IsNot Nothing Then If node.SyntaxTree Is groupOpt.Syntax.SyntaxTree AndAlso node.Span.Contains(groupOpt.Syntax.Span) Then result = groupOpt.Syntax If result Is node AndAlso (groupOpt.ReceiverOpt Is Nothing OrElse groupOpt.ReceiverOpt.Syntax Is result) Then Return result.GetLocation() End If Else Return node.GetLocation() End If ElseIf node.IsKind(SyntaxKind.InvocationExpression) Then result = If(DirectCast(node, InvocationExpressionSyntax).Expression, node) Else Return node.GetLocation() End If Select Case result.Kind Case SyntaxKind.QualifiedName Return DirectCast(result, QualifiedNameSyntax).Right.GetLocation() Case SyntaxKind.SimpleMemberAccessExpression If result.Parent IsNot Nothing AndAlso result.Parent.IsKind(SyntaxKind.AddressOfExpression) Then Return result.GetLocation() End If Return DirectCast(result, MemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression Return DirectCast(result, XmlMemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.HandlesClauseItem Return DirectCast(result, HandlesClauseItemSyntax).EventMember.GetLocation() End Select Return result.GetLocation() End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Debug.Assert(commonReturnType IsNot Nothing AndAlso bestSymbols.Length > 0 AndAlso bestCandidates.Count >= bestSymbols.Length) Debug.Assert(groupOpt Is Nothing OrElse lookupResult = groupOpt.ResultKind) Dim state = OverloadResolution.CandidateAnalysisResultState.Count If bestCandidates.Count > 0 Then state = bestCandidates(0).State End If If boundArguments.IsDefault Then boundArguments = ImmutableArray(Of BoundExpression).Empty End If Dim singleCandidateAnalysisResult As OverloadResolution.CandidateAnalysisResult = Nothing Dim singleCandidate As OverloadResolution.Candidate = Nothing Dim allowUnexpandedParamArrayForm As Boolean = False Dim allowExpandedParamArrayForm As Boolean = False ' Figure out if we should report single candidate errors If bestSymbols.Length = 1 AndAlso bestCandidates.Count < 3 Then singleCandidateAnalysisResult = bestCandidates(0) singleCandidate = singleCandidateAnalysisResult.Candidate allowExpandedParamArrayForm = singleCandidateAnalysisResult.IsExpandedParamArrayForm allowUnexpandedParamArrayForm = Not allowExpandedParamArrayForm If bestCandidates.Count > 1 Then If bestCandidates(1).IsExpandedParamArrayForm Then allowExpandedParamArrayForm = True Else allowUnexpandedParamArrayForm = True End If End If End If If lookupResult = LookupResultKind.Inaccessible Then If singleCandidate IsNot Nothing Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), GetInaccessibleErrorInfo(singleCandidate.UnderlyingSymbol)) Else If Not queryMode Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), ERRID.ERR_NoViableOverloadCandidates1, bestSymbols(0).Name) End If ' Do not report more errors. GoTo ProduceBoundNode End If Else Debug.Assert(lookupResult = LookupResultKind.Good) End If If diagnosticLocationOpt Is Nothing Then diagnosticLocationOpt = GetLocationForOverloadResolutionDiagnostic(node, groupOpt) End If ' Report diagnostic according to the state of candidates Select Case state Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError, OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_BadOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.Ambiguous Dim candidate As Symbol = bestSymbols(0).OriginalDefinition Dim container As Symbol = candidate.ContainingSymbol ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_MetadataMembersAmbiguous3, candidate.Name, container.GetKindText(), container) Case OverloadResolution.CandidateAnalysisResultState.BadGenericArity Debug.Assert(groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.MethodGroup) Dim mg = DirectCast(groupOpt, BoundMethodGroup) If singleCandidate IsNot Nothing Then Dim typeArguments = If(mg.TypeArgumentsOpt IsNot Nothing, mg.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty) If typeArguments.IsDefault Then typeArguments = ImmutableArray(Of TypeSymbol).Empty End If Dim singleSymbol As Symbol = singleCandidate.UnderlyingSymbol Dim isExtension As Boolean = singleCandidate.IsExtensionMethod If singleCandidate.Arity < typeArguments.Length Then If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric2, ERRID.ERR_TooManyGenericArguments2), singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric1, ERRID.ERR_TooManyGenericArguments1), singleSymbol) End If Else Debug.Assert(singleCandidate.Arity > typeArguments.Length) If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments2, singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments1, singleSymbol) End If End If Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoTypeArgumentCountOverloadCand1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch If node.Kind = SyntaxKind.IdentifierName AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.NamedFieldInitializer AndAlso groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.PropertyGroup Then ' report special diagnostics for a failed overload resolution because all available properties ' require arguments in case this method was called while binding a object member initializer. ReportDiagnostic(diagnostics, diagnosticLocationOpt, If(singleCandidate IsNot Nothing, ERRID.ERR_ParameterizedPropertyInAggrInit1, ERRID.ERR_NoZeroCountArgumentInitCandidates1), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) Else If singleCandidate IsNot Nothing AndAlso (Not queryMode OrElse singleCandidate.ParameterCount <= boundArguments.Length) Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoArgumentCountOverloadCandidates1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch, OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Dim haveBadArgument As Boolean = False For i As Integer = 0 To boundArguments.Length - 1 Step 1 Dim type = boundArguments(i).Type If boundArguments(i).HasErrors OrElse (type IsNot Nothing AndAlso type.IsErrorType()) Then haveBadArgument = True Exit For End If Next If Not haveBadArgument Then If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoCallableOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If End If Case OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_NoCallableOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case OverloadResolution.CandidateAnalysisResultState.Applicable ' it is only possible to get overloading failure with a single candidate ' if we have a paramarray with equally specific virtual signatures Debug.Assert(singleCandidate Is Nothing OrElse singleCandidate.ParameterCount <> 0 AndAlso singleCandidate.Parameters(singleCandidate.ParameterCount - 1).IsParamArray) If bestCandidates(0).RequiresNarrowingConversion Then ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) Else ReportUnspecificProcedures(diagnosticLocationOpt, bestSymbols, diagnostics, (delegateSymbol IsNot Nothing)) End If Case Else ' Unexpected Throw ExceptionUtilities.UnexpectedValue(state) End Select ProduceBoundNode: Dim childBoundNodes As ImmutableArray(Of BoundExpression) If boundArguments.IsEmpty AndAlso boundTypeExpression Is Nothing Then If groupOpt Is Nothing Then childBoundNodes = ImmutableArray(Of BoundExpression).Empty Else childBoundNodes = ImmutableArray.Create(Of BoundExpression)(groupOpt) End If Else Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() If groupOpt IsNot Nothing Then builder.Add(groupOpt) End If If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If If boundTypeExpression IsNot Nothing Then builder.Add(boundTypeExpression) End If childBoundNodes = builder.ToImmutableAndFree() End If Dim resultKind = LookupResultKind.OverloadResolutionFailure If lookupResult < resultKind Then resultKind = lookupResult End If Return New BoundBadExpression(node, resultKind, bestSymbols, childBoundNodes, commonReturnType, hasErrors:=True) End Function ''' <summary> '''Figure out the set of best candidates in the following preference order: ''' 1) Applicable ''' 2) ArgumentMismatch, GenericConstraintsViolated ''' 3) TypeInferenceFailed ''' 4) ArgumentCountMismatch ''' 5) BadGenericArity ''' 6) Ambiguous ''' 7) HasUseSiteError ''' 8) HasUnsupportedMetadata ''' ''' Also return the set of unique symbols behind the set. ''' ''' Returns type symbol for the common type, if any. ''' Otherwise returns ErrorTypeSymbol.UnknownResultType. ''' </summary> Private Shared Function GetSetOfTheBestCandidates( ByRef results As OverloadResolution.OverloadResolutionResult, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), ByRef bestSymbols As ImmutableArray(Of Symbol) ) As TypeSymbol Const Applicable = OverloadResolution.CandidateAnalysisResultState.Applicable Const ArgumentMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch Const GenericConstraintsViolated = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Const TypeInferenceFailed = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Const ArgumentCountMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch Const BadGenericArity = OverloadResolution.CandidateAnalysisResultState.BadGenericArity Const Ambiguous = OverloadResolution.CandidateAnalysisResultState.Ambiguous Const HasUseSiteError = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError Const HasUnsupportedMetadata = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Dim preference(OverloadResolution.CandidateAnalysisResultState.Count - 1) As Integer preference(Applicable) = 1 preference(ArgumentMismatch) = 2 preference(GenericConstraintsViolated) = 2 preference(TypeInferenceFailed) = 3 preference(ArgumentCountMismatch) = 4 preference(BadGenericArity) = 5 preference(Ambiguous) = 6 preference(HasUseSiteError) = 7 preference(HasUnsupportedMetadata) = 8 For Each candidate In results.Candidates Dim prefNew = preference(candidate.State) If prefNew <> 0 Then If bestCandidates.Count = 0 Then bestCandidates.Add(candidate) Else Dim prefOld = preference(bestCandidates(0).State) If prefNew = prefOld Then bestCandidates.Add(candidate) ElseIf prefNew < prefOld Then bestCandidates.Clear() bestCandidates.Add(candidate) End If End If End If Next ' Collect unique best symbols. Dim bestSymbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(bestCandidates.Count) Dim commonReturnType As TypeSymbol = Nothing If bestCandidates.Count = 1 Then ' For multiple candidates we never pick common type that refers to method's type parameter ' because each method has distinct type parameters. For single candidate case we need to ' ensure this explicitly. Dim underlyingSymbol As Symbol = bestCandidates(0).Candidate.UnderlyingSymbol bestSymbolsBuilder.Add(underlyingSymbol) commonReturnType = bestCandidates(0).Candidate.ReturnType If underlyingSymbol.Kind = SymbolKind.Method Then Dim method = DirectCast(underlyingSymbol, MethodSymbol) If method.IsGenericMethod AndAlso commonReturnType.ReferencesMethodsTypeParameter(method) Then Select Case CInt(bestCandidates(0).State) Case TypeInferenceFailed, HasUseSiteError, HasUnsupportedMetadata, BadGenericArity, ArgumentCountMismatch commonReturnType = Nothing End Select End If End If Else For i As Integer = 0 To bestCandidates.Count - 1 Step 1 If i = 0 OrElse Not bestSymbolsBuilder(bestSymbolsBuilder.Count - 1).Equals(bestCandidates(i).Candidate.UnderlyingSymbol) Then bestSymbolsBuilder.Add(bestCandidates(i).Candidate.UnderlyingSymbol) Dim returnType = bestCandidates(i).Candidate.ReturnType If commonReturnType Is Nothing Then commonReturnType = returnType ElseIf commonReturnType IsNot ErrorTypeSymbol.UnknownResultType AndAlso Not commonReturnType.IsSameTypeIgnoringAll(returnType) Then commonReturnType = ErrorTypeSymbol.UnknownResultType End If End If Next End If bestSymbols = bestSymbolsBuilder.ToImmutableAndFree() Return If(commonReturnType, ErrorTypeSymbol.UnknownResultType) End Function Private Shared Sub ReportUnspecificProcedures( diagnosticLocation As Location, bestSymbols As ImmutableArray(Of Symbol), diagnostics As BindingDiagnosticBag, isDelegateContext As Boolean ) Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(bestSymbols.Length) Dim notMostSpecificMessage = ErrorFactory.ErrorInfo(ERRID.ERR_NotMostSpecificOverload) Dim withContainingTypeInDiagnostics As Boolean = False If Not bestSymbols(0).IsReducedExtensionMethod Then Dim container As NamedTypeSymbol = bestSymbols(0).ContainingType For i As Integer = 1 To bestSymbols.Length - 1 Step 1 If Not TypeSymbol.Equals(bestSymbols(i).ContainingType, container, TypeCompareKind.ConsiderEverything) Then withContainingTypeInDiagnostics = True End If Next End If For i As Integer = 0 To bestSymbols.Length - 1 Step 1 ' in delegate context we just output for each candidates ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer) ' Public Sub goo(p As Integer) ' ' in other contexts we give more information, e.g. ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer): <reason> ' Public Sub goo(p As Integer): <reason> Dim bestSymbol As Symbol = bestSymbols(i) Dim bestSymbolIsExtension As Boolean = bestSymbol.IsReducedExtensionMethod If isDelegateContext Then If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate2, bestSymbol, bestSymbol.ContainingType)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, bestSymbol)) End If Else If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, bestSymbol, bestSymbol.ContainingType, notMostSpecificMessage)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol), notMostSpecificMessage)) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, bestSymbol, notMostSpecificMessage)) End If End If Next ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(If(isDelegateContext, ERRID.ERR_AmbiguousDelegateBinding2, ERRID.ERR_NoMostSpecificOverload2), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0)), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree()) )) End Sub Private Sub ReportOverloadResolutionFailureForASetOfCandidates( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, errorNo As ERRID, candidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode ) Dim diagnosticPerSymbol = ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))).GetInstance(candidates.Count) If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If For i As Integer = 0 To candidates.Count - 1 Step 1 ' See if we need to consider both expanded and unexpanded version of the same method. ' We want to report only one set of errors in this case. ' Note, that, when OverloadResolution collects candidates expanded form always ' immediately follows unexpanded form, if both should be considered. Dim allowExpandedParamArrayForm As Boolean = candidates(i).IsExpandedParamArrayForm Dim allowUnexpandedParamArrayForm As Boolean = Not allowExpandedParamArrayForm If allowUnexpandedParamArrayForm AndAlso i + 1 < candidates.Count AndAlso candidates(i + 1).IsExpandedParamArrayForm AndAlso candidates(i + 1).Candidate.UnderlyingSymbol.Equals(candidates(i).Candidate.UnderlyingSymbol) Then allowExpandedParamArrayForm = True i += 1 End If Dim candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) ' Collect diagnostic for this candidate ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocation, lookupResult, candidates(i), arguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, False, errorNo = If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), candidateDiagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=Nothing) diagnosticPerSymbol.Add(KeyValuePairUtil.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) Next ' See if there are errors that are reported for each candidate at the same location within a lambda argument. ' Report them and don't report remaining diagnostics for each symbol separately. If Not ReportCommonErrorsFromLambdas(diagnosticPerSymbol, arguments, diagnostics) Then Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(candidates.Count) For i As Integer = 0 To diagnosticPerSymbol.Count - 1 Dim symbol = diagnosticPerSymbol(i).Key Dim isExtension As Boolean = symbol.IsReducedExtensionMethod() Dim sealedCandidateDiagnostics = diagnosticPerSymbol(i).Value.Diagnostics ' When reporting errors for an AddressOf, Dev 10 shows different error messages depending on how many ' errors there are per candidate. ' One narrowing error will be shown like: ' 'Public Sub goo6(p As Integer, p2 As Byte)': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. ' More than one narrowing issues in the parameters are abbreviated with: ' 'Public Sub goo6(p As Byte, p2 As Byte)': Method does not have a signature compatible with the delegate. If delegateSymbol Is Nothing OrElse Not sealedCandidateDiagnostics.Skip(1).Any() Then If isExtension Then For Each iDiagnostic In sealedCandidateDiagnostics diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next Else For Each iDiagnostic In sealedCandidateDiagnostics Dim msg = VisualBasicDiagnosticFormatter.Instance.Format(iDiagnostic.WithLocation(Location.None)) diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next End If Else If isExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) End If End If Next Dim diagnosticCompoundInfos() As DiagnosticInfo = diagnosticInfos.ToArrayAndFree() If delegateSymbol Is Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) Else ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), CustomSymbolDisplayFormatter.DelegateSignature(delegateSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) End If End If diagnosticPerSymbol.Free() End Sub Private Shared Function ReportCommonErrorsFromLambdas( diagnosticPerSymbol As ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))), arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As Boolean Dim haveCommonErrors As Boolean = False For Each diagnostic In diagnosticPerSymbol(0).Value.Diagnostics If diagnostic.Severity <> DiagnosticSeverity.Error Then Continue For End If For Each argument In arguments If argument.Syntax.SyntaxTree Is diagnostic.Location.SourceTree AndAlso argument.Kind = BoundKind.UnboundLambda Then If argument.Syntax.Span.Contains(diagnostic.Location.SourceSpan) Then Dim common As Boolean = True For i As Integer = 1 To diagnosticPerSymbol.Count - 1 If Not diagnosticPerSymbol(i).Value.Diagnostics.Contains(diagnostic) Then common = False Exit For End If Next If common Then haveCommonErrors = True diagnostics.Add(diagnostic) End If Exit For End If End If Next Next Return haveCommonErrors End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments. Anything that ''' OverloadResolution.MatchArguments flags as an error should be detected by ''' this function as well. ''' </summary> Private Sub ReportOverloadResolutionFailureForASingleCandidate( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, ByRef candidateAnalysisResult As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), allowUnexpandedParamArrayForm As Boolean, allowExpandedParamArrayForm As Boolean, includeMethodNameInErrorMessages As Boolean, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode, representCandidateInDiagnosticsOpt As Symbol ) Dim candidate As OverloadResolution.Candidate = candidateAnalysisResult.Candidate If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If Debug.Assert(argumentNames.IsDefaultOrEmpty OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length)) Debug.Assert(allowUnexpandedParamArrayForm OrElse allowExpandedParamArrayForm) If candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Then If lookupResult <> LookupResultKind.Inaccessible Then Debug.Assert(lookupResult = LookupResultKind.Good) ReportUseSite(diagnostics, diagnosticLocation, candidate.UnderlyingSymbol.GetUseSiteInfo()) End If Return End If ' To simplify following code If Not argumentNames.IsDefault AndAlso argumentNames.Length = 0 Then argumentNames = Nothing End If Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance(candidate.ParameterCount, -1) Dim paramArrayItems As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance() Try '§11.8.2 Applicable Methods '1. First, match each positional argument in order to the list of method parameters. 'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. 'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments. 'If a positional argument is omitted, the method is not applicable. ' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable." ' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional. Dim positionalArguments As Integer = 0 Dim paramIndex = 0 Dim someArgumentsBad As Boolean = False Dim someParamArrayArgumentsBad As Boolean = False Dim seenOutOfPositionNamedArgIndex As Integer = -1 Dim candidateSymbol As Symbol = candidate.UnderlyingSymbol Dim candidateIsExtension As Boolean = candidate.IsExtensionMethod For i As Integer = 0 To arguments.Length - 1 Step 1 ' A named argument which is used in-position counts as positional If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then Exit For End If If paramIndex <> i Then ' all remaining arguments must be named seenOutOfPositionNamedArgIndex = i Exit For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then Exit For End If Debug.Assert(parameterToArgumentMap(paramIndex) = -1) End If If paramIndex = candidate.ParameterCount Then If Not someArgumentsBad Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If ElseIf paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' Collect ParamArray arguments While i < arguments.Length If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then ' First named argument Continue For End If If arguments(i).Kind = BoundKind.OmittedArgument Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_OmittedParamArrayArgument) someParamArrayArgumentsBad = True Else paramArrayItems.Add(i) End If positionalArguments += 1 i += 1 End While Exit For Else parameterToArgumentMap(paramIndex) = i paramIndex += 1 End If positionalArguments += 1 Next Dim skippedSomeArguments As Boolean = False '§11.8.2 Applicable Methods '2. Next, match each named argument to a parameter with the given name. 'If one of the named arguments fails to match, matches a paramarray parameter, 'or matches an argument already matched with another positional or named argument, 'the method is not applicable. For i As Integer = positionalArguments To arguments.Length - 1 Step 1 Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0) If argumentNames(i) Is Nothing Then ' Unnamed argument follows out-of-position named arguments If Not someArgumentsBad Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(seenOutOfPositionNamedArgIndex).Syntax), ERRID.ERR_BadNonTrailingNamedArgument, argumentNames(seenOutOfPositionNamedArgIndex)) End If Return End If If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then ' ERRID_NamedParamNotFound1 ' ERRID_NamedParamNotFound2 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' ERRID_NamedParamArrayArgument ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamArrayArgument) someArgumentsBad = True Continue For End If If parameterToArgumentMap(paramIndex) <> -1 AndAlso arguments(parameterToArgumentMap(paramIndex)).Kind <> BoundKind.OmittedArgument Then ' ERRID_NamedArgUsedTwice1 ' ERRID_NamedArgUsedTwice2 ' ERRID_NamedArgUsedTwice3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If ' It is an error for a named argument to specify ' a value for an explicitly omitted positional argument. If paramIndex < positionalArguments Then 'ERRID_NamedArgAlsoOmitted1 'ERRID_NamedArgAlsoOmitted2 'ERRID_NamedArgAlsoOmitted3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If parameterToArgumentMap(paramIndex) = i Next ' Check whether type inference failed If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt) End If If candidate.IsGeneric AndAlso candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Then ' Bug 122092: AddressOf doesn't want detailed info on which parameters could not be ' inferred, just report the general type inference failed message in this case. If delegateSymbol IsNot Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_DelegateBindingTypeInferenceFails) Return End If If Not candidateAnalysisResult.SomeInferenceFailed Then Dim reportedAnError As Boolean = False For i As Integer = 0 To candidate.Arity - 1 Step 1 If candidateAnalysisResult.NotInferredTypeArguments(i) Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam1, candidate.TypeParameters(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam3, candidate.TypeParameters(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam2, candidate.TypeParameters(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If reportedAnError = True End If Next If reportedAnError Then Return End If End If Dim inferenceErrorReasons As InferenceErrorReasons = candidateAnalysisResult.InferenceErrorReasons If (inferenceErrorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous1, ERRID.ERR_TypeInferenceFailureAmbiguous1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous3, ERRID.ERR_TypeInferenceFailureAmbiguous3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous2, ERRID.ERR_TypeInferenceFailureAmbiguous2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If ElseIf (inferenceErrorReasons And InferenceErrorReasons.NoBest) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest1, ERRID.ERR_TypeInferenceFailureNoBest1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest3, ERRID.ERR_TypeInferenceFailureNoBest3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest2, ERRID.ERR_TypeInferenceFailureNoBest2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyResolvedErrors Then ' Already reported some errors, let's not report a general inference error Return End If If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit1, ERRID.ERR_TypeInferenceFailure1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit3, ERRID.ERR_TypeInferenceFailure3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit2, ERRID.ERR_TypeInferenceFailure2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If Return End If ' Check generic constraints for method type arguments. If candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Then Debug.Assert(candidate.IsGeneric) Debug.Assert(candidate.UnderlyingSymbol.Kind = SymbolKind.Method) Dim method = DirectCast(candidate.UnderlyingSymbol, MethodSymbol) ' TODO: Dev10 uses the location of the type parameter or argument that ' violated the constraint, rather than the entire invocation expression. Dim succeeded = method.CheckConstraints(diagnosticLocation, diagnostics, template:=GetNewCompoundUseSiteInfo(diagnostics)) Debug.Assert(Not succeeded) Return End If If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyErrors Then Return End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim argIndex As Integer Dim candidateIsAProperty As Boolean = (candidateSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim isByRef As Boolean = param.IsByRef Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then If targetType.Kind <> SymbolKind.ErrorType Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) End If someArgumentsBad = True Continue For ElseIf someParamArrayArgumentsBad Then Continue For End If If paramArrayItems.Count = 1 Then Dim paramArrayArgument = arguments(paramArrayItems(0)) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing If allowUnexpandedParamArrayForm AndAlso Not (Not paramArrayArgument.HasErrors AndAlso OverloadResolution.CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) Then allowUnexpandedParamArrayForm = False End If '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form If allowExpandedParamArrayForm AndAlso paramArrayArgument.IsNothingLiteral() Then allowExpandedParamArrayForm = False End If Else ' Unexpanded form is not applicable: there are either more than one value or no values. If Not allowExpandedParamArrayForm Then If paramArrayItems.Count = 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If someArgumentsBad = True Continue For End If allowUnexpandedParamArrayForm = False End If If allowUnexpandedParamArrayForm Then argument = arguments(paramArrayItems(0)) ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics) ElseIf allowExpandedParamArrayForm Then Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) someArgumentsBad = True Continue For End If Dim arrayElementType = arrayType.ElementType For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 argument = arguments(paramArrayItems(i)) ReportByValConversionErrors(param, argument, arrayElementType, reportNarrowingConversions, diagnostics) Next Else Debug.Assert(paramArrayItems.Count = 1) Dim paramArrayArgument = arguments(paramArrayItems(0)) ReportDiagnostic(diagnostics, paramArrayArgument.Syntax, ERRID.ERR_ParamArrayArgumentMismatch) End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) ' Argument nothing when the argument syntax is missing or BoundKind.OmittedArgument when the argument list contains commas ' for the missing syntax so we have to test for both. If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then If argument Is Nothing AndAlso skippedSomeArguments Then someArgumentsBad = True Continue For End If 'See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments ' Need to handle optional arguments here, there could be conversion errors, etc. ' reducedExtensionReceiverOpt is used to determine the default value of a CallerArgumentExpression when it refers to the first parameter of an extension method. ' Don't bother with correctly determining the correct value for this case since we're in an error case anyway. argument = GetArgumentForParameterDefaultValue(param, node, diagnostics, callerInfoOpt, parameterToArgumentMap, arguments, reducedExtensionReceiverOpt:=Nothing) If argument Is Nothing Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If End If Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If isByRef AndAlso Not candidateIsAProperty AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then ReportByRefConversionErrors(candidate, param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) Else ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) End If Next Finally paramArrayItems.Free() parameterToArgumentMap.Free() End Try End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByRefParameter ''' </summary> Private Sub ReportByRefConversionErrors( candidate As OverloadResolution.Candidate, param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return End If If argument.IsSupportingAssignment() Then If Not (argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type)) Then If Not ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) Then ' Check copy back conversion Dim boundTemp = New BoundRValuePlaceholder(argument.Syntax, targetType) Dim copyBackType = argument.GetTypeOfAssignmentTarget() Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(boundTemp, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then ' Possible only with user-defined conversions, I think. CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf Conversions.IsNarrowingConversion(conv.Key) Then Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0) If OptionStrict = VisualBasic.OptionStrict.On Then CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf reportNarrowingConversions Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentCopyBackNarrowing3, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType, copyBackType) End If End If End If End If Else ' No copy back needed ' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which ' would be an LValue field, if it were referred to in the constructor outside of a lambda, ' we need to report an error because the operation will result in a simulated pass by ' ref (through a temp, without a copy back), which might be not the intent. If Report_ERRID_ReadOnlyInClosure(argument) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ReadOnlyInClosure) End If ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) End If End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByValParameter. ''' </summary> Private Function ReportByValConversionErrors( param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) As Boolean ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return True End If Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If Dim requiresNarrowingConversion As Boolean = False If Conversions.IsNarrowingConversion(conv.Key) Then If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then If OptionStrict = VisualBasic.OptionStrict.On Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error ' because delegates have different error messages in case there is one or more candidates for narrowing ' indicate this as well. CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If End If requiresNarrowingConversion = True ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then ' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type ' as narrowing. requiresNarrowingConversion = True End If If reportNarrowingConversions AndAlso requiresNarrowingConversion Then Dim err As ERRID = ERRID.ERR_ArgumentNarrowing3 Dim targetDelegateType = targetType.DelegateOrExpressionDelegate(Me) If argument.Kind = BoundKind.QueryLambda AndAlso targetDelegateType IsNot Nothing Then Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso Not invoke.IsSub Then err = ERRID.ERR_NestedFunctionArgumentNarrowing3 argument = DirectCast(argument, BoundQueryLambda).Expression targetType = invoke.ReturnType End If End If If argument.Type Is Nothing Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentNarrowing2, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType) Else ReportDiagnostic(diagnostics, argument.Syntax, err, CustomSymbolDisplayFormatter.ShortErrorName(param), argument.Type, targetType) End If End If Return False End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments, which populates ''' data this function operates on. ''' </summary> Private Function PassArguments( node As SyntaxNode, ByRef candidate As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) Debug.Assert(candidate.State = OverloadResolution.CandidateAnalysisResultState.Applicable) If (arguments.IsDefault) Then arguments = ImmutableArray(Of BoundExpression).Empty End If Dim paramCount As Integer = candidate.Candidate.ParameterCount Dim parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(paramCount, -1) Dim argumentsInOrder = ArrayBuilder(Of BoundExpression).GetInstance(paramCount) Dim defaultArguments = BitVector.Null Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing If candidate.IsExpandedParamArrayForm Then paramArrayItems = ArrayBuilder(Of Integer).GetInstance() End If Dim paramIndex As Integer ' For each parameter figure out matching argument. If candidate.ArgsToParamsOpt.IsDefaultOrEmpty Then Dim regularParamCount As Integer = paramCount If candidate.IsExpandedParamArrayForm Then regularParamCount -= 1 End If For i As Integer = 0 To Math.Min(regularParamCount, arguments.Length) - 1 Step 1 If arguments(i).Kind <> BoundKind.OmittedArgument Then parameterToArgumentMap(i) = i End If Next If candidate.IsExpandedParamArrayForm Then For i As Integer = regularParamCount To arguments.Length - 1 Step 1 paramArrayItems.Add(i) Next End If Else Dim argsToParams = candidate.ArgsToParamsOpt For i As Integer = 0 To argsToParams.Length - 1 Step 1 paramIndex = argsToParams(i) If arguments(i).Kind <> BoundKind.OmittedArgument Then If (candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1) Then paramArrayItems.Add(i) Else parameterToArgumentMap(paramIndex) = i End If End If Next End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To paramCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity If candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then Dim arrayElementType = DirectCast(targetType, ArrayTypeSymbol).ElementType Dim items = ArrayBuilder(Of BoundExpression).GetInstance(paramArrayItems.Count) For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 items.Add(PassArgumentByVal(arguments(paramArrayItems(i)), If(candidate.ConversionsOpt.IsDefaultOrEmpty, Conversions.Identity, candidate.ConversionsOpt(paramArrayItems(i))), arrayElementType, diagnostics)) Next ' Create the bound array and ensure that it is marked as compiler generated. argument = New BoundArrayCreation(node, True, (New BoundExpression() {New BoundLiteral(node, ConstantValue.Create(items.Count), GetSpecialType(SpecialType.System_Int32, node, diagnostics)).MakeCompilerGenerated()}).AsImmutableOrNull(), New BoundArrayInitialization(node, items.ToImmutableAndFree(), targetType).MakeCompilerGenerated(), Nothing, Nothing, targetType).MakeCompilerGenerated() Else Dim argIndex As Integer argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument IsNot Nothing AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso param.IsParamArray Then argument = ApplyImplicitConversion(argument.Syntax, targetType, argument, diagnostics) ' Leave both conversions at identity since we already applied the conversion ElseIf argIndex > -1 Then If Not candidate.ConversionsOpt.IsDefaultOrEmpty Then conversion = candidate.ConversionsOpt(argIndex) End If If Not candidate.ConversionsBackOpt.IsDefaultOrEmpty Then conversionBack = candidate.ConversionsBackOpt(argIndex) End If End If End If Dim argumentIsDefaultValue As Boolean = False If argument Is Nothing Then Debug.Assert(Not candidate.OptionalArguments.IsEmpty, "Optional arguments expected") If defaultArguments.IsNull Then defaultArguments = BitVector.Create(paramCount) End If ' Deal with Optional arguments Dim defaultArgument As OverloadResolution.OptionalArgument = candidate.OptionalArguments(paramIndex) argument = defaultArgument.DefaultValue diagnostics.AddDependencies(defaultArgument.Dependencies) argumentIsDefaultValue = True defaultArguments(paramIndex) = True Debug.Assert(argument IsNot Nothing) conversion = defaultArgument.Conversion Dim argType = argument.Type If argType IsNot Nothing Then ' Report usesiteerror if it exists. Dim useSiteInfo = argType.GetUseSiteInfo ReportUseSite(diagnostics, argument.Syntax, useSiteInfo) End If End If ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. Debug.Assert(Not argumentIsDefaultValue OrElse argument.WasCompilerGenerated) Dim adjustedArgument As BoundExpression = PassArgument(argument, conversion, candidateIsAProperty, conversionBack, targetType, param, diagnostics) ' Keep SemanticModel happy. If argumentIsDefaultValue AndAlso adjustedArgument IsNot argument Then adjustedArgument.SetWasCompilerGenerated() End If argumentsInOrder.Add(adjustedArgument) Next If paramArrayItems IsNot Nothing Then paramArrayItems.Free() End If parameterToArgumentMap.Free() Return (argumentsInOrder.ToImmutableAndFree(), defaultArguments) End Function Private Function PassArgument( argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), forceByValueSemantics As Boolean, conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, param As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(Not param.IsByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If param.IsByRef AndAlso Not forceByValueSemantics AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then Return PassArgumentByRef(param.IsOut, argument, conversionTo, conversionFrom, targetType, param.Name, diagnostics) Else Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function Private Function PassArgumentByRef( isOutParameter As Boolean, argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, parameterName As String, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionTo.Key = checkAgainst.Key) Debug.Assert(Equals(conversionTo.Value, checkAgainst.Value)) #End If ' TODO: Fields of MarshalByRef object are passed via temp. Dim isLValue As Boolean = argument.IsLValue() If isLValue AndAlso argument.Kind = BoundKind.PropertyAccess Then argument = argument.SetAccessKind(PropertyAccessKind.Get) End If If isLValue AndAlso Conversions.IsIdentityConversion(conversionTo.Key) Then 'Nothing to do Debug.Assert(Conversions.IsIdentityConversion(conversionFrom.Key)) Return argument ElseIf isLValue OrElse argument.IsSupportingAssignment() Then ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim inPlaceholder = New BoundByRefArgumentPlaceholder(argument.Syntax, isOutParameter, argument.Type, argument.HasErrors).MakeCompilerGenerated() Dim inConversion = CreateConversionAndReportDiagnostic(argument.Syntax, inPlaceholder, conversionTo, False, targetType, diagnostics) Dim outPlaceholder = New BoundRValuePlaceholder(argument.Syntax, targetType).MakeCompilerGenerated() Dim copyBackType = argument.GetTypeOfAssignmentTarget() #If DEBUG Then checkAgainst = Conversions.ClassifyConversion(outPlaceholder, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionFrom.Key = checkAgainst.Key) Debug.Assert(Equals(conversionFrom.Value, checkAgainst.Value)) #End If Dim outConversion = CreateConversionAndReportDiagnostic(argument.Syntax, outPlaceholder, conversionFrom, False, copyBackType, diagnostics, copybackConversionParamName:=parameterName).MakeCompilerGenerated() ' since we are going to assign to a latebound invocation ' force its arguments to be rvalues. If argument.Kind = BoundKind.LateInvocation Then argument = MakeArgsRValues(DirectCast(argument, BoundLateInvocation), diagnostics) End If Dim copyBackExpression = BindAssignment(argument.Syntax, argument, outConversion, diagnostics) Debug.Assert(copyBackExpression.HasErrors OrElse (copyBackExpression.Kind = BoundKind.AssignmentOperator AndAlso DirectCast(copyBackExpression, BoundAssignmentOperator).Right Is outConversion)) If Not isLValue Then If argument.IsLateBound() Then argument = argument.SetLateBoundAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Else ' Diagnostics for PropertyAccessKind.Set case has been reported when we called BindAssignment. WarnOnRecursiveAccess(argument, PropertyAccessKind.Get, diagnostics) argument = argument.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) End If End If Return New BoundByRefArgumentWithCopyBack(argument.Syntax, argument, inConversion, inPlaceholder, outConversion, outPlaceholder, targetType, copyBackExpression.HasErrors).MakeCompilerGenerated() Else Dim propertyAccess = TryCast(argument, BoundPropertyAccess) If propertyAccess IsNot Nothing AndAlso propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.SetMethod?.IsInitOnly Then Debug.Assert(Not propertyAccess.IsWriteable) ' Used to be writable prior to VB 16.9, which caused a use-site error while binding an assignment above. InternalSyntax.Parser.CheckFeatureAvailability(diagnostics, argument.Syntax.Location, DirectCast(argument.Syntax.SyntaxTree.Options, VisualBasicParseOptions).LanguageVersion, InternalSyntax.Feature.InitOnlySettersUsage) End If ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef. Code gen will do this. Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function ' when latebound invocation acts as an LHS in an assignment ' its arguments are always passed ByVal since property parameters ' are always treated as ByVal ' This method is used to force the arguments to be RValues Private Function MakeArgsRValues(ByVal invocation As BoundLateInvocation, diagnostics As BindingDiagnosticBag) As BoundLateInvocation Dim args = invocation.ArgumentsOpt If Not args.IsEmpty Then Dim argBuilder As ArrayBuilder(Of BoundExpression) = Nothing For i As Integer = 0 To args.Length - 1 Dim arg = args(i) Dim newArg = MakeRValue(arg, diagnostics) If argBuilder Is Nothing AndAlso arg IsNot newArg Then argBuilder = ArrayBuilder(Of BoundExpression).GetInstance argBuilder.AddRange(args, i) End If If argBuilder IsNot Nothing Then argBuilder.Add(newArg) End If Next If argBuilder IsNot Nothing Then invocation = invocation.Update(invocation.Member, argBuilder.ToImmutableAndFree, invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) End If End If Return invocation End Function Friend Function PassArgumentByVal( argument As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversion.Key = checkAgainst.Key) Debug.Assert(Equals(conversion.Value, checkAgainst.Value)) #End If argument = CreateConversionAndReportDiagnostic(argument.Syntax, argument, conversion, False, targetType, diagnostics) Debug.Assert(Not argument.IsLValue) Return argument End Function ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( argumentListOpt As ArgumentListSyntax, ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) Dim args As ImmutableArray(Of ArgumentSyntax) = Nothing If argumentListOpt IsNot Nothing Then Dim arguments = argumentListOpt.Arguments Dim argsArr(arguments.Count - 1) As ArgumentSyntax For i = 0 To argsArr.Length - 1 argsArr(i) = arguments(i) Next args = argsArr.AsImmutableOrNull End If BindArgumentsAndNames( args, boundArguments, argumentNames, argumentNamesLocations, diagnostics ) End Sub ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( arguments As ImmutableArray(Of ArgumentSyntax), ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) ' With SeparatedSyntaxList, it is most efficient to iterate with foreach and not to access Count. If arguments.IsDefaultOrEmpty Then boundArguments = s_noArguments argumentNames = Nothing argumentNamesLocations = Nothing Else Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim argumentNamesBuilder As ArrayBuilder(Of String) = Nothing Dim argumentNamesLocationsBuilder As ArrayBuilder(Of Location) = Nothing Dim argCount As Integer = 0 Dim argumentSyntax As ArgumentSyntax For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) boundArgumentsBuilder.Add(BindValue(simpleArgument.Expression, diagnostics)) If simpleArgument.IsNamed Then ' The common case is no named arguments. So we defer all work until the first named argument is seen. If argumentNamesBuilder Is Nothing Then argumentNamesBuilder = ArrayBuilder(Of String).GetInstance() argumentNamesLocationsBuilder = ArrayBuilder(Of Location).GetInstance() For i = 0 To argCount - 1 argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) Next i End If Dim id = simpleArgument.NameColonEquals.Name.Identifier If id.ValueText.Length > 0 Then argumentNamesBuilder.Add(id.ValueText) Else argumentNamesBuilder.Add(Nothing) End If argumentNamesLocationsBuilder.Add(id.GetLocation()) ElseIf argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.OmittedArgument boundArgumentsBuilder.Add(New BoundOmittedArgument(argumentSyntax, Nothing)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.RangeArgument ' NOTE: Redim statement supports range argument, like: Redim x(0 To 3)(0 To 6) ' This behavior is misleading, because the 'range' (0 To 3) is actually ' being ignored and only upper bound is being used. ' TODO: revise (add warning/error?) Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax) CheckRangeArgumentLowerBound(rangeArgument, diagnostics) boundArgumentsBuilder.Add(BindValue(rangeArgument.UpperBound, diagnostics)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select argCount += 1 Next boundArguments = boundArgumentsBuilder.ToImmutableAndFree argumentNames = If(argumentNamesBuilder Is Nothing, Nothing, argumentNamesBuilder.ToImmutableAndFree) argumentNamesLocations = If(argumentNamesLocationsBuilder Is Nothing, Nothing, argumentNamesLocationsBuilder.ToImmutableAndFree) End If End Sub Friend Function GetArgumentForParameterDefaultValue(param As ParameterSymbol, syntax As SyntaxNode, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, parameterToArgumentMap As ArrayBuilder(Of Integer), arguments As ImmutableArray(Of BoundExpression), reducedExtensionReceiverOpt As BoundExpression) As BoundExpression Dim defaultArgument As BoundExpression = Nothing ' See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments. HasDefaultValue is true if the parameter is optional and has a default value. Dim defaultConstantValue As ConstantValue = If(param.IsOptional, param.ExplicitDefaultConstantValue(DefaultParametersInProgress), Nothing) If defaultConstantValue IsNot Nothing Then If callerInfoOpt IsNot Nothing AndAlso callerInfoOpt.SyntaxTree IsNot Nothing AndAlso Not callerInfoOpt.SyntaxTree.IsEmbeddedOrMyTemplateTree() AndAlso Not SuppressCallerInfo Then Dim isCallerLineNumber As Boolean = param.IsCallerLineNumber Dim isCallerMemberName As Boolean = param.IsCallerMemberName Dim isCallerFilePath As Boolean = param.IsCallerFilePath Dim callerArgumentExpressionParameterIndex As Integer = param.CallerArgumentExpressionParameterIndex Dim isCallerArgumentExpression = callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2) If isCallerArgumentExpression AndAlso Not SyntaxTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then ' Silently require feature flag for this feature until Aleksey approves. isCallerArgumentExpression = False End If If isCallerLineNumber OrElse isCallerMemberName OrElse isCallerFilePath OrElse isCallerArgumentExpression Then Dim callerInfoValue As ConstantValue = Nothing If isCallerLineNumber Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayLineNumber(GetCallerLocation(callerInfoOpt))) ElseIf isCallerMemberName Then Dim container As Symbol = ContainingMember While container IsNot Nothing Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Event Exit While Case SymbolKind.Method If container.IsLambdaMethod Then container = container.ContainingSymbol Else Dim propertyOrEvent As Symbol = DirectCast(container, MethodSymbol).AssociatedSymbol If propertyOrEvent IsNot Nothing Then container = propertyOrEvent End If Exit While End If Case Else container = container.ContainingSymbol End Select End While If container IsNot Nothing AndAlso container.Name IsNot Nothing Then callerInfoValue = ConstantValue.Create(container.Name) End If ElseIf isCallerFilePath Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayPath(callerInfoOpt.Span, Me.Compilation.Options.SourceReferenceResolver)) Else Debug.Assert(callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2)) Dim argumentSyntax As SyntaxNode = Nothing If callerArgumentExpressionParameterIndex = -1 Then argumentSyntax = reducedExtensionReceiverOpt.Syntax Else Dim argumentIndex = parameterToArgumentMap(callerArgumentExpressionParameterIndex) Debug.Assert(argumentIndex < arguments.Length) If argumentIndex > -1 Then argumentSyntax = arguments(argumentIndex).Syntax End If End If If argumentSyntax IsNot Nothing Then callerInfoValue = ConstantValue.Create(argumentSyntax.ToString()) End If End If If callerInfoValue IsNot Nothing Then ' Use the value only if it will not cause errors. Dim ignoreDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) Dim literal As BoundLiteral If callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.Int32 Then literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_Int32, syntax, ignoreDiagnostics)) Else Debug.Assert(callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.String) literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_String, syntax, ignoreDiagnostics)) End If Dim convertedValue As BoundExpression = ApplyImplicitConversion(syntax, param.Type, literal, ignoreDiagnostics) If Not convertedValue.HasErrors AndAlso Not ignoreDiagnostics.HasAnyErrors Then ' Dev11 #248795: Caller info should be omitted if user defined conversion is involved. If Not (convertedValue.Kind = BoundKind.Conversion AndAlso (DirectCast(convertedValue, BoundConversion).ConversionKind And ConversionKind.UserDefined) <> 0) Then defaultConstantValue = callerInfoValue End If End If ignoreDiagnostics.Free() End If End If End If ' For compatibility with the native compiler bad metadata constants should be treated as default(T). This ' is a possible outcome of running an obfuscator over a valid DLL If defaultConstantValue.IsBad Then defaultConstantValue = ConstantValue.Null End If Dim defaultSpecialType = defaultConstantValue.SpecialType Dim defaultArgumentType As TypeSymbol = Nothing ' Constant has a type. Dim paramNullableUnderlyingTypeOrSelf As TypeSymbol = param.Type.GetNullableUnderlyingTypeOrSelf() If param.HasOptionCompare Then ' If the argument has the OptionCompareAttribute ' then use the setting for Option Compare [Binary|Text] ' Other languages will use the default value specified. If Me.OptionCompareText Then defaultConstantValue = ConstantValue.Create(1) Else defaultConstantValue = ConstantValue.Default(SpecialType.System_Int32) End If If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32 Then defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else defaultArgumentType = GetSpecialType(SpecialType.System_Int32, syntax, diagnostics) End If ElseIf defaultSpecialType <> SpecialType.None Then If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = defaultSpecialType Then ' Enum default values are encoded as the underlying primitive type. If the underlying types match then ' use the parameter's enum type. defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else 'Use the primitive type. defaultArgumentType = GetSpecialType(defaultSpecialType, syntax, diagnostics) End If Else ' No type in constant. Constant should be nothing Debug.Assert(defaultConstantValue.IsNothing) End If defaultArgument = New BoundLiteral(syntax, defaultConstantValue, defaultArgumentType) ElseIf param.IsOptional Then ' Handle optional object type argument when no default value is specified. ' Section 3 of §11.8.2 Applicable Methods If param.Type.SpecialType = SpecialType.System_Object Then Dim methodSymbol As MethodSymbol = Nothing If param.IsMarshalAsObject Then ' Nothing defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) ElseIf param.IsIDispatchConstant Then ' new DispatchWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, syntax, diagnostics), MethodSymbol) ElseIf param.IsIUnknownConstant Then ' new UnknownWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, syntax, diagnostics), MethodSymbol) Else defaultArgument = New BoundOmittedArgument(syntax, param.Type) End If If methodSymbol IsNot Nothing Then Dim argument = New BoundLiteral(syntax, ConstantValue.Null, param.Type).MakeCompilerGenerated() defaultArgument = New BoundObjectCreationExpression(syntax, methodSymbol, ImmutableArray.Create(Of BoundExpression)(argument), Nothing, methodSymbol.ContainingType) End If Else defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) End If End If Return defaultArgument?.MakeCompilerGenerated() End Function Private Shared Function GetCallerLocation(syntax As SyntaxNode) As TextSpan Select Case syntax.Kind Case SyntaxKind.SimpleMemberAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).Name.Span Case SyntaxKind.DictionaryAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).OperatorToken.Span Case Else Return syntax.Span End Select End Function ''' <summary> ''' Return true if the node is an immediate child of a call statement. ''' </summary> Private Shared Function IsCallStatementContext(node As InvocationExpressionSyntax) As Boolean Dim parent As VisualBasicSyntaxNode = node.Parent ' Dig through conditional access If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ConditionalAccessExpression Then Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax) If conditional.WhenNotNull Is node Then parent = conditional.Parent End If End If Return parent IsNot Nothing AndAlso (parent.Kind = SyntaxKind.CallStatement OrElse parent.Kind = SyntaxKind.ExpressionStatement) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of method/property invocation is implemented in this part. Partial Friend Class Binder Private Function CreateBoundMethodGroup( node As SyntaxNode, lookupResult As LookupResult, lookupOptionsUsed As LookupOptions, withDependencies As Boolean, receiver As BoundExpression, typeArgumentsOpt As BoundTypeArguments, qualKind As QualificationKind, Optional hasError As Boolean = False ) As BoundMethodGroup Dim pendingExtensionMethods As ExtensionMethodGroup = Nothing Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) ' Name lookup does not look for extension methods if it found a suitable ' instance method. So, if the first symbol we have is not a reduced extension ' method, we might need to look for extension methods later, on demand. Debug.Assert((lookupOptionsUsed And LookupOptions.EagerlyLookupExtensionMethods) = 0) If lookupResult.IsGood AndAlso Not lookupResult.Symbols(0).IsReducedExtensionMethod() Then pendingExtensionMethods = New ExtensionMethodGroup(Me, lookupOptionsUsed, withDependencies) End If Return New BoundMethodGroup( node, typeArgumentsOpt, lookupResult.Symbols.ToDowncastedImmutable(Of MethodSymbol), pendingExtensionMethods, lookupResult.Kind, receiver, qualKind, hasErrors:=hasError) End Function ''' <summary> ''' Returns if all the rules for a "Me.New" or "MyBase.New" constructor call are satisfied: ''' a) In instance constructor body ''' b) First statement of that constructor ''' c) "Me", "MyClass", or "MyBase" is the receiver. ''' </summary> Private Function IsConstructorCallAllowed(invocationExpression As InvocationExpressionSyntax, boundMemberGroup As BoundMethodOrPropertyGroup) As Boolean If Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.Constructor Then ' (a) we are in an instance constructor body Dim node As VisualBasicSyntaxNode = invocationExpression.Parent If node Is Nothing OrElse (node.Kind <> SyntaxKind.CallStatement AndAlso node.Kind <> SyntaxKind.ExpressionStatement) Then Return False End If Dim nodeParent As VisualBasicSyntaxNode = node.Parent If nodeParent Is Nothing OrElse nodeParent.Kind <> SyntaxKind.ConstructorBlock Then Return False End If If DirectCast(nodeParent, ConstructorBlockSyntax).Statements(0) Is node Then ' (b) call statement we are binding is 'the first' statement of the constructor Dim receiver As BoundExpression = boundMemberGroup.ReceiverOpt If receiver IsNot Nothing AndAlso (receiver.Kind = BoundKind.MeReference OrElse receiver.Kind = BoundKind.MyBaseReference OrElse receiver.Kind = BoundKind.MyClassReference) Then ' (c) receiver is 'Me'/'MyClass'/'MyBase' Return True End If End If End If Return False End Function Friend Class ConstructorCallArgumentsBinder Inherits Binder Public Sub New(containingBinder As Binder) MyBase.New(containingBinder) End Sub Protected Overrides ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return True End Get End Property End Class ''' <summary> ''' Bind a Me.New(...), MyBase.New (...), MyClass.New(...) constructor call. ''' (NOT a normal constructor call like New Type(...)). ''' </summary> Private Function BindDirectConstructorCall(node As InvocationExpressionSyntax, group As BoundMethodGroup, diagnostics As BindingDiagnosticBag) As BoundExpression Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Dim argumentList As ArgumentListSyntax = node.ArgumentList Debug.Assert(IsGroupOfConstructors(group)) ' Direct constructor call is only allowed if: (a) we are in an instance constructor body, ' and (b) call statement we are binding is 'the first' statement of the constructor, ' and (c) receiver is 'Me'/'MyClass'/'MyBase' If IsConstructorCallAllowed(node, group) Then ' Bind arguments with special binder that prevents use of Me. Dim argumentsBinder As Binder = New ConstructorCallArgumentsBinder(Me) argumentsBinder.BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, errors will be generated if needed Return BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, diagnostics, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) Else ' Error case -- constructor call in wrong location. ' Report error BC30282 about invalid constructor call ' For semantic model / IDE purposes, we still bind it even if in a location that wasn't allowed. If Not group.HasErrors Then ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall) End If BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, ignore errors by putting into discarded bag. Dim expr = BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) If expr.Kind = BoundKind.Call Then ' Set HasErrors to prevent cascading errors. Dim callExpr = DirectCast(expr, BoundCall) expr = New BoundCall( callExpr.Syntax, callExpr.Method, callExpr.MethodGroupOpt, callExpr.ReceiverOpt, callExpr.Arguments, callExpr.DefaultArguments, callExpr.ConstantValueOpt, isLValue:=False, suppressObjectClone:=False, type:=callExpr.Type, hasErrors:=True) End If Return expr End If End Function Private Function BindInvocationExpression(node As InvocationExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression ' Set "IsInvocationsOrAddressOf" to prevent binding to return value variable. Dim target As BoundExpression If node.Expression Is Nothing Then ' Must be conditional case Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then target = GetConditionalAccessReceiver(conditionalAccess) Else target = ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_Syntax).MakeCompilerGenerated() End If Else target = BindExpression(node.Expression, diagnostics:=diagnostics, isInvocationOrAddressOf:=True, isOperandOfConditionalBranch:=False, eventContext:=False) End If ' If 'target' is a bound constructor group, we need to do special checks and special processing of arguments. If target.Kind = BoundKind.MethodGroup Then Dim group = DirectCast(target, BoundMethodGroup) If IsGroupOfConstructors(group) Then Return BindDirectConstructorCall(node, group, diagnostics) End If End If Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Me.BindArgumentsAndNames(node.ArgumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) If target.Kind = BoundKind.MethodGroup OrElse target.Kind = BoundKind.PropertyGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, ExtractTypeCharacter(node.Expression), DirectCast(target, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, diagnostics:=diagnostics) End If If target.Kind = BoundKind.NamespaceExpression Then Dim namespaceExp As BoundNamespaceExpression = DirectCast(target, BoundNamespaceExpression) Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_NamespaceNotExpression1, namespaceExp.NamespaceSymbol) ReportDiagnostic(diagnostics, node.Expression, diagInfo) ElseIf target.Kind = BoundKind.TypeExpression Then Dim typeExp As BoundTypeExpression = DirectCast(target, BoundTypeExpression) If Not IsCallStatementContext(node) Then ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(typeExp, diagnostics) If instance IsNot Nothing Then Return BindIndexedInvocationExpression( node, instance, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=False, diagnostics:=diagnostics) End If End If Dim diagInfo = ErrorFactory.ErrorInfo(GetTypeNotExpressionErrorId(typeExp.Type), typeExp.Type) ReportDiagnostic(diagnostics, node.Expression, diagInfo) Else Return BindIndexedInvocationExpression( node, target, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, hasIndexableTarget:=False, diagnostics:=diagnostics) End If Return GenerateBadExpression(node, target, boundArguments) End Function ''' <summary> ''' Bind an invocation expression representing an array access, ''' delegate invocation, or default member. ''' </summary> Private Function BindIndexedInvocationExpression( node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, <Out()> ByRef hasIndexableTarget As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(target.Kind <> BoundKind.NamespaceExpression) Debug.Assert(target.Kind <> BoundKind.TypeExpression) Debug.Assert(target.Kind <> BoundKind.MethodGroup) Debug.Assert(target.Kind <> BoundKind.PropertyGroup) hasIndexableTarget = False If Not target.IsLValue AndAlso target.Kind <> BoundKind.LateMemberAccess Then target = MakeRValue(target, diagnostics) End If Dim targetType As TypeSymbol = target.Type ' there are values or variables like "Nothing" which have no type If targetType IsNot Nothing Then ' this method is also called for e.g. Arrays because they are also InvocationExpressions ' if target is an array, then call BindArrayAccess only if target is not a direct successor ' of a call statement If targetType.IsArrayType Then hasIndexableTarget = True ' only bind to an array if this method was called outside of a call statement context If Not IsCallStatementContext(node) Then Return BindArrayAccess(node, target, boundArguments, argumentNames, diagnostics) End If ElseIf targetType.Kind = SymbolKind.NamedType AndAlso targetType.TypeKind = TypeKind.Delegate Then hasIndexableTarget = True ' an invocation of a delegate actually calls the delegate's Invoke method. Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod If delegateInvoke Is Nothing Then If Not target.HasErrors Then ReportDiagnostic(diagnostics, target.Syntax, ERRID.ERR_DelegateNoInvoke1, target.Type) End If ElseIf ReportDelegateInvokeUseSite(diagnostics, target.Syntax, targetType, delegateInvoke) Then delegateInvoke = Nothing End If If delegateInvoke IsNot Nothing Then Dim methodGroup = New BoundMethodGroup( If(node.Expression, node), Nothing, ImmutableArray.Create(Of MethodSymbol)(delegateInvoke), LookupResultKind.Good, target, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() Return BindInvocationExpression( node, If(node.Expression, node), ExtractTypeCharacter(node.Expression), methodGroup, boundArguments, argumentNames, diagnostics, callerInfoOpt:=node, representCandidateInDiagnosticsOpt:=targetType) Else Dim badExpressionChildren = ArrayBuilder(Of BoundExpression).GetInstance() badExpressionChildren.Add(target) badExpressionChildren.AddRange(boundArguments) Return BadExpression(node, badExpressionChildren.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType) End If End If End If If target.Kind = BoundKind.BadExpression Then ' Error already reported for a bad expression, so don't report another error ElseIf Not IsCallStatementContext(node) Then ' If the invocation is outside of a call statement ' context, bind to the default property group if any. If target.Type.SpecialType = SpecialType.System_Object OrElse target.Type.SpecialType = SpecialType.System_Array Then hasIndexableTarget = True Return BindLateBoundInvocation(node, Nothing, target, boundArguments, argumentNames, diagnostics, suppressLateBindingResolutionDiagnostics:=(target.Kind = BoundKind.LateMemberAccess)) End If If Not target.HasErrors Then ' Bind to the default property group. Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(If(node.Expression, node), target, diagnostics) If defaultPropertyGroup IsNot Nothing Then Debug.Assert(defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors) hasIndexableTarget = True If defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, TypeCharacter.None, DirectCast(defaultPropertyGroup, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments, diagnostics) End If Else ReportNoDefaultProperty(target, diagnostics) End If End If ElseIf target.Kind = BoundKind.LateMemberAccess Then hasIndexableTarget = True Dim lateMember = DirectCast(target, BoundLateMemberAccess) Return BindLateBoundInvocation(node, Nothing, lateMember, boundArguments, argumentNames, diagnostics) ElseIf Not target.HasErrors Then ' "Expression is not a method." Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedProcedure) ReportDiagnostic(diagnostics, If(node.Expression, node), diagInfo) End If Return GenerateBadExpression(node, target, boundArguments) End Function Private Function BindInvocationExpressionPossiblyWithoutArguments( node As InvocationExpressionSyntax, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression ' Spec §11.8 Invocation Expressions ' ... ' If the method group only contains one accessible method, including both instance and ' extension methods, and that method takes no arguments and is a function, then the method ' group is interpreted as an invocation expression with an empty argument list and the result ' is used as the target of an invocation expression with the provided argument list(s). If allowBindingWithoutArguments AndAlso boundArguments.Length > 0 AndAlso Not IsCallStatementContext(node) AndAlso ShouldBindWithoutArguments(node, group, diagnostics) Then Dim tmpDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) Dim result As BoundExpression = Nothing Debug.Assert(node.Expression IsNot Nothing) ' NOTE: when binding without arguments, we pass node.Expression as the first parameter ' so that the new bound node references it instead of invocation expression Dim withoutArgs = BindInvocationExpression( node.Expression, node.Expression, typeChar, group, ImmutableArray(Of BoundExpression).Empty, Nothing, tmpDiagnostics, callerInfoOpt:=group.Syntax) If withoutArgs.Kind = BoundKind.Call OrElse withoutArgs.Kind = BoundKind.PropertyAccess Then ' We were able to bind the method group or property access without arguments, ' possibly with some diagnostic. diagnostics.AddRange(tmpDiagnostics) tmpDiagnostics.Clear() If withoutArgs.Kind = BoundKind.PropertyAccess Then Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundPropertyAccess).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If withoutArgs = MakeRValue(withoutArgs, diagnostics) Else Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundCall).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If End If If withoutArgs.Kind = BoundKind.BadExpression Then result = GenerateBadExpression(node, withoutArgs, boundArguments) Else Dim hasIndexableTarget = False ' Bind the invocation with arguments as an indexed invocation. Dim withArgs = BindIndexedInvocationExpression( node, withoutArgs, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=hasIndexableTarget, diagnostics:=tmpDiagnostics) If hasIndexableTarget Then diagnostics.AddRange(tmpDiagnostics) result = withArgs Else ' Report BC32016 if something wrong. ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_FunctionResultCannotBeIndexed1, withoutArgs.ExpressionSymbol) ' If result of binding with no args was not indexable after all, then instead ' of just producing a bad expression, bind the invocation expression normally, ' but without reporting any more diagnostics. This produces more accurate ' bound nodes for semantic model questions and may allow the type of the ' expression to be computed, thus leading to fewer errors later. result = BindInvocationExpression( node, node.Expression, typeChar, group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, callerInfoOpt:=group.Syntax) End If End If End If tmpDiagnostics.Free() If result IsNot Nothing Then Return result End If End If Return BindInvocationExpression( node, If(node.Expression, group.Syntax), typeChar, group, boundArguments, argumentNames, diagnostics, callerInfoOpt:=group.Syntax) End Function ''' <summary> ''' Returns a BoundPropertyGroup if the expression represents a valid ''' default property access. If there is a default property but the property ''' access is invalid, a BoundBadExpression is returned. If there is no ''' default property for the expression type, Nothing is returned. ''' ''' Note, that default Query Indexer may be a method, not a property. ''' </summary> Private Function BindDefaultPropertyGroup(node As VisualBasicSyntaxNode, target As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression Dim result = LookupResult.GetInstance() Dim defaultMemberGroup As BoundExpression = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) MemberLookup.LookupDefaultProperty(result, target.Type, Me, useSiteInfo) ' We're not reporting any diagnostic if there are no symbols. Debug.Assert(result.HasSymbol OrElse Not result.HasDiagnostic) If result.HasSymbol Then defaultMemberGroup = BindSymbolAccess(node, result, LookupOptions.Default, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) Debug.Assert(defaultMemberGroup IsNot Nothing) Debug.Assert((defaultMemberGroup.Kind = BoundKind.BadExpression) OrElse (defaultMemberGroup.Kind = BoundKind.PropertyGroup)) Else ' All queryable sources have default indexer, which maps to an ElementAtOrDefault method or property on the source. Dim tempDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) target = MakeRValue(target, tempDiagnostics) Dim controlVariableType As TypeSymbol = Nothing target = ConvertToQueryableType(target, tempDiagnostics, controlVariableType) If controlVariableType IsNot Nothing Then result.Clear() Const options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity. LookupMember(result, target.Type, StringConstants.ElementAtMethod, 0, options, useSiteInfo) If result.IsGood Then Dim kind As SymbolKind = result.Symbols(0).Kind If kind = SymbolKind.Method OrElse kind = SymbolKind.Property Then diagnostics.AddRange(tempDiagnostics) defaultMemberGroup = BindSymbolAccess(node, result, options, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) End If End If End If tempDiagnostics.Free() End If diagnostics.Add(node, useSiteInfo) result.Free() ' We don't want the default property GROUP to override the meaning of the item it's being ' accessed off of, so mark it as compiler generated. If defaultMemberGroup IsNot Nothing Then defaultMemberGroup.SetWasCompilerGenerated() End If Return defaultMemberGroup End Function ''' <summary> ''' Tests whether or not the method or property group should be bound without arguments. ''' In case of method group it may also update the group by filtering out all subs ''' </summary> Private Function ShouldBindWithoutArguments(node As VisualBasicSyntaxNode, ByRef group As BoundMethodOrPropertyGroup, diagnostics As BindingDiagnosticBag) As Boolean Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim result = ShouldBindWithoutArguments(group, useSiteInfo) diagnostics.Add(node, useSiteInfo) Return result End Function Private Function ShouldBindWithoutArguments(ByRef group As BoundMethodOrPropertyGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim newMethods As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() ' check method group members Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) ' any sub should be removed from a group in case we try binding without arguments Dim shouldUpdateGroup As Boolean = False Dim atLeastOneFunction As Boolean = False ' Dev10 behavior: ' For instance methods - ' Check if all functions from the group (ignoring subs) ' have the same arity as specified in the call and 0 parameters. ' However, the part that handles arity check is rather inconsistent between methods ' overloaded within the same type and in derived type. Also, language spec doesn't mention ' any restrictions for arity. So, we will not try to duplicate Dev10 logic around arity ' because the logic is close to impossible to match and behavior change will not be a breaking ' change. ' In presence of extension methods the rules are more constrained- ' If group contains an extension method, it must be the only method in the group, ' it must have no parameters, must have no type parameters and must be a Function. ' Note, we should avoid requesting AdditionalExtensionMethods whenever possible because ' lookup of extension methods might be very expensive. Dim extensionMethod As MethodSymbol = Nothing For Each method In methodGroup.Methods If method.IsReducedExtensionMethod Then extensionMethod = method Exit For End If If (method.IsSub) Then If method.CanBeCalledWithNoParameters() Then ' If its a sub that could be called parameterlessly, it might hide the function. So it is included ' in the group for further processing in overload resolution (which will process possible hiding). ' If overload resolution does select the Sub, we'll get an error about return type not indexable. ' See Roslyn bug 14019 for example. newMethods.Add(method) Else ' ignore other subs entirely shouldUpdateGroup = True End If ElseIf method.ParameterCount > 0 Then ' any function with more than 0 parameters newMethods.Free() Return False Else newMethods.Add(method) atLeastOneFunction = True End If Next If extensionMethod Is Nothing Then Dim additionalExtensionMethods As ImmutableArray(Of MethodSymbol) = methodGroup.AdditionalExtensionMethods(useSiteInfo) If additionalExtensionMethods.Length > 0 Then Debug.Assert(methodGroup.Methods.Length > 0) ' We have at least one extension method in the group and it is not the only one method in the ' group. Cannot apply default property transformation. newMethods.Free() Return False End If Else newMethods.Free() Debug.Assert(extensionMethod IsNot Nothing) ' This method must have no parameters, must have no type parameters and must not be a Sub. Return methodGroup.Methods.Length = 1 AndAlso methodGroup.TypeArgumentsOpt Is Nothing AndAlso extensionMethod.ParameterCount = 0 AndAlso extensionMethod.Arity = 0 AndAlso Not extensionMethod.IsSub AndAlso methodGroup.AdditionalExtensionMethods(useSiteInfo).Length = 0 End If If Not atLeastOneFunction Then newMethods.Free() Return False End If If shouldUpdateGroup Then ' at least one sub was removed If newMethods.IsEmpty Then ' no functions left newMethods.Free() Return False End If ' there are some functions, update the group group = methodGroup.Update(methodGroup.TypeArgumentsOpt, newMethods.ToImmutable(), Nothing, methodGroup.ResultKind, methodGroup.ReceiverOpt, methodGroup.QualificationKind) End If newMethods.Free() Return True Else ' check property group members Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Debug.Assert(propertyGroup.Properties.Length > 0) For Each prop In propertyGroup.Properties If (prop.ParameterCount > 0) Then Return False End If Next ' assuming property group was not empty Return True End If End Function Private Shared Function IsGroupOfConstructors(group As BoundMethodOrPropertyGroup) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) Return methodGroup.Methods(0).MethodKind = MethodKind.Constructor End If Return False End Function Friend Function BindInvocationExpression( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional allowConstructorCall As Boolean = False, Optional suppressAbstractCallDiagnostics As Boolean = False, Optional isDefaultMemberAccess As Boolean = False, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional forceExpandedForm As Boolean = False ) As BoundExpression Debug.Assert(group IsNot Nothing) Debug.Assert(allowConstructorCall OrElse Not IsGroupOfConstructors(group)) Debug.Assert(group.ResultKind = LookupResultKind.Good OrElse group.ResultKind = LookupResultKind.Inaccessible) ' It is possible to get here with method group with ResultKind = LookupResultKind.Inaccessible. ' When this happens, it is worth trying to do overload resolution on the "bad" set ' to report better errors. Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, callerInfoOpt, useSiteInfo, forceExpandedForm:=forceExpandedForm) If diagnostics.Add(node, useSiteInfo) Then If group.ResultKind <> LookupResultKind.Inaccessible Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If End If If Not results.BestResult.HasValue Then If results.ResolutionIsLateBound Then Debug.Assert(OptionStrict <> VisualBasic.OptionStrict.On) ' Did we have extension methods among candidates? If group.Kind = BoundKind.MethodGroup Then Dim haveAnExtensionMethod As Boolean = False Dim methodGroup = DirectCast(group, BoundMethodGroup) For Each method As MethodSymbol In methodGroup.Methods If method.ReducedFrom IsNot Nothing Then haveAnExtensionMethod = True Exit For End If Next If Not haveAnExtensionMethod Then useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) haveAnExtensionMethod = Not methodGroup.AdditionalExtensionMethods(useSiteInfo).IsEmpty diagnostics.Add(node, useSiteInfo) End If If haveAnExtensionMethod Then ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, group), ERRID.ERR_ExtensionMethodCannotBeLateBound) Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() builder.Add(group) If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If Return New BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, builder.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If End If Return BindLateBoundInvocation(node, group, isDefaultMemberAccess, boundArguments, argumentNames, diagnostics) End If ' Create and report the diagnostic. If results.Candidates.Length = 0 Then results = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, includeEliminatedCandidates:=True, callerInfoOpt:=callerInfoOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded, forceExpandedForm:=forceExpandedForm) End If Return ReportOverloadResolutionFailureAndProduceBoundNode(node, group, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else Return CreateBoundCallOrPropertyAccess( node, target, typeChar, group, boundArguments, results.BestResult.Value, results.AsyncLambdaSubToFunctionMismatch, diagnostics, suppressAbstractCallDiagnostics) End If End Function Private Function CreateBoundCallOrPropertyAccess( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), bestResult As OverloadResolution.CandidateAnalysisResult, asyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag, Optional suppressAbstractCallDiagnostics As Boolean = False ) As BoundExpression Dim candidate = bestResult.Candidate Dim methodOrProperty = candidate.UnderlyingSymbol Dim returnType = candidate.ReturnType If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, target, GetInaccessibleErrorInfo(bestResult.Candidate.UnderlyingSymbol)) Else Debug.Assert(group.ResultKind = LookupResultKind.Good) CheckMemberTypeAccessibility(diagnostics, node, methodOrProperty) End If If bestResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(bestResult.TypeArgumentInferenceDiagnosticsOpt) End If Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bestResult, boundArguments, diagnostics) boundArguments = argumentInfo.Arguments Debug.Assert(Not boundArguments.IsDefault) Dim hasErrors As Boolean = False Dim receiver As BoundExpression = group.ReceiverOpt If group.ResultKind = LookupResultKind.Good Then hasErrors = CheckSharedSymbolAccess(target, methodOrProperty.IsShared, receiver, group.QualificationKind, diagnostics) ' give diagnostics if sharedness is wrong. End If ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, methodOrProperty, node) hasErrors = hasErrors Or group.HasErrors If Not returnType.IsErrorType() Then VerifyTypeCharacterConsistency(node, returnType, typeChar, diagnostics) End If Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing If receiver IsNot Nothing AndAlso Not hasErrors Then receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, methodOrProperty.IsShared, diagnostics, resolvedTypeOrValueReceiver) End If If Not suppressAbstractCallDiagnostics AndAlso receiver IsNot Nothing AndAlso (receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then If methodOrProperty.IsMustOverride Then ' Generate an error, but continue processing ReportDiagnostic(diagnostics, group.Syntax, If(receiver.IsMyBaseReference, ERRID.ERR_MyBaseAbstractCall1, ERRID.ERR_MyClassAbstractCall1), methodOrProperty) End If End If If Not asyncLambdaSubToFunctionMismatch.IsEmpty Then For Each lambda In asyncLambdaSubToFunctionMismatch Dim errorLocation As SyntaxNode = lambda.Syntax Dim lambdaNode = TryCast(errorLocation, LambdaExpressionSyntax) If lambdaNode IsNot Nothing Then errorLocation = lambdaNode.SubOrFunctionHeader End If ReportDiagnostic(diagnostics, errorLocation, ERRID.WRN_AsyncSubCouldBeFunction) Next End If If methodOrProperty.Kind = SymbolKind.Method Then Dim method = DirectCast(methodOrProperty, MethodSymbol) Dim reducedFrom = method.ReducedFrom Dim constantValue As ConstantValue = Nothing If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If If method.IsUserDefinedOperator() AndAlso Me.ContainingMember Is method Then ReportDiagnostic(diagnostics, target, ERRID.WRN_RecursiveOperatorCall, method) End If ' replace call with literal if possible (Chr, ChrW, Asc, AscW) constantValue = OptimizeLibraryCall(method, boundArguments, node, hasErrors, diagnostics) Else ' We are calling an extension method, prepare the receiver to be ' passed as the first parameter. receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, method.ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the method group ' NOTE: we only remove it if we pass it to a new BoundCall node, ' otherwise we keep it in the group to support semantic queries Dim methodGroup = DirectCast(group, BoundMethodGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, methodGroup.ReceiverOpt)) methodGroup = methodGroup.Update(methodGroup.TypeArgumentsOpt, methodGroup.Methods, methodGroup.PendingExtensionMethodsOpt, methodGroup.ResultKind, newReceiver, methodGroup.QualificationKind) Return New BoundCall( node, method, methodGroup, receiver, boundArguments, constantValue, returnType, suppressObjectClone:=False, hasErrors:=hasErrors, defaultArguments:=argumentInfo.DefaultArguments) Else Dim [property] = DirectCast(methodOrProperty, PropertySymbol) Dim reducedFrom = [property].ReducedFromDefinition Debug.Assert(Not boundArguments.Any(Function(a) a.Kind = BoundKind.ByRefArgumentWithCopyBack)) If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Else receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, [property].ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the property group ' NOTE: we only remove it if we pass it to a new BoundPropertyAccess node, ' otherwise we keep it in the group to support semantic queries Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, propertyGroup.ReceiverOpt)) propertyGroup = propertyGroup.Update(propertyGroup.Properties, propertyGroup.ResultKind, newReceiver, propertyGroup.QualificationKind) Return New BoundPropertyAccess( node, [property], propertyGroup, PropertyAccessKind.Unknown, [property].IsWritable(receiver, Me, isKnownTargetOfObjectMemberInitializer:=False), receiver, boundArguments, argumentInfo.DefaultArguments, hasErrors:=hasErrors) End If End Function Friend Sub WarnOnRecursiveAccess(propertyAccess As BoundPropertyAccess, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Dim [property] As PropertySymbol = propertyAccess.PropertySymbol If [property].ReducedFromDefinition Is Nothing AndAlso [property].ParameterCount = 0 AndAlso ([property].IsShared OrElse (propertyAccess.ReceiverOpt IsNot Nothing AndAlso propertyAccess.ReceiverOpt.Kind = BoundKind.MeReference)) Then Dim reportRecursiveCall As Boolean = False If [property].GetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Get) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Get) = 0 Then reportRecursiveCall = True End If ElseIf [property].SetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Set) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Set) = 0 Then reportRecursiveCall = True End If End If If reportRecursiveCall Then ReportDiagnostic(diagnostics, propertyAccess.Syntax, ERRID.WRN_RecursivePropertyCall, [property]) End If End If End Sub Friend Sub WarnOnRecursiveAccess(node As BoundExpression, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Select Case node.Kind Case BoundKind.XmlMemberAccess ' Nothing to do Case BoundKind.PropertyAccess WarnOnRecursiveAccess(DirectCast(node, BoundPropertyAccess), accessKind, diagnostics) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Sub Private Function UpdateReceiverForExtensionMethodOrPropertyGroup( receiver As BoundExpression, targetType As TypeSymbol, thisParameterDefinition As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression If receiver IsNot Nothing AndAlso receiver.IsValue AndAlso Not targetType.IsErrorType() AndAlso Not receiver.Type.IsErrorType() Then Dim oldReceiver As BoundExpression = receiver Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) receiver = PassArgument(receiver, Conversions.ClassifyConversion(receiver, targetType, Me, useSiteInfo), False, Conversions.ClassifyConversion(targetType, receiver.Type, useSiteInfo), targetType, thisParameterDefinition, diagnostics) diagnostics.Add(receiver, useSiteInfo) If oldReceiver.WasCompilerGenerated AndAlso receiver IsNot oldReceiver Then Select Case oldReceiver.Kind Case BoundKind.MeReference, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder receiver.SetWasCompilerGenerated() End Select End If End If Return receiver End Function Private Function IsWellKnownTypeMember(memberId As WellKnownMember, method As MethodSymbol) As Boolean Return Compilation.GetWellKnownTypeMember(memberId) Is method End Function ''' <summary> ''' Optimizes some runtime library calls through replacing them with a literal if possible. ''' VB Spec 11.2 defines the following runtime functions as being constant: ''' - Microsoft.VisualBasic.Strings.ChrW ''' - Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ''' - Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ''' - Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ''' </summary> ''' <param name="method">The method.</param> ''' <param name="arguments">The arguments of the method call.</param> ''' <param name="syntax">The syntax node for report errors.</param> ''' <param name="diagnostics">The diagnostics.</param> ''' <param name="hasErrors">Set to true if there are conversion errors (e.g. Asc("")). Otherwise it's not written to.</param> ''' <returns>The constant value that replaces this node, or nothing.</returns> Private Function OptimizeLibraryCall( method As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), syntax As SyntaxNode, ByRef hasErrors As Boolean, diagnostics As BindingDiagnosticBag ) As ConstantValue ' cheapest way to filter out methods that do not match If arguments.Length = 1 AndAlso arguments(0).IsConstant AndAlso Not arguments(0).ConstantValueOpt.IsBad Then ' only continue checking if containing type is Microsoft.VisualBasic.Strings If Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Strings) IsNot method.ContainingType Then Return Nothing End If ' AscW(char) / AscW(String) ' all values can be optimized as a literal, except an empty string that produces a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWStringInt32, method) Then Dim argumentConstantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If argumentConstantValue.IsNull Then argumentValue = String.Empty ElseIf argumentConstantValue.IsChar Then argumentValue = argumentConstantValue.CharValue Else Debug.Assert(argumentConstantValue.IsString()) argumentValue = argumentConstantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(AscW(argumentValue)) End If ' ChrW ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(ChrW(argumentValue)) End If ' Asc(Char) / Asc(String) ' all values from 0 to 127 can be optimized to a literal. If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, method) Then Dim constantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If constantValue.IsNull Then argumentValue = String.Empty ElseIf constantValue.IsChar Then argumentValue = constantValue.CharValue Else Debug.Assert(constantValue.IsString()) argumentValue = constantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If ' we are only folding 7bit ASCII chars, so it's ok to use AscW here, although this is the Asc folding. Dim charValue = AscW(argumentValue) If charValue < 128 Then Return ConstantValue.Create(charValue) End If Return Nothing End If ' Chr ' values from 0 to 127 can be optimized as a literal ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue >= 0 AndAlso argumentValue < 128 Then Return ConstantValue.Create(ChrW(argumentValue)) ElseIf argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If End If End If Return Nothing End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, group, overrideCommonReturnType, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance() Dim bestSymbols = ImmutableArray(Of Symbol).Empty Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(results, bestCandidates, bestSymbols) If overrideCommonReturnType IsNot Nothing Then commonReturnType = overrideCommonReturnType End If Dim result As BoundExpression = ReportOverloadResolutionFailureAndProduceBoundNode( node, lookupResult, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, groupOpt, Nothing, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) bestCandidates.Free() Return result End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, group, delegateSymbol, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt) End Function Public Shared Function GetLocationForOverloadResolutionDiagnostic(node As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing) As Location Dim result As SyntaxNode If groupOpt IsNot Nothing Then If node.SyntaxTree Is groupOpt.Syntax.SyntaxTree AndAlso node.Span.Contains(groupOpt.Syntax.Span) Then result = groupOpt.Syntax If result Is node AndAlso (groupOpt.ReceiverOpt Is Nothing OrElse groupOpt.ReceiverOpt.Syntax Is result) Then Return result.GetLocation() End If Else Return node.GetLocation() End If ElseIf node.IsKind(SyntaxKind.InvocationExpression) Then result = If(DirectCast(node, InvocationExpressionSyntax).Expression, node) Else Return node.GetLocation() End If Select Case result.Kind Case SyntaxKind.QualifiedName Return DirectCast(result, QualifiedNameSyntax).Right.GetLocation() Case SyntaxKind.SimpleMemberAccessExpression If result.Parent IsNot Nothing AndAlso result.Parent.IsKind(SyntaxKind.AddressOfExpression) Then Return result.GetLocation() End If Return DirectCast(result, MemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression Return DirectCast(result, XmlMemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.HandlesClauseItem Return DirectCast(result, HandlesClauseItemSyntax).EventMember.GetLocation() End Select Return result.GetLocation() End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Debug.Assert(commonReturnType IsNot Nothing AndAlso bestSymbols.Length > 0 AndAlso bestCandidates.Count >= bestSymbols.Length) Debug.Assert(groupOpt Is Nothing OrElse lookupResult = groupOpt.ResultKind) Dim state = OverloadResolution.CandidateAnalysisResultState.Count If bestCandidates.Count > 0 Then state = bestCandidates(0).State End If If boundArguments.IsDefault Then boundArguments = ImmutableArray(Of BoundExpression).Empty End If Dim singleCandidateAnalysisResult As OverloadResolution.CandidateAnalysisResult = Nothing Dim singleCandidate As OverloadResolution.Candidate = Nothing Dim allowUnexpandedParamArrayForm As Boolean = False Dim allowExpandedParamArrayForm As Boolean = False ' Figure out if we should report single candidate errors If bestSymbols.Length = 1 AndAlso bestCandidates.Count < 3 Then singleCandidateAnalysisResult = bestCandidates(0) singleCandidate = singleCandidateAnalysisResult.Candidate allowExpandedParamArrayForm = singleCandidateAnalysisResult.IsExpandedParamArrayForm allowUnexpandedParamArrayForm = Not allowExpandedParamArrayForm If bestCandidates.Count > 1 Then If bestCandidates(1).IsExpandedParamArrayForm Then allowExpandedParamArrayForm = True Else allowUnexpandedParamArrayForm = True End If End If End If If lookupResult = LookupResultKind.Inaccessible Then If singleCandidate IsNot Nothing Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), GetInaccessibleErrorInfo(singleCandidate.UnderlyingSymbol)) Else If Not queryMode Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), ERRID.ERR_NoViableOverloadCandidates1, bestSymbols(0).Name) End If ' Do not report more errors. GoTo ProduceBoundNode End If Else Debug.Assert(lookupResult = LookupResultKind.Good) End If If diagnosticLocationOpt Is Nothing Then diagnosticLocationOpt = GetLocationForOverloadResolutionDiagnostic(node, groupOpt) End If ' Report diagnostic according to the state of candidates Select Case state Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError, OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_BadOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.Ambiguous Dim candidate As Symbol = bestSymbols(0).OriginalDefinition Dim container As Symbol = candidate.ContainingSymbol ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_MetadataMembersAmbiguous3, candidate.Name, container.GetKindText(), container) Case OverloadResolution.CandidateAnalysisResultState.BadGenericArity Debug.Assert(groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.MethodGroup) Dim mg = DirectCast(groupOpt, BoundMethodGroup) If singleCandidate IsNot Nothing Then Dim typeArguments = If(mg.TypeArgumentsOpt IsNot Nothing, mg.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty) If typeArguments.IsDefault Then typeArguments = ImmutableArray(Of TypeSymbol).Empty End If Dim singleSymbol As Symbol = singleCandidate.UnderlyingSymbol Dim isExtension As Boolean = singleCandidate.IsExtensionMethod If singleCandidate.Arity < typeArguments.Length Then If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric2, ERRID.ERR_TooManyGenericArguments2), singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric1, ERRID.ERR_TooManyGenericArguments1), singleSymbol) End If Else Debug.Assert(singleCandidate.Arity > typeArguments.Length) If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments2, singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments1, singleSymbol) End If End If Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoTypeArgumentCountOverloadCand1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch If node.Kind = SyntaxKind.IdentifierName AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.NamedFieldInitializer AndAlso groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.PropertyGroup Then ' report special diagnostics for a failed overload resolution because all available properties ' require arguments in case this method was called while binding a object member initializer. ReportDiagnostic(diagnostics, diagnosticLocationOpt, If(singleCandidate IsNot Nothing, ERRID.ERR_ParameterizedPropertyInAggrInit1, ERRID.ERR_NoZeroCountArgumentInitCandidates1), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) Else If singleCandidate IsNot Nothing AndAlso (Not queryMode OrElse singleCandidate.ParameterCount <= boundArguments.Length) Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoArgumentCountOverloadCandidates1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch, OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Dim haveBadArgument As Boolean = False For i As Integer = 0 To boundArguments.Length - 1 Step 1 Dim type = boundArguments(i).Type If boundArguments(i).HasErrors OrElse (type IsNot Nothing AndAlso type.IsErrorType()) Then haveBadArgument = True Exit For End If Next If Not haveBadArgument Then If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoCallableOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If End If Case OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_NoCallableOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case OverloadResolution.CandidateAnalysisResultState.Applicable ' it is only possible to get overloading failure with a single candidate ' if we have a paramarray with equally specific virtual signatures Debug.Assert(singleCandidate Is Nothing OrElse singleCandidate.ParameterCount <> 0 AndAlso singleCandidate.Parameters(singleCandidate.ParameterCount - 1).IsParamArray) If bestCandidates(0).RequiresNarrowingConversion Then ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) Else ReportUnspecificProcedures(diagnosticLocationOpt, bestSymbols, diagnostics, (delegateSymbol IsNot Nothing)) End If Case Else ' Unexpected Throw ExceptionUtilities.UnexpectedValue(state) End Select ProduceBoundNode: Dim childBoundNodes As ImmutableArray(Of BoundExpression) If boundArguments.IsEmpty AndAlso boundTypeExpression Is Nothing Then If groupOpt Is Nothing Then childBoundNodes = ImmutableArray(Of BoundExpression).Empty Else childBoundNodes = ImmutableArray.Create(Of BoundExpression)(groupOpt) End If Else Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() If groupOpt IsNot Nothing Then builder.Add(groupOpt) End If If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If If boundTypeExpression IsNot Nothing Then builder.Add(boundTypeExpression) End If childBoundNodes = builder.ToImmutableAndFree() End If Dim resultKind = LookupResultKind.OverloadResolutionFailure If lookupResult < resultKind Then resultKind = lookupResult End If Return New BoundBadExpression(node, resultKind, bestSymbols, childBoundNodes, commonReturnType, hasErrors:=True) End Function ''' <summary> '''Figure out the set of best candidates in the following preference order: ''' 1) Applicable ''' 2) ArgumentMismatch, GenericConstraintsViolated ''' 3) TypeInferenceFailed ''' 4) ArgumentCountMismatch ''' 5) BadGenericArity ''' 6) Ambiguous ''' 7) HasUseSiteError ''' 8) HasUnsupportedMetadata ''' ''' Also return the set of unique symbols behind the set. ''' ''' Returns type symbol for the common type, if any. ''' Otherwise returns ErrorTypeSymbol.UnknownResultType. ''' </summary> Private Shared Function GetSetOfTheBestCandidates( ByRef results As OverloadResolution.OverloadResolutionResult, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), ByRef bestSymbols As ImmutableArray(Of Symbol) ) As TypeSymbol Const Applicable = OverloadResolution.CandidateAnalysisResultState.Applicable Const ArgumentMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch Const GenericConstraintsViolated = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Const TypeInferenceFailed = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Const ArgumentCountMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch Const BadGenericArity = OverloadResolution.CandidateAnalysisResultState.BadGenericArity Const Ambiguous = OverloadResolution.CandidateAnalysisResultState.Ambiguous Const HasUseSiteError = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError Const HasUnsupportedMetadata = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Dim preference(OverloadResolution.CandidateAnalysisResultState.Count - 1) As Integer preference(Applicable) = 1 preference(ArgumentMismatch) = 2 preference(GenericConstraintsViolated) = 2 preference(TypeInferenceFailed) = 3 preference(ArgumentCountMismatch) = 4 preference(BadGenericArity) = 5 preference(Ambiguous) = 6 preference(HasUseSiteError) = 7 preference(HasUnsupportedMetadata) = 8 For Each candidate In results.Candidates Dim prefNew = preference(candidate.State) If prefNew <> 0 Then If bestCandidates.Count = 0 Then bestCandidates.Add(candidate) Else Dim prefOld = preference(bestCandidates(0).State) If prefNew = prefOld Then bestCandidates.Add(candidate) ElseIf prefNew < prefOld Then bestCandidates.Clear() bestCandidates.Add(candidate) End If End If End If Next ' Collect unique best symbols. Dim bestSymbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(bestCandidates.Count) Dim commonReturnType As TypeSymbol = Nothing If bestCandidates.Count = 1 Then ' For multiple candidates we never pick common type that refers to method's type parameter ' because each method has distinct type parameters. For single candidate case we need to ' ensure this explicitly. Dim underlyingSymbol As Symbol = bestCandidates(0).Candidate.UnderlyingSymbol bestSymbolsBuilder.Add(underlyingSymbol) commonReturnType = bestCandidates(0).Candidate.ReturnType If underlyingSymbol.Kind = SymbolKind.Method Then Dim method = DirectCast(underlyingSymbol, MethodSymbol) If method.IsGenericMethod AndAlso commonReturnType.ReferencesMethodsTypeParameter(method) Then Select Case CInt(bestCandidates(0).State) Case TypeInferenceFailed, HasUseSiteError, HasUnsupportedMetadata, BadGenericArity, ArgumentCountMismatch commonReturnType = Nothing End Select End If End If Else For i As Integer = 0 To bestCandidates.Count - 1 Step 1 If i = 0 OrElse Not bestSymbolsBuilder(bestSymbolsBuilder.Count - 1).Equals(bestCandidates(i).Candidate.UnderlyingSymbol) Then bestSymbolsBuilder.Add(bestCandidates(i).Candidate.UnderlyingSymbol) Dim returnType = bestCandidates(i).Candidate.ReturnType If commonReturnType Is Nothing Then commonReturnType = returnType ElseIf commonReturnType IsNot ErrorTypeSymbol.UnknownResultType AndAlso Not commonReturnType.IsSameTypeIgnoringAll(returnType) Then commonReturnType = ErrorTypeSymbol.UnknownResultType End If End If Next End If bestSymbols = bestSymbolsBuilder.ToImmutableAndFree() Return If(commonReturnType, ErrorTypeSymbol.UnknownResultType) End Function Private Shared Sub ReportUnspecificProcedures( diagnosticLocation As Location, bestSymbols As ImmutableArray(Of Symbol), diagnostics As BindingDiagnosticBag, isDelegateContext As Boolean ) Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(bestSymbols.Length) Dim notMostSpecificMessage = ErrorFactory.ErrorInfo(ERRID.ERR_NotMostSpecificOverload) Dim withContainingTypeInDiagnostics As Boolean = False If Not bestSymbols(0).IsReducedExtensionMethod Then Dim container As NamedTypeSymbol = bestSymbols(0).ContainingType For i As Integer = 1 To bestSymbols.Length - 1 Step 1 If Not TypeSymbol.Equals(bestSymbols(i).ContainingType, container, TypeCompareKind.ConsiderEverything) Then withContainingTypeInDiagnostics = True End If Next End If For i As Integer = 0 To bestSymbols.Length - 1 Step 1 ' in delegate context we just output for each candidates ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer) ' Public Sub goo(p As Integer) ' ' in other contexts we give more information, e.g. ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer): <reason> ' Public Sub goo(p As Integer): <reason> Dim bestSymbol As Symbol = bestSymbols(i) Dim bestSymbolIsExtension As Boolean = bestSymbol.IsReducedExtensionMethod If isDelegateContext Then If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate2, bestSymbol, bestSymbol.ContainingType)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, bestSymbol)) End If Else If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, bestSymbol, bestSymbol.ContainingType, notMostSpecificMessage)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol), notMostSpecificMessage)) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, bestSymbol, notMostSpecificMessage)) End If End If Next ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(If(isDelegateContext, ERRID.ERR_AmbiguousDelegateBinding2, ERRID.ERR_NoMostSpecificOverload2), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0)), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree()) )) End Sub Private Sub ReportOverloadResolutionFailureForASetOfCandidates( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, errorNo As ERRID, candidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode ) Dim diagnosticPerSymbol = ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))).GetInstance(candidates.Count) If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If For i As Integer = 0 To candidates.Count - 1 Step 1 ' See if we need to consider both expanded and unexpanded version of the same method. ' We want to report only one set of errors in this case. ' Note, that, when OverloadResolution collects candidates expanded form always ' immediately follows unexpanded form, if both should be considered. Dim allowExpandedParamArrayForm As Boolean = candidates(i).IsExpandedParamArrayForm Dim allowUnexpandedParamArrayForm As Boolean = Not allowExpandedParamArrayForm If allowUnexpandedParamArrayForm AndAlso i + 1 < candidates.Count AndAlso candidates(i + 1).IsExpandedParamArrayForm AndAlso candidates(i + 1).Candidate.UnderlyingSymbol.Equals(candidates(i).Candidate.UnderlyingSymbol) Then allowExpandedParamArrayForm = True i += 1 End If Dim candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) ' Collect diagnostic for this candidate ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocation, lookupResult, candidates(i), arguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, False, errorNo = If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), candidateDiagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=Nothing) diagnosticPerSymbol.Add(KeyValuePairUtil.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) Next ' See if there are errors that are reported for each candidate at the same location within a lambda argument. ' Report them and don't report remaining diagnostics for each symbol separately. If Not ReportCommonErrorsFromLambdas(diagnosticPerSymbol, arguments, diagnostics) Then Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(candidates.Count) For i As Integer = 0 To diagnosticPerSymbol.Count - 1 Dim symbol = diagnosticPerSymbol(i).Key Dim isExtension As Boolean = symbol.IsReducedExtensionMethod() Dim sealedCandidateDiagnostics = diagnosticPerSymbol(i).Value.Diagnostics ' When reporting errors for an AddressOf, Dev 10 shows different error messages depending on how many ' errors there are per candidate. ' One narrowing error will be shown like: ' 'Public Sub goo6(p As Integer, p2 As Byte)': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. ' More than one narrowing issues in the parameters are abbreviated with: ' 'Public Sub goo6(p As Byte, p2 As Byte)': Method does not have a signature compatible with the delegate. If delegateSymbol Is Nothing OrElse Not sealedCandidateDiagnostics.Skip(1).Any() Then If isExtension Then For Each iDiagnostic In sealedCandidateDiagnostics diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next Else For Each iDiagnostic In sealedCandidateDiagnostics Dim msg = VisualBasicDiagnosticFormatter.Instance.Format(iDiagnostic.WithLocation(Location.None)) diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next End If Else If isExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) End If End If Next Dim diagnosticCompoundInfos() As DiagnosticInfo = diagnosticInfos.ToArrayAndFree() If delegateSymbol Is Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) Else ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), CustomSymbolDisplayFormatter.DelegateSignature(delegateSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) End If End If diagnosticPerSymbol.Free() End Sub Private Shared Function ReportCommonErrorsFromLambdas( diagnosticPerSymbol As ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))), arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As Boolean Dim haveCommonErrors As Boolean = False For Each diagnostic In diagnosticPerSymbol(0).Value.Diagnostics If diagnostic.Severity <> DiagnosticSeverity.Error Then Continue For End If For Each argument In arguments If argument.Syntax.SyntaxTree Is diagnostic.Location.SourceTree AndAlso argument.Kind = BoundKind.UnboundLambda Then If argument.Syntax.Span.Contains(diagnostic.Location.SourceSpan) Then Dim common As Boolean = True For i As Integer = 1 To diagnosticPerSymbol.Count - 1 If Not diagnosticPerSymbol(i).Value.Diagnostics.Contains(diagnostic) Then common = False Exit For End If Next If common Then haveCommonErrors = True diagnostics.Add(diagnostic) End If Exit For End If End If Next Next Return haveCommonErrors End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments. Anything that ''' OverloadResolution.MatchArguments flags as an error should be detected by ''' this function as well. ''' </summary> Private Sub ReportOverloadResolutionFailureForASingleCandidate( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, ByRef candidateAnalysisResult As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), allowUnexpandedParamArrayForm As Boolean, allowExpandedParamArrayForm As Boolean, includeMethodNameInErrorMessages As Boolean, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode, representCandidateInDiagnosticsOpt As Symbol ) Dim candidate As OverloadResolution.Candidate = candidateAnalysisResult.Candidate If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If Debug.Assert(argumentNames.IsDefaultOrEmpty OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length)) Debug.Assert(allowUnexpandedParamArrayForm OrElse allowExpandedParamArrayForm) If candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Then If lookupResult <> LookupResultKind.Inaccessible Then Debug.Assert(lookupResult = LookupResultKind.Good) ReportUseSite(diagnostics, diagnosticLocation, candidate.UnderlyingSymbol.GetUseSiteInfo()) End If Return End If ' To simplify following code If Not argumentNames.IsDefault AndAlso argumentNames.Length = 0 Then argumentNames = Nothing End If Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance(candidate.ParameterCount, -1) Dim paramArrayItems As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance() Try '§11.8.2 Applicable Methods '1. First, match each positional argument in order to the list of method parameters. 'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. 'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments. 'If a positional argument is omitted, the method is not applicable. ' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable." ' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional. Dim positionalArguments As Integer = 0 Dim paramIndex = 0 Dim someArgumentsBad As Boolean = False Dim someParamArrayArgumentsBad As Boolean = False Dim seenOutOfPositionNamedArgIndex As Integer = -1 Dim candidateSymbol As Symbol = candidate.UnderlyingSymbol Dim candidateIsExtension As Boolean = candidate.IsExtensionMethod For i As Integer = 0 To arguments.Length - 1 Step 1 ' A named argument which is used in-position counts as positional If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then Exit For End If If paramIndex <> i Then ' all remaining arguments must be named seenOutOfPositionNamedArgIndex = i Exit For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then Exit For End If Debug.Assert(parameterToArgumentMap(paramIndex) = -1) End If If paramIndex = candidate.ParameterCount Then If Not someArgumentsBad Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If ElseIf paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' Collect ParamArray arguments While i < arguments.Length If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then ' First named argument Continue For End If If arguments(i).Kind = BoundKind.OmittedArgument Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_OmittedParamArrayArgument) someParamArrayArgumentsBad = True Else paramArrayItems.Add(i) End If positionalArguments += 1 i += 1 End While Exit For Else parameterToArgumentMap(paramIndex) = i paramIndex += 1 End If positionalArguments += 1 Next Dim skippedSomeArguments As Boolean = False '§11.8.2 Applicable Methods '2. Next, match each named argument to a parameter with the given name. 'If one of the named arguments fails to match, matches a paramarray parameter, 'or matches an argument already matched with another positional or named argument, 'the method is not applicable. For i As Integer = positionalArguments To arguments.Length - 1 Step 1 Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0) If argumentNames(i) Is Nothing Then ' Unnamed argument follows out-of-position named arguments If Not someArgumentsBad Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(seenOutOfPositionNamedArgIndex).Syntax), ERRID.ERR_BadNonTrailingNamedArgument, argumentNames(seenOutOfPositionNamedArgIndex)) End If Return End If If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then ' ERRID_NamedParamNotFound1 ' ERRID_NamedParamNotFound2 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' ERRID_NamedParamArrayArgument ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamArrayArgument) someArgumentsBad = True Continue For End If If parameterToArgumentMap(paramIndex) <> -1 AndAlso arguments(parameterToArgumentMap(paramIndex)).Kind <> BoundKind.OmittedArgument Then ' ERRID_NamedArgUsedTwice1 ' ERRID_NamedArgUsedTwice2 ' ERRID_NamedArgUsedTwice3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If ' It is an error for a named argument to specify ' a value for an explicitly omitted positional argument. If paramIndex < positionalArguments Then 'ERRID_NamedArgAlsoOmitted1 'ERRID_NamedArgAlsoOmitted2 'ERRID_NamedArgAlsoOmitted3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If parameterToArgumentMap(paramIndex) = i Next ' Check whether type inference failed If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt) End If If candidate.IsGeneric AndAlso candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Then ' Bug 122092: AddressOf doesn't want detailed info on which parameters could not be ' inferred, just report the general type inference failed message in this case. If delegateSymbol IsNot Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_DelegateBindingTypeInferenceFails) Return End If If Not candidateAnalysisResult.SomeInferenceFailed Then Dim reportedAnError As Boolean = False For i As Integer = 0 To candidate.Arity - 1 Step 1 If candidateAnalysisResult.NotInferredTypeArguments(i) Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam1, candidate.TypeParameters(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam3, candidate.TypeParameters(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam2, candidate.TypeParameters(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If reportedAnError = True End If Next If reportedAnError Then Return End If End If Dim inferenceErrorReasons As InferenceErrorReasons = candidateAnalysisResult.InferenceErrorReasons If (inferenceErrorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous1, ERRID.ERR_TypeInferenceFailureAmbiguous1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous3, ERRID.ERR_TypeInferenceFailureAmbiguous3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous2, ERRID.ERR_TypeInferenceFailureAmbiguous2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If ElseIf (inferenceErrorReasons And InferenceErrorReasons.NoBest) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest1, ERRID.ERR_TypeInferenceFailureNoBest1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest3, ERRID.ERR_TypeInferenceFailureNoBest3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest2, ERRID.ERR_TypeInferenceFailureNoBest2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyResolvedErrors Then ' Already reported some errors, let's not report a general inference error Return End If If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit1, ERRID.ERR_TypeInferenceFailure1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit3, ERRID.ERR_TypeInferenceFailure3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit2, ERRID.ERR_TypeInferenceFailure2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If Return End If ' Check generic constraints for method type arguments. If candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Then Debug.Assert(candidate.IsGeneric) Debug.Assert(candidate.UnderlyingSymbol.Kind = SymbolKind.Method) Dim method = DirectCast(candidate.UnderlyingSymbol, MethodSymbol) ' TODO: Dev10 uses the location of the type parameter or argument that ' violated the constraint, rather than the entire invocation expression. Dim succeeded = method.CheckConstraints(diagnosticLocation, diagnostics, template:=GetNewCompoundUseSiteInfo(diagnostics)) Debug.Assert(Not succeeded) Return End If If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyErrors Then Return End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim argIndex As Integer Dim candidateIsAProperty As Boolean = (candidateSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim isByRef As Boolean = param.IsByRef Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then If targetType.Kind <> SymbolKind.ErrorType Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) End If someArgumentsBad = True Continue For ElseIf someParamArrayArgumentsBad Then Continue For End If If paramArrayItems.Count = 1 Then Dim paramArrayArgument = arguments(paramArrayItems(0)) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing If allowUnexpandedParamArrayForm AndAlso Not (Not paramArrayArgument.HasErrors AndAlso OverloadResolution.CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) Then allowUnexpandedParamArrayForm = False End If '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form If allowExpandedParamArrayForm AndAlso paramArrayArgument.IsNothingLiteral() Then allowExpandedParamArrayForm = False End If Else ' Unexpanded form is not applicable: there are either more than one value or no values. If Not allowExpandedParamArrayForm Then If paramArrayItems.Count = 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If someArgumentsBad = True Continue For End If allowUnexpandedParamArrayForm = False End If If allowUnexpandedParamArrayForm Then argument = arguments(paramArrayItems(0)) ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics) ElseIf allowExpandedParamArrayForm Then Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) someArgumentsBad = True Continue For End If Dim arrayElementType = arrayType.ElementType For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 argument = arguments(paramArrayItems(i)) ReportByValConversionErrors(param, argument, arrayElementType, reportNarrowingConversions, diagnostics) Next Else Debug.Assert(paramArrayItems.Count = 1) Dim paramArrayArgument = arguments(paramArrayItems(0)) ReportDiagnostic(diagnostics, paramArrayArgument.Syntax, ERRID.ERR_ParamArrayArgumentMismatch) End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) ' Argument nothing when the argument syntax is missing or BoundKind.OmittedArgument when the argument list contains commas ' for the missing syntax so we have to test for both. If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then If argument Is Nothing AndAlso skippedSomeArguments Then someArgumentsBad = True Continue For End If 'See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments ' Need to handle optional arguments here, there could be conversion errors, etc. ' reducedExtensionReceiverOpt is used to determine the default value of a CallerArgumentExpression when it refers to the first parameter of an extension method. ' Don't bother with correctly determining the correct value for this case since we're in an error case anyway. argument = GetArgumentForParameterDefaultValue(param, node, diagnostics, callerInfoOpt, parameterToArgumentMap, arguments, reducedExtensionReceiverOpt:=Nothing) If argument Is Nothing Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If End If Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If isByRef AndAlso Not candidateIsAProperty AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then ReportByRefConversionErrors(candidate, param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) Else ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) End If Next Finally paramArrayItems.Free() parameterToArgumentMap.Free() End Try End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByRefParameter ''' </summary> Private Sub ReportByRefConversionErrors( candidate As OverloadResolution.Candidate, param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return End If If argument.IsSupportingAssignment() Then If Not (argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type)) Then If Not ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) Then ' Check copy back conversion Dim boundTemp = New BoundRValuePlaceholder(argument.Syntax, targetType) Dim copyBackType = argument.GetTypeOfAssignmentTarget() Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(boundTemp, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then ' Possible only with user-defined conversions, I think. CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf Conversions.IsNarrowingConversion(conv.Key) Then Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0) If OptionStrict = VisualBasic.OptionStrict.On Then CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf reportNarrowingConversions Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentCopyBackNarrowing3, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType, copyBackType) End If End If End If End If Else ' No copy back needed ' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which ' would be an LValue field, if it were referred to in the constructor outside of a lambda, ' we need to report an error because the operation will result in a simulated pass by ' ref (through a temp, without a copy back), which might be not the intent. If Report_ERRID_ReadOnlyInClosure(argument) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ReadOnlyInClosure) End If ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) End If End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByValParameter. ''' </summary> Private Function ReportByValConversionErrors( param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) As Boolean ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return True End If Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If Dim requiresNarrowingConversion As Boolean = False If Conversions.IsNarrowingConversion(conv.Key) Then If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then If OptionStrict = VisualBasic.OptionStrict.On Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error ' because delegates have different error messages in case there is one or more candidates for narrowing ' indicate this as well. CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If End If requiresNarrowingConversion = True ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then ' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type ' as narrowing. requiresNarrowingConversion = True End If If reportNarrowingConversions AndAlso requiresNarrowingConversion Then Dim err As ERRID = ERRID.ERR_ArgumentNarrowing3 Dim targetDelegateType = targetType.DelegateOrExpressionDelegate(Me) If argument.Kind = BoundKind.QueryLambda AndAlso targetDelegateType IsNot Nothing Then Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso Not invoke.IsSub Then err = ERRID.ERR_NestedFunctionArgumentNarrowing3 argument = DirectCast(argument, BoundQueryLambda).Expression targetType = invoke.ReturnType End If End If If argument.Type Is Nothing Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentNarrowing2, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType) Else ReportDiagnostic(diagnostics, argument.Syntax, err, CustomSymbolDisplayFormatter.ShortErrorName(param), argument.Type, targetType) End If End If Return False End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments, which populates ''' data this function operates on. ''' </summary> Private Function PassArguments( node As SyntaxNode, ByRef candidate As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) Debug.Assert(candidate.State = OverloadResolution.CandidateAnalysisResultState.Applicable) If (arguments.IsDefault) Then arguments = ImmutableArray(Of BoundExpression).Empty End If Dim paramCount As Integer = candidate.Candidate.ParameterCount Dim parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(paramCount, -1) Dim argumentsInOrder = ArrayBuilder(Of BoundExpression).GetInstance(paramCount) Dim defaultArguments = BitVector.Null Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing If candidate.IsExpandedParamArrayForm Then paramArrayItems = ArrayBuilder(Of Integer).GetInstance() End If Dim paramIndex As Integer ' For each parameter figure out matching argument. If candidate.ArgsToParamsOpt.IsDefaultOrEmpty Then Dim regularParamCount As Integer = paramCount If candidate.IsExpandedParamArrayForm Then regularParamCount -= 1 End If For i As Integer = 0 To Math.Min(regularParamCount, arguments.Length) - 1 Step 1 If arguments(i).Kind <> BoundKind.OmittedArgument Then parameterToArgumentMap(i) = i End If Next If candidate.IsExpandedParamArrayForm Then For i As Integer = regularParamCount To arguments.Length - 1 Step 1 paramArrayItems.Add(i) Next End If Else Dim argsToParams = candidate.ArgsToParamsOpt For i As Integer = 0 To argsToParams.Length - 1 Step 1 paramIndex = argsToParams(i) If arguments(i).Kind <> BoundKind.OmittedArgument Then If (candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1) Then paramArrayItems.Add(i) Else parameterToArgumentMap(paramIndex) = i End If End If Next End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To paramCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity If candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then Dim arrayElementType = DirectCast(targetType, ArrayTypeSymbol).ElementType Dim items = ArrayBuilder(Of BoundExpression).GetInstance(paramArrayItems.Count) For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 items.Add(PassArgumentByVal(arguments(paramArrayItems(i)), If(candidate.ConversionsOpt.IsDefaultOrEmpty, Conversions.Identity, candidate.ConversionsOpt(paramArrayItems(i))), arrayElementType, diagnostics)) Next ' Create the bound array and ensure that it is marked as compiler generated. argument = New BoundArrayCreation(node, True, (New BoundExpression() {New BoundLiteral(node, ConstantValue.Create(items.Count), GetSpecialType(SpecialType.System_Int32, node, diagnostics)).MakeCompilerGenerated()}).AsImmutableOrNull(), New BoundArrayInitialization(node, items.ToImmutableAndFree(), targetType).MakeCompilerGenerated(), Nothing, Nothing, targetType).MakeCompilerGenerated() Else Dim argIndex As Integer argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument IsNot Nothing AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso param.IsParamArray Then argument = ApplyImplicitConversion(argument.Syntax, targetType, argument, diagnostics) ' Leave both conversions at identity since we already applied the conversion ElseIf argIndex > -1 Then If Not candidate.ConversionsOpt.IsDefaultOrEmpty Then conversion = candidate.ConversionsOpt(argIndex) End If If Not candidate.ConversionsBackOpt.IsDefaultOrEmpty Then conversionBack = candidate.ConversionsBackOpt(argIndex) End If End If End If Dim argumentIsDefaultValue As Boolean = False If argument Is Nothing Then Debug.Assert(Not candidate.OptionalArguments.IsEmpty, "Optional arguments expected") If defaultArguments.IsNull Then defaultArguments = BitVector.Create(paramCount) End If ' Deal with Optional arguments Dim defaultArgument As OverloadResolution.OptionalArgument = candidate.OptionalArguments(paramIndex) argument = defaultArgument.DefaultValue diagnostics.AddDependencies(defaultArgument.Dependencies) argumentIsDefaultValue = True defaultArguments(paramIndex) = True Debug.Assert(argument IsNot Nothing) conversion = defaultArgument.Conversion Dim argType = argument.Type If argType IsNot Nothing Then ' Report usesiteerror if it exists. Dim useSiteInfo = argType.GetUseSiteInfo ReportUseSite(diagnostics, argument.Syntax, useSiteInfo) End If End If ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. Debug.Assert(Not argumentIsDefaultValue OrElse argument.WasCompilerGenerated) Dim adjustedArgument As BoundExpression = PassArgument(argument, conversion, candidateIsAProperty, conversionBack, targetType, param, diagnostics) ' Keep SemanticModel happy. If argumentIsDefaultValue AndAlso adjustedArgument IsNot argument Then adjustedArgument.SetWasCompilerGenerated() End If argumentsInOrder.Add(adjustedArgument) Next If paramArrayItems IsNot Nothing Then paramArrayItems.Free() End If parameterToArgumentMap.Free() Return (argumentsInOrder.ToImmutableAndFree(), defaultArguments) End Function Private Function PassArgument( argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), forceByValueSemantics As Boolean, conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, param As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(Not param.IsByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If param.IsByRef AndAlso Not forceByValueSemantics AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then Return PassArgumentByRef(param.IsOut, argument, conversionTo, conversionFrom, targetType, param.Name, diagnostics) Else Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function Private Function PassArgumentByRef( isOutParameter As Boolean, argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, parameterName As String, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionTo.Key = checkAgainst.Key) Debug.Assert(Equals(conversionTo.Value, checkAgainst.Value)) #End If ' TODO: Fields of MarshalByRef object are passed via temp. Dim isLValue As Boolean = argument.IsLValue() If isLValue AndAlso argument.Kind = BoundKind.PropertyAccess Then argument = argument.SetAccessKind(PropertyAccessKind.Get) End If If isLValue AndAlso Conversions.IsIdentityConversion(conversionTo.Key) Then 'Nothing to do Debug.Assert(Conversions.IsIdentityConversion(conversionFrom.Key)) Return argument ElseIf isLValue OrElse argument.IsSupportingAssignment() Then ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim inPlaceholder = New BoundByRefArgumentPlaceholder(argument.Syntax, isOutParameter, argument.Type, argument.HasErrors).MakeCompilerGenerated() Dim inConversion = CreateConversionAndReportDiagnostic(argument.Syntax, inPlaceholder, conversionTo, False, targetType, diagnostics) Dim outPlaceholder = New BoundRValuePlaceholder(argument.Syntax, targetType).MakeCompilerGenerated() Dim copyBackType = argument.GetTypeOfAssignmentTarget() #If DEBUG Then checkAgainst = Conversions.ClassifyConversion(outPlaceholder, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionFrom.Key = checkAgainst.Key) Debug.Assert(Equals(conversionFrom.Value, checkAgainst.Value)) #End If Dim outConversion = CreateConversionAndReportDiagnostic(argument.Syntax, outPlaceholder, conversionFrom, False, copyBackType, diagnostics, copybackConversionParamName:=parameterName).MakeCompilerGenerated() ' since we are going to assign to a latebound invocation ' force its arguments to be rvalues. If argument.Kind = BoundKind.LateInvocation Then argument = MakeArgsRValues(DirectCast(argument, BoundLateInvocation), diagnostics) End If Dim copyBackExpression = BindAssignment(argument.Syntax, argument, outConversion, diagnostics) Debug.Assert(copyBackExpression.HasErrors OrElse (copyBackExpression.Kind = BoundKind.AssignmentOperator AndAlso DirectCast(copyBackExpression, BoundAssignmentOperator).Right Is outConversion)) If Not isLValue Then If argument.IsLateBound() Then argument = argument.SetLateBoundAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Else ' Diagnostics for PropertyAccessKind.Set case has been reported when we called BindAssignment. WarnOnRecursiveAccess(argument, PropertyAccessKind.Get, diagnostics) argument = argument.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) End If End If Return New BoundByRefArgumentWithCopyBack(argument.Syntax, argument, inConversion, inPlaceholder, outConversion, outPlaceholder, targetType, copyBackExpression.HasErrors).MakeCompilerGenerated() Else Dim propertyAccess = TryCast(argument, BoundPropertyAccess) If propertyAccess IsNot Nothing AndAlso propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.SetMethod?.IsInitOnly Then Debug.Assert(Not propertyAccess.IsWriteable) ' Used to be writable prior to VB 16.9, which caused a use-site error while binding an assignment above. InternalSyntax.Parser.CheckFeatureAvailability(diagnostics, argument.Syntax.Location, DirectCast(argument.Syntax.SyntaxTree.Options, VisualBasicParseOptions).LanguageVersion, InternalSyntax.Feature.InitOnlySettersUsage) End If ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef. Code gen will do this. Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function ' when latebound invocation acts as an LHS in an assignment ' its arguments are always passed ByVal since property parameters ' are always treated as ByVal ' This method is used to force the arguments to be RValues Private Function MakeArgsRValues(ByVal invocation As BoundLateInvocation, diagnostics As BindingDiagnosticBag) As BoundLateInvocation Dim args = invocation.ArgumentsOpt If Not args.IsEmpty Then Dim argBuilder As ArrayBuilder(Of BoundExpression) = Nothing For i As Integer = 0 To args.Length - 1 Dim arg = args(i) Dim newArg = MakeRValue(arg, diagnostics) If argBuilder Is Nothing AndAlso arg IsNot newArg Then argBuilder = ArrayBuilder(Of BoundExpression).GetInstance argBuilder.AddRange(args, i) End If If argBuilder IsNot Nothing Then argBuilder.Add(newArg) End If Next If argBuilder IsNot Nothing Then invocation = invocation.Update(invocation.Member, argBuilder.ToImmutableAndFree, invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) End If End If Return invocation End Function Friend Function PassArgumentByVal( argument As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversion.Key = checkAgainst.Key) Debug.Assert(Equals(conversion.Value, checkAgainst.Value)) #End If argument = CreateConversionAndReportDiagnostic(argument.Syntax, argument, conversion, False, targetType, diagnostics) Debug.Assert(Not argument.IsLValue) Return argument End Function ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( argumentListOpt As ArgumentListSyntax, ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) Dim args As ImmutableArray(Of ArgumentSyntax) = Nothing If argumentListOpt IsNot Nothing Then Dim arguments = argumentListOpt.Arguments Dim argsArr(arguments.Count - 1) As ArgumentSyntax For i = 0 To argsArr.Length - 1 argsArr(i) = arguments(i) Next args = argsArr.AsImmutableOrNull End If BindArgumentsAndNames( args, boundArguments, argumentNames, argumentNamesLocations, diagnostics ) End Sub ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( arguments As ImmutableArray(Of ArgumentSyntax), ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) ' With SeparatedSyntaxList, it is most efficient to iterate with foreach and not to access Count. If arguments.IsDefaultOrEmpty Then boundArguments = s_noArguments argumentNames = Nothing argumentNamesLocations = Nothing Else Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim argumentNamesBuilder As ArrayBuilder(Of String) = Nothing Dim argumentNamesLocationsBuilder As ArrayBuilder(Of Location) = Nothing Dim argCount As Integer = 0 Dim argumentSyntax As ArgumentSyntax For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) boundArgumentsBuilder.Add(BindValue(simpleArgument.Expression, diagnostics)) If simpleArgument.IsNamed Then ' The common case is no named arguments. So we defer all work until the first named argument is seen. If argumentNamesBuilder Is Nothing Then argumentNamesBuilder = ArrayBuilder(Of String).GetInstance() argumentNamesLocationsBuilder = ArrayBuilder(Of Location).GetInstance() For i = 0 To argCount - 1 argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) Next i End If Dim id = simpleArgument.NameColonEquals.Name.Identifier If id.ValueText.Length > 0 Then argumentNamesBuilder.Add(id.ValueText) Else argumentNamesBuilder.Add(Nothing) End If argumentNamesLocationsBuilder.Add(id.GetLocation()) ElseIf argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.OmittedArgument boundArgumentsBuilder.Add(New BoundOmittedArgument(argumentSyntax, Nothing)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.RangeArgument ' NOTE: Redim statement supports range argument, like: Redim x(0 To 3)(0 To 6) ' This behavior is misleading, because the 'range' (0 To 3) is actually ' being ignored and only upper bound is being used. ' TODO: revise (add warning/error?) Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax) CheckRangeArgumentLowerBound(rangeArgument, diagnostics) boundArgumentsBuilder.Add(BindValue(rangeArgument.UpperBound, diagnostics)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select argCount += 1 Next boundArguments = boundArgumentsBuilder.ToImmutableAndFree argumentNames = If(argumentNamesBuilder Is Nothing, Nothing, argumentNamesBuilder.ToImmutableAndFree) argumentNamesLocations = If(argumentNamesLocationsBuilder Is Nothing, Nothing, argumentNamesLocationsBuilder.ToImmutableAndFree) End If End Sub Friend Function GetArgumentForParameterDefaultValue(param As ParameterSymbol, syntax As SyntaxNode, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, parameterToArgumentMap As ArrayBuilder(Of Integer), arguments As ImmutableArray(Of BoundExpression), reducedExtensionReceiverOpt As BoundExpression) As BoundExpression Dim defaultArgument As BoundExpression = Nothing ' See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments. HasDefaultValue is true if the parameter is optional and has a default value. Dim defaultConstantValue As ConstantValue = If(param.IsOptional, param.ExplicitDefaultConstantValue(DefaultParametersInProgress), Nothing) If defaultConstantValue IsNot Nothing Then If callerInfoOpt IsNot Nothing AndAlso callerInfoOpt.SyntaxTree IsNot Nothing AndAlso Not callerInfoOpt.SyntaxTree.IsEmbeddedOrMyTemplateTree() AndAlso Not SuppressCallerInfo Then Dim isCallerLineNumber As Boolean = param.IsCallerLineNumber Dim isCallerMemberName As Boolean = param.IsCallerMemberName Dim isCallerFilePath As Boolean = param.IsCallerFilePath Dim callerArgumentExpressionParameterIndex As Integer = param.CallerArgumentExpressionParameterIndex Dim isCallerArgumentExpression = callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2) If isCallerLineNumber OrElse isCallerMemberName OrElse isCallerFilePath OrElse isCallerArgumentExpression Then Dim callerInfoValue As ConstantValue = Nothing If isCallerLineNumber Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayLineNumber(GetCallerLocation(callerInfoOpt))) ElseIf isCallerMemberName Then Dim container As Symbol = ContainingMember While container IsNot Nothing Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Event Exit While Case SymbolKind.Method If container.IsLambdaMethod Then container = container.ContainingSymbol Else Dim propertyOrEvent As Symbol = DirectCast(container, MethodSymbol).AssociatedSymbol If propertyOrEvent IsNot Nothing Then container = propertyOrEvent End If Exit While End If Case Else container = container.ContainingSymbol End Select End While If container IsNot Nothing AndAlso container.Name IsNot Nothing Then callerInfoValue = ConstantValue.Create(container.Name) End If ElseIf isCallerFilePath Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayPath(callerInfoOpt.Span, Me.Compilation.Options.SourceReferenceResolver)) Else Debug.Assert(callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2)) Dim argumentSyntax As SyntaxNode = Nothing If callerArgumentExpressionParameterIndex = -1 Then argumentSyntax = reducedExtensionReceiverOpt.Syntax Else Dim argumentIndex = parameterToArgumentMap(callerArgumentExpressionParameterIndex) Debug.Assert(argumentIndex < arguments.Length) If argumentIndex > -1 Then argumentSyntax = arguments(argumentIndex).Syntax End If End If If argumentSyntax IsNot Nothing Then callerInfoValue = ConstantValue.Create(argumentSyntax.ToString()) End If End If If callerInfoValue IsNot Nothing Then ' Use the value only if it will not cause errors. Dim ignoreDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) Dim literal As BoundLiteral If callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.Int32 Then literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_Int32, syntax, ignoreDiagnostics)) Else Debug.Assert(callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.String) literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_String, syntax, ignoreDiagnostics)) End If Dim convertedValue As BoundExpression = ApplyImplicitConversion(syntax, param.Type, literal, ignoreDiagnostics) If Not convertedValue.HasErrors AndAlso Not ignoreDiagnostics.HasAnyErrors Then ' Dev11 #248795: Caller info should be omitted if user defined conversion is involved. If Not (convertedValue.Kind = BoundKind.Conversion AndAlso (DirectCast(convertedValue, BoundConversion).ConversionKind And ConversionKind.UserDefined) <> 0) Then defaultConstantValue = callerInfoValue End If End If ignoreDiagnostics.Free() End If End If End If ' For compatibility with the native compiler bad metadata constants should be treated as default(T). This ' is a possible outcome of running an obfuscator over a valid DLL If defaultConstantValue.IsBad Then defaultConstantValue = ConstantValue.Null End If Dim defaultSpecialType = defaultConstantValue.SpecialType Dim defaultArgumentType As TypeSymbol = Nothing ' Constant has a type. Dim paramNullableUnderlyingTypeOrSelf As TypeSymbol = param.Type.GetNullableUnderlyingTypeOrSelf() If param.HasOptionCompare Then ' If the argument has the OptionCompareAttribute ' then use the setting for Option Compare [Binary|Text] ' Other languages will use the default value specified. If Me.OptionCompareText Then defaultConstantValue = ConstantValue.Create(1) Else defaultConstantValue = ConstantValue.Default(SpecialType.System_Int32) End If If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32 Then defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else defaultArgumentType = GetSpecialType(SpecialType.System_Int32, syntax, diagnostics) End If ElseIf defaultSpecialType <> SpecialType.None Then If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = defaultSpecialType Then ' Enum default values are encoded as the underlying primitive type. If the underlying types match then ' use the parameter's enum type. defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else 'Use the primitive type. defaultArgumentType = GetSpecialType(defaultSpecialType, syntax, diagnostics) End If Else ' No type in constant. Constant should be nothing Debug.Assert(defaultConstantValue.IsNothing) End If defaultArgument = New BoundLiteral(syntax, defaultConstantValue, defaultArgumentType) ElseIf param.IsOptional Then ' Handle optional object type argument when no default value is specified. ' Section 3 of §11.8.2 Applicable Methods If param.Type.SpecialType = SpecialType.System_Object Then Dim methodSymbol As MethodSymbol = Nothing If param.IsMarshalAsObject Then ' Nothing defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) ElseIf param.IsIDispatchConstant Then ' new DispatchWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, syntax, diagnostics), MethodSymbol) ElseIf param.IsIUnknownConstant Then ' new UnknownWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, syntax, diagnostics), MethodSymbol) Else defaultArgument = New BoundOmittedArgument(syntax, param.Type) End If If methodSymbol IsNot Nothing Then Dim argument = New BoundLiteral(syntax, ConstantValue.Null, param.Type).MakeCompilerGenerated() defaultArgument = New BoundObjectCreationExpression(syntax, methodSymbol, ImmutableArray.Create(Of BoundExpression)(argument), Nothing, methodSymbol.ContainingType) End If Else defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) End If End If Return defaultArgument?.MakeCompilerGenerated() End Function Private Shared Function GetCallerLocation(syntax As SyntaxNode) As TextSpan Select Case syntax.Kind Case SyntaxKind.SimpleMemberAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).Name.Span Case SyntaxKind.DictionaryAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).OperatorToken.Span Case Else Return syntax.Span End Select End Function ''' <summary> ''' Return true if the node is an immediate child of a call statement. ''' </summary> Private Shared Function IsCallStatementContext(node As InvocationExpressionSyntax) As Boolean Dim parent As VisualBasicSyntaxNode = node.Parent ' Dig through conditional access If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ConditionalAccessExpression Then Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax) If conditional.WhenNotNull Is node Then parent = conditional.Parent End If End If Return parent IsNot Nothing AndAlso (parent.Kind = SyntaxKind.CallStatement OrElse parent.Kind = SyntaxKind.ExpressionStatement) End Function End Class End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Parser/ParserFeature.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 Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Enum Feature AutoProperties LineContinuation StatementLambdas CoContraVariance CollectionInitializers SubLambdas ArrayLiterals AsyncExpressions Iterators GlobalNamespace NullPropagatingOperator NameOfExpressions InterpolatedStrings ReadonlyAutoProperties RegionsEverywhere MultilineStringLiterals CObjInAttributeArguments LineContinuationComments TypeOfIsNot YearFirstDateLiterals WarningDirectives PartialModules PartialInterfaces ImplementingReadonlyOrWriteonlyPropertyWithReadwrite DigitSeparators BinaryLiterals Tuples InferredTupleNames LeadingDigitSeparator NonTrailingNamedArguments PrivateProtected UnconstrainedTypeParameterInConditional CommentsAfterLineContinuation InitOnlySettersUsage CallerArgumentExpression End Enum Friend Module FeatureExtensions <Extension> Friend Function GetFeatureFlag(feature As Feature) As String Select Case feature Case Feature.CallerArgumentExpression Return NameOf(Feature.CallerArgumentExpression) Case Else Return Nothing End Select End Function <Extension> Friend Function GetLanguageVersion(feature As Feature) As LanguageVersion Select Case feature Case Feature.AutoProperties, Feature.LineContinuation, Feature.StatementLambdas, Feature.CoContraVariance, Feature.CollectionInitializers, Feature.SubLambdas, Feature.ArrayLiterals Return LanguageVersion.VisualBasic10 Case Feature.AsyncExpressions, Feature.Iterators, Feature.GlobalNamespace Return LanguageVersion.VisualBasic11 Case Feature.NullPropagatingOperator, Feature.NameOfExpressions, Feature.InterpolatedStrings, Feature.ReadonlyAutoProperties, Feature.RegionsEverywhere, Feature.MultilineStringLiterals, Feature.CObjInAttributeArguments, Feature.LineContinuationComments, Feature.TypeOfIsNot, Feature.YearFirstDateLiterals, Feature.WarningDirectives, Feature.PartialModules, Feature.PartialInterfaces, Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return LanguageVersion.VisualBasic14 Case Feature.Tuples, Feature.BinaryLiterals, Feature.DigitSeparators Return LanguageVersion.VisualBasic15 Case Feature.InferredTupleNames Return LanguageVersion.VisualBasic15_3 Case Feature.LeadingDigitSeparator, Feature.NonTrailingNamedArguments, Feature.PrivateProtected Return LanguageVersion.VisualBasic15_5 Case Feature.UnconstrainedTypeParameterInConditional, Feature.CommentsAfterLineContinuation Return LanguageVersion.VisualBasic16 Case Feature.InitOnlySettersUsage Return LanguageVersion.VisualBasic16_9 Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select End Function <Extension> Friend Function GetResourceId(feature As Feature) As ERRID Select Case feature Case Feature.AutoProperties Return ERRID.FEATURE_AutoProperties Case Feature.ReadonlyAutoProperties Return ERRID.FEATURE_ReadonlyAutoProperties Case Feature.LineContinuation Return ERRID.FEATURE_LineContinuation Case Feature.StatementLambdas Return ERRID.FEATURE_StatementLambdas Case Feature.CoContraVariance Return ERRID.FEATURE_CoContraVariance Case Feature.CollectionInitializers Return ERRID.FEATURE_CollectionInitializers Case Feature.SubLambdas Return ERRID.FEATURE_SubLambdas Case Feature.ArrayLiterals Return ERRID.FEATURE_ArrayLiterals Case Feature.AsyncExpressions Return ERRID.FEATURE_AsyncExpressions Case Feature.Iterators Return ERRID.FEATURE_Iterators Case Feature.GlobalNamespace Return ERRID.FEATURE_GlobalNamespace Case Feature.NullPropagatingOperator Return ERRID.FEATURE_NullPropagatingOperator Case Feature.NameOfExpressions Return ERRID.FEATURE_NameOfExpressions Case Feature.RegionsEverywhere Return ERRID.FEATURE_RegionsEverywhere Case Feature.MultilineStringLiterals Return ERRID.FEATURE_MultilineStringLiterals Case Feature.CObjInAttributeArguments Return ERRID.FEATURE_CObjInAttributeArguments Case Feature.LineContinuationComments Return ERRID.FEATURE_LineContinuationComments Case Feature.TypeOfIsNot Return ERRID.FEATURE_TypeOfIsNot Case Feature.YearFirstDateLiterals Return ERRID.FEATURE_YearFirstDateLiterals Case Feature.WarningDirectives Return ERRID.FEATURE_WarningDirectives Case Feature.PartialModules Return ERRID.FEATURE_PartialModules Case Feature.PartialInterfaces Return ERRID.FEATURE_PartialInterfaces Case Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return ERRID.FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Case Feature.DigitSeparators Return ERRID.FEATURE_DigitSeparators Case Feature.BinaryLiterals Return ERRID.FEATURE_BinaryLiterals Case Feature.Tuples Return ERRID.FEATURE_Tuples Case Feature.LeadingDigitSeparator Return ERRID.FEATURE_LeadingDigitSeparator Case Feature.PrivateProtected Return ERRID.FEATURE_PrivateProtected Case Feature.InterpolatedStrings Return ERRID.FEATURE_InterpolatedStrings Case Feature.UnconstrainedTypeParameterInConditional Return ERRID.FEATURE_UnconstrainedTypeParameterInConditional Case Feature.CommentsAfterLineContinuation Return ERRID.FEATURE_CommentsAfterLineContinuation Case Feature.InitOnlySettersUsage Return ERRID.FEATURE_InitOnlySettersUsage Case Feature.CallerArgumentExpression Return ERRID.FEATURE_CallerArgumentExpression Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Enum Feature AutoProperties LineContinuation StatementLambdas CoContraVariance CollectionInitializers SubLambdas ArrayLiterals AsyncExpressions Iterators GlobalNamespace NullPropagatingOperator NameOfExpressions InterpolatedStrings ReadonlyAutoProperties RegionsEverywhere MultilineStringLiterals CObjInAttributeArguments LineContinuationComments TypeOfIsNot YearFirstDateLiterals WarningDirectives PartialModules PartialInterfaces ImplementingReadonlyOrWriteonlyPropertyWithReadwrite DigitSeparators BinaryLiterals Tuples InferredTupleNames LeadingDigitSeparator NonTrailingNamedArguments PrivateProtected UnconstrainedTypeParameterInConditional CommentsAfterLineContinuation InitOnlySettersUsage End Enum Friend Module FeatureExtensions <Extension> Friend Function GetFeatureFlag(feature As Feature) As String Select Case feature Case Else Return Nothing End Select End Function <Extension> Friend Function GetLanguageVersion(feature As Feature) As LanguageVersion Select Case feature Case Feature.AutoProperties, Feature.LineContinuation, Feature.StatementLambdas, Feature.CoContraVariance, Feature.CollectionInitializers, Feature.SubLambdas, Feature.ArrayLiterals Return LanguageVersion.VisualBasic10 Case Feature.AsyncExpressions, Feature.Iterators, Feature.GlobalNamespace Return LanguageVersion.VisualBasic11 Case Feature.NullPropagatingOperator, Feature.NameOfExpressions, Feature.InterpolatedStrings, Feature.ReadonlyAutoProperties, Feature.RegionsEverywhere, Feature.MultilineStringLiterals, Feature.CObjInAttributeArguments, Feature.LineContinuationComments, Feature.TypeOfIsNot, Feature.YearFirstDateLiterals, Feature.WarningDirectives, Feature.PartialModules, Feature.PartialInterfaces, Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return LanguageVersion.VisualBasic14 Case Feature.Tuples, Feature.BinaryLiterals, Feature.DigitSeparators Return LanguageVersion.VisualBasic15 Case Feature.InferredTupleNames Return LanguageVersion.VisualBasic15_3 Case Feature.LeadingDigitSeparator, Feature.NonTrailingNamedArguments, Feature.PrivateProtected Return LanguageVersion.VisualBasic15_5 Case Feature.UnconstrainedTypeParameterInConditional, Feature.CommentsAfterLineContinuation Return LanguageVersion.VisualBasic16 Case Feature.InitOnlySettersUsage Return LanguageVersion.VisualBasic16_9 Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select End Function <Extension> Friend Function GetResourceId(feature As Feature) As ERRID Select Case feature Case Feature.AutoProperties Return ERRID.FEATURE_AutoProperties Case Feature.ReadonlyAutoProperties Return ERRID.FEATURE_ReadonlyAutoProperties Case Feature.LineContinuation Return ERRID.FEATURE_LineContinuation Case Feature.StatementLambdas Return ERRID.FEATURE_StatementLambdas Case Feature.CoContraVariance Return ERRID.FEATURE_CoContraVariance Case Feature.CollectionInitializers Return ERRID.FEATURE_CollectionInitializers Case Feature.SubLambdas Return ERRID.FEATURE_SubLambdas Case Feature.ArrayLiterals Return ERRID.FEATURE_ArrayLiterals Case Feature.AsyncExpressions Return ERRID.FEATURE_AsyncExpressions Case Feature.Iterators Return ERRID.FEATURE_Iterators Case Feature.GlobalNamespace Return ERRID.FEATURE_GlobalNamespace Case Feature.NullPropagatingOperator Return ERRID.FEATURE_NullPropagatingOperator Case Feature.NameOfExpressions Return ERRID.FEATURE_NameOfExpressions Case Feature.RegionsEverywhere Return ERRID.FEATURE_RegionsEverywhere Case Feature.MultilineStringLiterals Return ERRID.FEATURE_MultilineStringLiterals Case Feature.CObjInAttributeArguments Return ERRID.FEATURE_CObjInAttributeArguments Case Feature.LineContinuationComments Return ERRID.FEATURE_LineContinuationComments Case Feature.TypeOfIsNot Return ERRID.FEATURE_TypeOfIsNot Case Feature.YearFirstDateLiterals Return ERRID.FEATURE_YearFirstDateLiterals Case Feature.WarningDirectives Return ERRID.FEATURE_WarningDirectives Case Feature.PartialModules Return ERRID.FEATURE_PartialModules Case Feature.PartialInterfaces Return ERRID.FEATURE_PartialInterfaces Case Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Return ERRID.FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite Case Feature.DigitSeparators Return ERRID.FEATURE_DigitSeparators Case Feature.BinaryLiterals Return ERRID.FEATURE_BinaryLiterals Case Feature.Tuples Return ERRID.FEATURE_Tuples Case Feature.LeadingDigitSeparator Return ERRID.FEATURE_LeadingDigitSeparator Case Feature.PrivateProtected Return ERRID.FEATURE_PrivateProtected Case Feature.InterpolatedStrings Return ERRID.FEATURE_InterpolatedStrings Case Feature.UnconstrainedTypeParameterInConditional Return ERRID.FEATURE_UnconstrainedTypeParameterInConditional Case Feature.CommentsAfterLineContinuation Return ERRID.FEATURE_CommentsAfterLineContinuation Case Feature.InitOnlySettersUsage Return ERRID.FEATURE_InitOnlySettersUsage Case Else Throw ExceptionUtilities.UnexpectedValue(feature) End Select End Function End Module End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter symbol defined in source. ''' </summary> Friend Class SourceComplexParameterSymbol Inherits SourceParameterSymbol Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _flags As SourceParameterFlags ' m_lazyDefaultValue is not readonly because it is lazily computed Private _lazyDefaultValue As ConstantValue Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) #If DEBUG Then Friend Sub AssertAttributesNotValidatedYet() Debug.Assert(_lazyCustomAttributesBag Is Nothing) End Sub #End If ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for partial method parameters: ''' Implementation parameter always copies its attributes from the corresponding definition parameter. ''' Definition is always complex parameter and so it stores the attribute bag. ''' </remarks> Private ReadOnly Property BoundAttributesSource As SourceParameterSymbol Get Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return Nothing End If Dim impl = sourceMethod.SourcePartialDefinition If impl Is Nothing Then Return Nothing End If Return DirectCast(impl.Parameters(Me.Ordinal), SourceParameterSymbol) End Get End Property Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return If(Me._syntaxRef Is Nothing, Nothing, DirectCast(Me._syntaxRef.GetSyntax, ParameterSyntax).AttributeLists()) End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Dim attributes = AttributeDeclarationList Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return OneOrMany.Create(attributes) End If Dim otherAttributes As SyntaxList(Of AttributeListSyntax) ' combine attributes with the corresponding parameter of a partial implementation: Dim otherPart As SourceMemberMethodSymbol = sourceMethod.SourcePartialImplementation If otherPart IsNot Nothing Then otherAttributes = DirectCast(otherPart.Parameters(Me.Ordinal), SourceParameterSymbol).AttributeDeclarationList Else otherAttributes = Nothing End If If attributes.Equals(Nothing) Then Return OneOrMany.Create(otherAttributes) ElseIf otherAttributes.Equals(Nothing) Then Return OneOrMany.Create(attributes) Else Return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)) End If End Function Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then Dim copyFrom As SourceParameterSymbol = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(_lazyCustomAttributesBag, attributesBag, Nothing) Else Dim attributeSyntax = Me.GetAttributeDeclarations() LoadAndValidateAttributes(attributeSyntax, _lazyCustomAttributesBag) End If End If Return _lazyCustomAttributesBag End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, ParameterEarlyWellKnownAttributeData) End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonParameterWellKnownAttributeData) End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty) IsNot Nothing End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get If _lazyDefaultValue Is ConstantValue.Unset Then Dim diagnostics = BindingDiagnosticBag.GetInstance() If Interlocked.CompareExchange(_lazyDefaultValue, BindDefaultValue(inProgress, diagnostics), ConstantValue.Unset) Is ConstantValue.Unset Then DirectCast(ContainingModule, SourceModuleSymbol).AddDeclarationDiagnostics(diagnostics) End If diagnostics.Free() End If Return _lazyDefaultValue End Get End Property Private Function BindDefaultValue(inProgress As SymbolsInProgress(Of ParameterSymbol), diagnostics As BindingDiagnosticBag) As ConstantValue Dim parameterSyntax = SyntaxNode If parameterSyntax Is Nothing Then Return Nothing End If Dim defaultSyntax = parameterSyntax.[Default] If defaultSyntax Is Nothing Then Return Nothing End If Dim binder As Binder = BinderBuilder.CreateBinderForParameterDefaultValue(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, Me, parameterSyntax) ' Before binding the default value, check if we are already in the process of binding it. If so report ' an error and return nothing. If inProgress.Contains(Me) Then Binder.ReportDiagnostic(diagnostics, defaultSyntax.Value, ERRID.ERR_CircularEvaluation1, Me) Return Nothing End If Dim inProgressBinder = New DefaultParametersInProgressBinder(inProgress.Add(Me), binder) Dim constValue As ConstantValue = Nothing inProgressBinder.BindParameterDefaultValue(Me.Type, defaultSyntax, diagnostics, constValue:=constValue) If constValue IsNot Nothing Then VerifyParamDefaultValueMatchesAttributeIfAny(constValue, defaultSyntax.Value, diagnostics) End If Return constValue End Function Friend ReadOnly Property SyntaxNode As ParameterSyntax Get Return If(_syntaxRef Is Nothing, Nothing, DirectCast(_syntaxRef.GetSyntax(), ParameterSyntax)) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty ElseIf _syntaxRef IsNot Nothing Then Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) Else Return MyBase.DeclaringSyntaxReferences End If End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.SyntaxNode, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property IsOptional As Boolean Get Return (_flags And SourceParameterFlags.Optional) <> 0 End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get If (_flags And SourceParameterFlags.ParamArray) <> 0 Then Return True End If Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get If Not _syntaxRef.SyntaxTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then ' Silently require feature flag for this feature until Aleksey approves. Return -1 End If Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property ''' <summary> ''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for ''' String parameters of Declare methods. ''' </summary> Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return (_flags And SourceParameterFlags.ByRef) <> 0 End Get End Property Private Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue ) MyBase.New(container, name, ordinal, type, location) _flags = flags _lazyDefaultValue = defaultValueOpt _syntaxRef = syntaxRef End Sub ' Create a simple or complex parameter, as necessary. Friend Shared Function Create(container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue) As ParameterSymbol ' Note that parameters of partial method declarations should always be complex Dim method = TryCast(container, SourceMethodSymbol) If flags <> 0 OrElse defaultValueOpt IsNot Nothing OrElse syntaxRef IsNot Nothing OrElse (method IsNot Nothing AndAlso method.IsPartial) Then Return New SourceComplexParameterSymbol(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Else Return New SourceSimpleParameterSymbol(container, name, ordinal, type, location) End If End Function Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol ' When changing the owner, it is not safe to get the constant value from this parameter symbol (Me.DefaultConstantValue). Default values for source ' parameters are computed after all members have been added to the type. See GenerateAllDeclarationErrors in SourceNamedTypeSymbol. ' Asking for the default value earlier than that can lead to infinite recursion. Instead, pass in the m_lazyDefaultValue. If the value hasn't ' been computed yet, the new symbol will compute it. Return New SourceComplexParameterSymbol(newContainingSymbol, Me.Name, Me.Ordinal, Me.Type, Me.Locations(0), _syntaxRef, _flags, _lazyDefaultValue) End Function ' Create a parameter from syntax. Friend Shared Function CreateFromSyntax(container As Symbol, syntax As ParameterSyntax, name As String, flags As SourceParameterFlags, ordinal As Integer, binder As Binder, checkModifier As CheckParameterModifierDelegate, diagnostics As BindingDiagnosticBag) As ParameterSymbol Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitArgs ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl End If Dim paramType = binder.DecodeModifiedIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, getErrorInfo, diagnostics, ModifiedIdentifierTypeDecoderContext.ParameterType) If (flags And SourceParameterFlags.ParamArray) <> 0 AndAlso paramType.TypeKind <> TypeKind.Error Then If paramType.TypeKind <> TypeKind.Array Then ' ParamArray must be of array type. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_ParamArrayNotArray) Else Dim paramTypeAsArray = DirectCast(paramType, ArrayTypeSymbol) If Not paramTypeAsArray.IsSZArray Then ' ParamArray type must be rank-1 array. Binder.ReportDiagnostic(diagnostics, syntax.Identifier.Identifier, ERRID.ERR_ParamArrayRank) End If ' 'touch' the constructor in order to generate proper diagnostics binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, syntax, diagnostics) End If End If Dim syntaxRef As SyntaxReference = Nothing ' Attributes and default values are computed lazily and need access to the parameter's syntax. ' If the parameter syntax includes either of these get a syntax reference and pass it to the parameter symbol. If (syntax.AttributeLists.Count <> 0 OrElse syntax.Default IsNot Nothing) Then syntaxRef = binder.GetSyntaxReference(syntax) End If Dim defaultValue As ConstantValue = Nothing If (flags And SourceParameterFlags.Optional) <> 0 Then ' The default value is computed lazily. If there is default syntax then set the value to ConstantValue.unset to indicate the value needs to ' be computed. If syntax.Default IsNot Nothing Then defaultValue = ConstantValue.Unset End If ' Report diagnostic if constructors for datetime and decimal default values are not available Select Case paramType.SpecialType Case SpecialType.System_DateTime binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, syntax.Default, diagnostics) Case SpecialType.System_Decimal binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, syntax.Default, diagnostics) End Select End If Return Create(container, name, ordinal, paramType, syntax.Identifier.Identifier.GetLocation(), syntaxRef, flags, defaultValue) End Function Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceComplexParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue) End If Return New SourceComplexParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue, customModifiers, refCustomModifiers) End Function Private Class SourceComplexParameterSymbolWithCustomModifiers Inherits SourceComplexParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol 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 System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter symbol defined in source. ''' </summary> Friend Class SourceComplexParameterSymbol Inherits SourceParameterSymbol Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _flags As SourceParameterFlags ' m_lazyDefaultValue is not readonly because it is lazily computed Private _lazyDefaultValue As ConstantValue Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) #If DEBUG Then Friend Sub AssertAttributesNotValidatedYet() Debug.Assert(_lazyCustomAttributesBag Is Nothing) End Sub #End If ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for partial method parameters: ''' Implementation parameter always copies its attributes from the corresponding definition parameter. ''' Definition is always complex parameter and so it stores the attribute bag. ''' </remarks> Private ReadOnly Property BoundAttributesSource As SourceParameterSymbol Get Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return Nothing End If Dim impl = sourceMethod.SourcePartialDefinition If impl Is Nothing Then Return Nothing End If Return DirectCast(impl.Parameters(Me.Ordinal), SourceParameterSymbol) End Get End Property Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return If(Me._syntaxRef Is Nothing, Nothing, DirectCast(Me._syntaxRef.GetSyntax, ParameterSyntax).AttributeLists()) End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Dim attributes = AttributeDeclarationList Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return OneOrMany.Create(attributes) End If Dim otherAttributes As SyntaxList(Of AttributeListSyntax) ' combine attributes with the corresponding parameter of a partial implementation: Dim otherPart As SourceMemberMethodSymbol = sourceMethod.SourcePartialImplementation If otherPart IsNot Nothing Then otherAttributes = DirectCast(otherPart.Parameters(Me.Ordinal), SourceParameterSymbol).AttributeDeclarationList Else otherAttributes = Nothing End If If attributes.Equals(Nothing) Then Return OneOrMany.Create(otherAttributes) ElseIf otherAttributes.Equals(Nothing) Then Return OneOrMany.Create(attributes) Else Return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)) End If End Function Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then Dim copyFrom As SourceParameterSymbol = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(_lazyCustomAttributesBag, attributesBag, Nothing) Else Dim attributeSyntax = Me.GetAttributeDeclarations() LoadAndValidateAttributes(attributeSyntax, _lazyCustomAttributesBag) End If End If Return _lazyCustomAttributesBag End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, ParameterEarlyWellKnownAttributeData) End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonParameterWellKnownAttributeData) End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty) IsNot Nothing End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get If _lazyDefaultValue Is ConstantValue.Unset Then Dim diagnostics = BindingDiagnosticBag.GetInstance() If Interlocked.CompareExchange(_lazyDefaultValue, BindDefaultValue(inProgress, diagnostics), ConstantValue.Unset) Is ConstantValue.Unset Then DirectCast(ContainingModule, SourceModuleSymbol).AddDeclarationDiagnostics(diagnostics) End If diagnostics.Free() End If Return _lazyDefaultValue End Get End Property Private Function BindDefaultValue(inProgress As SymbolsInProgress(Of ParameterSymbol), diagnostics As BindingDiagnosticBag) As ConstantValue Dim parameterSyntax = SyntaxNode If parameterSyntax Is Nothing Then Return Nothing End If Dim defaultSyntax = parameterSyntax.[Default] If defaultSyntax Is Nothing Then Return Nothing End If Dim binder As Binder = BinderBuilder.CreateBinderForParameterDefaultValue(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, Me, parameterSyntax) ' Before binding the default value, check if we are already in the process of binding it. If so report ' an error and return nothing. If inProgress.Contains(Me) Then Binder.ReportDiagnostic(diagnostics, defaultSyntax.Value, ERRID.ERR_CircularEvaluation1, Me) Return Nothing End If Dim inProgressBinder = New DefaultParametersInProgressBinder(inProgress.Add(Me), binder) Dim constValue As ConstantValue = Nothing inProgressBinder.BindParameterDefaultValue(Me.Type, defaultSyntax, diagnostics, constValue:=constValue) If constValue IsNot Nothing Then VerifyParamDefaultValueMatchesAttributeIfAny(constValue, defaultSyntax.Value, diagnostics) End If Return constValue End Function Friend ReadOnly Property SyntaxNode As ParameterSyntax Get Return If(_syntaxRef Is Nothing, Nothing, DirectCast(_syntaxRef.GetSyntax(), ParameterSyntax)) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty ElseIf _syntaxRef IsNot Nothing Then Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) Else Return MyBase.DeclaringSyntaxReferences End If End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.SyntaxNode, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property IsOptional As Boolean Get Return (_flags And SourceParameterFlags.Optional) <> 0 End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get If (_flags And SourceParameterFlags.ParamArray) <> 0 Then Return True End If Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property ''' <summary> ''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for ''' String parameters of Declare methods. ''' </summary> Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return (_flags And SourceParameterFlags.ByRef) <> 0 End Get End Property Private Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue ) MyBase.New(container, name, ordinal, type, location) _flags = flags _lazyDefaultValue = defaultValueOpt _syntaxRef = syntaxRef End Sub ' Create a simple or complex parameter, as necessary. Friend Shared Function Create(container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue) As ParameterSymbol ' Note that parameters of partial method declarations should always be complex Dim method = TryCast(container, SourceMethodSymbol) If flags <> 0 OrElse defaultValueOpt IsNot Nothing OrElse syntaxRef IsNot Nothing OrElse (method IsNot Nothing AndAlso method.IsPartial) Then Return New SourceComplexParameterSymbol(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Else Return New SourceSimpleParameterSymbol(container, name, ordinal, type, location) End If End Function Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol ' When changing the owner, it is not safe to get the constant value from this parameter symbol (Me.DefaultConstantValue). Default values for source ' parameters are computed after all members have been added to the type. See GenerateAllDeclarationErrors in SourceNamedTypeSymbol. ' Asking for the default value earlier than that can lead to infinite recursion. Instead, pass in the m_lazyDefaultValue. If the value hasn't ' been computed yet, the new symbol will compute it. Return New SourceComplexParameterSymbol(newContainingSymbol, Me.Name, Me.Ordinal, Me.Type, Me.Locations(0), _syntaxRef, _flags, _lazyDefaultValue) End Function ' Create a parameter from syntax. Friend Shared Function CreateFromSyntax(container As Symbol, syntax As ParameterSyntax, name As String, flags As SourceParameterFlags, ordinal As Integer, binder As Binder, checkModifier As CheckParameterModifierDelegate, diagnostics As BindingDiagnosticBag) As ParameterSymbol Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitArgs ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl End If Dim paramType = binder.DecodeModifiedIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, getErrorInfo, diagnostics, ModifiedIdentifierTypeDecoderContext.ParameterType) If (flags And SourceParameterFlags.ParamArray) <> 0 AndAlso paramType.TypeKind <> TypeKind.Error Then If paramType.TypeKind <> TypeKind.Array Then ' ParamArray must be of array type. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_ParamArrayNotArray) Else Dim paramTypeAsArray = DirectCast(paramType, ArrayTypeSymbol) If Not paramTypeAsArray.IsSZArray Then ' ParamArray type must be rank-1 array. Binder.ReportDiagnostic(diagnostics, syntax.Identifier.Identifier, ERRID.ERR_ParamArrayRank) End If ' 'touch' the constructor in order to generate proper diagnostics binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, syntax, diagnostics) End If End If Dim syntaxRef As SyntaxReference = Nothing ' Attributes and default values are computed lazily and need access to the parameter's syntax. ' If the parameter syntax includes either of these get a syntax reference and pass it to the parameter symbol. If (syntax.AttributeLists.Count <> 0 OrElse syntax.Default IsNot Nothing) Then syntaxRef = binder.GetSyntaxReference(syntax) End If Dim defaultValue As ConstantValue = Nothing If (flags And SourceParameterFlags.Optional) <> 0 Then ' The default value is computed lazily. If there is default syntax then set the value to ConstantValue.unset to indicate the value needs to ' be computed. If syntax.Default IsNot Nothing Then defaultValue = ConstantValue.Unset End If ' Report diagnostic if constructors for datetime and decimal default values are not available Select Case paramType.SpecialType Case SpecialType.System_DateTime binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, syntax.Default, diagnostics) Case SpecialType.System_Decimal binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, syntax.Default, diagnostics) End Select End If Return Create(container, name, ordinal, paramType, syntax.Identifier.Identifier.GetLocation(), syntaxRef, flags, defaultValue) End Function Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceComplexParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue) End If Return New SourceComplexParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue, customModifiers, refCustomModifiers) End Function Private Class SourceComplexParameterSymbolWithCustomModifiers Inherits SourceComplexParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceParameterSymbol.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.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend MustInherit Class SourceParameterSymbol Inherits SourceParameterSymbolBase Implements IAttributeTargetSymbol Private ReadOnly _location As Location Private ReadOnly _name As String Private ReadOnly _type As TypeSymbol Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location) MyBase.New(container, ordinal) _name = name _type = type _location = location End Sub Friend ReadOnly Property Location As Location Get Return _location End Get End Property Public NotOverridable Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend NotOverridable Overrides ReadOnly Property HasOptionCompare As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get ' Ideally we should look for IDispatchConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get ' Ideally we should look for IUnknownConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Public NotOverridable Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get If _location IsNot Nothing Then Return ImmutableArray.Create(Of Location)(_location) Else Return ImmutableArray(Of Location).Empty End If End Get End Property Public NotOverridable Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property Public MustOverride Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Public MustOverride Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty Else Return GetDeclaringSyntaxReferenceHelper(Of ParameterSyntax)(Me.Locations) End If End Get End Property Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get If Me.ContainingSymbol.IsImplicitlyDeclared Then If If(TryCast(Me.ContainingSymbol, MethodSymbol)?.MethodKind = MethodKind.DelegateInvoke, False) AndAlso Not Me.ContainingType.AssociatedSymbol?.IsImplicitlyDeclared Then Return False End If Return True End If Return (GetMatchingPropertyParameter() IsNot Nothing) End Get End Property ''' <summary> ''' Is this an accessor parameter that came from the associated property? If so, ''' return it, else return Nothing. ''' </summary> Private Function GetMatchingPropertyParameter() As ParameterSymbol Dim containingMethod = TryCast(ContainingSymbol, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.IsAccessor() Then Dim containingProperty = TryCast(containingMethod.AssociatedSymbol, PropertySymbol) If containingProperty IsNot Nothing AndAlso Ordinal < containingProperty.ParameterCount Then ' We match a parameter on our containing property. Return containingProperty.Parameters(Ordinal) End If End If Return Nothing End Function #Region "Attributes" ' Attributes on corresponding parameters of partial methods are merged. ' We always create a complex parameter for a partial definition to store potential merged attributes there. ' At the creation time we don't know if the corresponding partial implementation has attributes so we need to always assume it might. ' ' Unlike in C#, where both partial definition and partial implementation have partial syntax and ' hence we create a complex parameter for both of them, in VB partial implementation Sub syntax ' is no different from non-partial Sub. Therefore we can't determine at the creation time whether ' a parameter of a Sub that is not a partial definition might need to store attributes or not. ' ' We therefore need to virtualize the storage for attribute data. Simple parameter of a partial implementation ' uses attribute storage of the corresponding partial definition parameter. ' ' When an implementation parameter is asked for attributes it gets them from the definition parameter: ' 1) If the implementation is a simple parameter it calls GetAttributeBag on the definition. ' 2) If it is a complex parameter it copies the data from the definition using BoundAttributesSource. Friend MustOverride Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Friend MustOverride Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Friend MustOverride Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Friend MustOverride ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Friend NotOverridable Overrides ReadOnly Property HasParamArrayAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDefaultValueAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.DefaultParameterValue <> ConstantValue.Unset End Get End Property Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Parameter End Get End Property ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData ' Declare methods need to know early what marshalling type are their parameters of to determine ByRef-ness. Dim containingSymbol = Me.ContainingSymbol If containingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(containingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.MarshalAsAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasMarshalAsAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Dim possibleValidParamArrayTarget As Boolean = False Select Case containingSymbol.Kind Case SymbolKind.Property possibleValidParamArrayTarget = True Case SymbolKind.Method Select Case DirectCast(containingSymbol, MethodSymbol).MethodKind Case MethodKind.Conversion, MethodKind.UserDefinedOperator, MethodKind.EventAdd, MethodKind.EventRemove Debug.Assert(Not possibleValidParamArrayTarget) Case Else possibleValidParamArrayTarget = True End Select End Select If possibleValidParamArrayTarget AndAlso VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ParamArrayAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasParamArrayAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerLineNumberAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerFilePathAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerMemberNameAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute) AndAlso Location.SourceTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then Dim index = -1 Dim attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, False) If Not attribute.HasErrors Then Dim parameterName As String = Nothing If attribute.ConstructorArguments.Single().TryDecodeValue(SpecialType.System_String, parameterName) Then Dim parameters = containingSymbol.GetParameters() For i = 0 To parameters.Length - 1 If IdentifierComparison.Equals(parameters(i).Name, parameterName) Then index = i Exit For End If Next End If End If arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).CallerArgumentExpressionParameterIndex = index End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Dim attributes = MyBase.GetCustomAttributesToEmit(compilationState) If Location Is Nothing OrElse Not Location.IsInSource OrElse Not Location.SourceTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then ' Silently require feature flag for this feature until Aleksey approves. For Each attribute In attributes Yield attribute Next Return End If For Each attribute In attributes If AttributeData.IsTargetEarlyAttribute(attributeType:=attribute.AttributeClass, attributeArgCount:=attribute.CommonConstructorArguments.Length, description:=AttributeDescription.CallerArgumentExpressionAttribute) Then Dim callerArgumentExpressionParameterIndex = Me.CallerArgumentExpressionParameterIndex If callerArgumentExpressionParameterIndex <> -1 AndAlso TypeOf attribute Is SourceAttributeData Then Debug.Assert(callerArgumentExpressionParameterIndex >= 0) Debug.Assert(attribute.CommonConstructorArguments.Length = 1) ' We allow CallerArgumentExpression to have case-insensitive parameter name, but we ' want to emit the parameter name with correct casing, so that it works with C#. Dim correctedParameterName = ContainingSymbol.GetParameters()(callerArgumentExpressionParameterIndex).Name Dim oldTypedConstant = attribute.CommonConstructorArguments.Single() If correctedParameterName.Equals(oldTypedConstant.Value.ToString(), StringComparison.Ordinal) Then Yield attribute Continue For End If Dim newArgs = ImmutableArray.Create(New TypedConstant(oldTypedConstant.TypeInternal, oldTypedConstant.Kind, correctedParameterName)) Yield New SourceAttributeData(attribute.ApplicationSyntaxReference, attribute.AttributeClass, attribute.AttributeConstructor, newArgs, attribute.CommonNamedArguments, attribute.IsConditionallyOmitted, attribute.HasErrors) Continue For End If End If Yield attribute Next End Function ' It is not strictly necessary to decode default value attributes early in VB, ' but it is necessary in C#, so this keeps the implementations consistent. Private Function EarlyDecodeAttributeForDefaultParameterValue(description As AttributeDescription, ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) OrElse description.Equals(AttributeDescription.DecimalConstantAttribute) OrElse description.Equals(AttributeDescription.DateTimeConstantAttribute)) Dim hasAnyDiagnostics = False Dim attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) Dim value As ConstantValue If attribute.HasErrors Then value = ConstantValue.Bad hasAnyDiagnostics = True Else value = DecodeDefaultParameterValueAttribute(description, attribute) End If Dim paramData = arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData)() If paramData.DefaultParameterValue = ConstantValue.Unset Then paramData.DefaultParameterValue = value End If Return If(hasAnyDiagnostics, Nothing, attribute) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) Debug.Assert(TypeOf arguments.Diagnostics Is BindingDiagnosticBag) ' Differences from C#: ' ' DefaultParameterValueAttribute ' - emitted as is, not treated as pseudo-custom attribute ' - checked (along with DecimalConstantAttribute and DateTimeConstantAttribute) for consistency with any explicit default value ' ' OptionalAttribute ' - Not used by the language, only syntactically optional parameters or metadata optional parameters are recognized by overload resolution. ' OptionalAttribute is checked for in emit phase. ' ' ParamArrayAttribute ' - emitted as is, no error reported ' - Dev11 incorrectly emits the attribute twice ' ' InAttribute, OutAttribute ' - metadata flag set, no diagnostics reported, don't influence language semantics If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultParameterValueAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DecimalConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DateTimeConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasInAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.OutAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasOutAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) Then MarshalAsAttributeDecoder(Of CommonParameterWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation).Decode(arguments, AttributeTargets.Parameter, MessageProvider.Instance) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.CallerArgumentExpressionAttribute) AndAlso Location.SourceTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then Dim index = GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex If index = Ordinal Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_CallerArgumentExpressionAttributeSelfReferential, arguments.AttributeSyntaxOpt.Location, Me.Name) ElseIf index = -1 Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName, arguments.AttributeSyntaxOpt.Location, Me.Name) End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Private Sub DecodeDefaultParameterValueAttribute(description As AttributeDescription, ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attribute = arguments.Attribute Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Debug.Assert(diagnostics IsNot Nothing) Dim value = DecodeDefaultParameterValueAttribute(description, attribute) If Not value.IsBad Then VerifyParamDefaultValueMatchesAttributeIfAny(value, arguments.AttributeSyntaxOpt, diagnostics) End If End Sub ''' <summary> ''' Verify the default value matches the default value from any earlier attribute ''' (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). ''' If not, report ERR_ParamDefaultValueDiffersFromAttribute. ''' </summary> Protected Sub VerifyParamDefaultValueMatchesAttributeIfAny(value As ConstantValue, syntax As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) Dim data = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing Then Dim attrValue = data.DefaultParameterValue If attrValue <> ConstantValue.Unset AndAlso value <> attrValue Then Binder.ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ParamDefaultValueDiffersFromAttribute) End If End If End Sub Private Function DecodeDefaultParameterValueAttribute(description As AttributeDescription, attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(Not attribute.HasErrors) If description.Equals(AttributeDescription.DefaultParameterValueAttribute) Then Return DecodeDefaultParameterValueAttribute(attribute) ElseIf description.Equals(AttributeDescription.DecimalConstantAttribute) Then Return attribute.DecodeDecimalConstantValue() Else Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute)) Return attribute.DecodeDateTimeConstantValue() End If End Function Private Function DecodeDefaultParameterValueAttribute(attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(attribute.CommonConstructorArguments.Length = 1) ' the type of the value is the type of the expression in the attribute Dim arg = attribute.CommonConstructorArguments(0) Dim specialType = If(arg.Kind = TypedConstantKind.Enum, DirectCast(arg.TypeInternal, NamedTypeSymbol).EnumUnderlyingType.SpecialType, arg.TypeInternal.SpecialType) Dim constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType) If constantValueDiscriminator = ConstantValueTypeDiscriminator.Bad Then If arg.Kind <> TypedConstantKind.Array AndAlso arg.ValueInternal Is Nothing AndAlso Type.IsReferenceType Then Return ConstantValue.Null End If Return ConstantValue.Bad End If Return ConstantValue.Create(arg.ValueInternal, constantValueDiscriminator) End Function Friend NotOverridable Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing Then Return data.MarshallingInformation End If ' Default marshalling for string parameters of Declare methods (ByRef or ByVal) If Type.IsStringType() Then Dim container As Symbol = ContainingSymbol If container.Kind = SymbolKind.Method Then Dim methodSymbol = DirectCast(container, MethodSymbol) If methodSymbol.MethodKind = MethodKind.DeclareMethod Then Dim info As New MarshalPseudoCustomAttributeData() Debug.Assert(IsByRef) If IsExplicitByRef Then Dim pinvoke As DllImportData = methodSymbol.GetDllImportData() Select Case pinvoke.CharacterSet Case Cci.Constants.CharSet_None, CharSet.Ansi info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_AnsiBStr) Case Cci.Constants.CharSet_Auto info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_TBStr) Case CharSet.Unicode info.SetMarshalAsSimpleType(UnmanagedType.BStr) Case Else Throw ExceptionUtilities.UnexpectedValue(pinvoke.CharacterSet) End Select Else info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_VBByRefStr) End If Return info End If End If End If Return Nothing End Get End Property Public NotOverridable Overrides ReadOnly Property IsByRef As Boolean Get If IsExplicitByRef Then Return True End If ' String parameters of Declare methods without explicit MarshalAs attribute are always ByRef, even if they are declared ByVal. If Type.IsStringType() AndAlso ContainingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(ContainingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then Dim data = GetEarlyDecodedWellKnownAttributeData() Return data Is Nothing OrElse Not data.HasMarshalAsAttribute End If Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataOut As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasOutAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataIn As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasInAttribute End Get End Property #End Region End Class Friend Enum SourceParameterFlags As Byte [ByVal] = 1 << 0 [ByRef] = 1 << 1 [Optional] = 1 << 2 [ParamArray] = 1 << 3 End Enum 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.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend MustInherit Class SourceParameterSymbol Inherits SourceParameterSymbolBase Implements IAttributeTargetSymbol Private ReadOnly _location As Location Private ReadOnly _name As String Private ReadOnly _type As TypeSymbol Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location) MyBase.New(container, ordinal) _name = name _type = type _location = location End Sub Friend ReadOnly Property Location As Location Get Return _location End Get End Property Public NotOverridable Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend NotOverridable Overrides ReadOnly Property HasOptionCompare As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get ' Ideally we should look for IDispatchConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get ' Ideally we should look for IUnknownConstantAttribute on this source parameter symbol, ' but the native VB compiler respects this attribute only on metadata parameter symbols, we do the same. ' See Devdiv bug #10789 (Handle special processing of object type without a default value per VB Language Spec 11.8.2 Applicable Methods) for details. Return False End Get End Property Public NotOverridable Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get If _location IsNot Nothing Then Return ImmutableArray.Create(Of Location)(_location) Else Return ImmutableArray(Of Location).Empty End If End Get End Property Public NotOverridable Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property Public MustOverride Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Public MustOverride Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty Else Return GetDeclaringSyntaxReferenceHelper(Of ParameterSyntax)(Me.Locations) End If End Get End Property Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get If Me.ContainingSymbol.IsImplicitlyDeclared Then If If(TryCast(Me.ContainingSymbol, MethodSymbol)?.MethodKind = MethodKind.DelegateInvoke, False) AndAlso Not Me.ContainingType.AssociatedSymbol?.IsImplicitlyDeclared Then Return False End If Return True End If Return (GetMatchingPropertyParameter() IsNot Nothing) End Get End Property ''' <summary> ''' Is this an accessor parameter that came from the associated property? If so, ''' return it, else return Nothing. ''' </summary> Private Function GetMatchingPropertyParameter() As ParameterSymbol Dim containingMethod = TryCast(ContainingSymbol, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.IsAccessor() Then Dim containingProperty = TryCast(containingMethod.AssociatedSymbol, PropertySymbol) If containingProperty IsNot Nothing AndAlso Ordinal < containingProperty.ParameterCount Then ' We match a parameter on our containing property. Return containingProperty.Parameters(Ordinal) End If End If Return Nothing End Function #Region "Attributes" ' Attributes on corresponding parameters of partial methods are merged. ' We always create a complex parameter for a partial definition to store potential merged attributes there. ' At the creation time we don't know if the corresponding partial implementation has attributes so we need to always assume it might. ' ' Unlike in C#, where both partial definition and partial implementation have partial syntax and ' hence we create a complex parameter for both of them, in VB partial implementation Sub syntax ' is no different from non-partial Sub. Therefore we can't determine at the creation time whether ' a parameter of a Sub that is not a partial definition might need to store attributes or not. ' ' We therefore need to virtualize the storage for attribute data. Simple parameter of a partial implementation ' uses attribute storage of the corresponding partial definition parameter. ' ' When an implementation parameter is asked for attributes it gets them from the definition parameter: ' 1) If the implementation is a simple parameter it calls GetAttributeBag on the definition. ' 2) If it is a complex parameter it copies the data from the definition using BoundAttributesSource. Friend MustOverride Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Friend MustOverride Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Friend MustOverride Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Friend MustOverride ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Friend NotOverridable Overrides ReadOnly Property HasParamArrayAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDefaultValueAttribute As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.DefaultParameterValue <> ConstantValue.Unset End Get End Property Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Parameter End Get End Property ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData ' Declare methods need to know early what marshalling type are their parameters of to determine ByRef-ness. Dim containingSymbol = Me.ContainingSymbol If containingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(containingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.MarshalAsAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasMarshalAsAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Dim possibleValidParamArrayTarget As Boolean = False Select Case containingSymbol.Kind Case SymbolKind.Property possibleValidParamArrayTarget = True Case SymbolKind.Method Select Case DirectCast(containingSymbol, MethodSymbol).MethodKind Case MethodKind.Conversion, MethodKind.UserDefinedOperator, MethodKind.EventAdd, MethodKind.EventRemove Debug.Assert(Not possibleValidParamArrayTarget) Case Else possibleValidParamArrayTarget = True End Select End Select If possibleValidParamArrayTarget AndAlso VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ParamArrayAttribute) Then Dim hasAnyDiagnostics As Boolean = False Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasParamArrayAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute) Then Return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerLineNumberAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerFilePathAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute) Then arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).HasCallerMemberNameAttribute = True ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute) Then Dim index = -1 Dim attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, False) If Not attribute.HasErrors Then Dim parameterName As String = Nothing If attribute.ConstructorArguments.Single().TryDecodeValue(SpecialType.System_String, parameterName) Then Dim parameters = containingSymbol.GetParameters() For i = 0 To parameters.Length - 1 If IdentifierComparison.Equals(parameters(i).Name, parameterName) Then index = i Exit For End If Next End If End If arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData).CallerArgumentExpressionParameterIndex = index End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) Dim attributes = MyBase.GetCustomAttributesToEmit(compilationState) For Each attribute In attributes If AttributeData.IsTargetEarlyAttribute(attributeType:=attribute.AttributeClass, attributeArgCount:=attribute.CommonConstructorArguments.Length, description:=AttributeDescription.CallerArgumentExpressionAttribute) Then Dim callerArgumentExpressionParameterIndex = Me.CallerArgumentExpressionParameterIndex If callerArgumentExpressionParameterIndex <> -1 AndAlso TypeOf attribute Is SourceAttributeData Then Debug.Assert(callerArgumentExpressionParameterIndex >= 0) Debug.Assert(attribute.CommonConstructorArguments.Length = 1) ' We allow CallerArgumentExpression to have case-insensitive parameter name, but we ' want to emit the parameter name with correct casing, so that it works with C#. Dim correctedParameterName = ContainingSymbol.GetParameters()(callerArgumentExpressionParameterIndex).Name Dim oldTypedConstant = attribute.CommonConstructorArguments.Single() If correctedParameterName.Equals(oldTypedConstant.Value.ToString(), StringComparison.Ordinal) Then Yield attribute Continue For End If Dim newArgs = ImmutableArray.Create(New TypedConstant(oldTypedConstant.TypeInternal, oldTypedConstant.Kind, correctedParameterName)) Yield New SourceAttributeData(attribute.ApplicationSyntaxReference, attribute.AttributeClass, attribute.AttributeConstructor, newArgs, attribute.CommonNamedArguments, attribute.IsConditionallyOmitted, attribute.HasErrors) Continue For End If End If Yield attribute Next End Function ' It is not strictly necessary to decode default value attributes early in VB, ' but it is necessary in C#, so this keeps the implementations consistent. Private Function EarlyDecodeAttributeForDefaultParameterValue(description As AttributeDescription, ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) OrElse description.Equals(AttributeDescription.DecimalConstantAttribute) OrElse description.Equals(AttributeDescription.DateTimeConstantAttribute)) Dim hasAnyDiagnostics = False Dim attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) Dim value As ConstantValue If attribute.HasErrors Then value = ConstantValue.Bad hasAnyDiagnostics = True Else value = DecodeDefaultParameterValueAttribute(description, attribute) End If Dim paramData = arguments.GetOrCreateData(Of ParameterEarlyWellKnownAttributeData)() If paramData.DefaultParameterValue = ConstantValue.Unset Then paramData.DefaultParameterValue = value End If Return If(hasAnyDiagnostics, Nothing, attribute) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) Debug.Assert(TypeOf arguments.Diagnostics Is BindingDiagnosticBag) ' Differences from C#: ' ' DefaultParameterValueAttribute ' - emitted as is, not treated as pseudo-custom attribute ' - checked (along with DecimalConstantAttribute and DateTimeConstantAttribute) for consistency with any explicit default value ' ' OptionalAttribute ' - Not used by the language, only syntactically optional parameters or metadata optional parameters are recognized by overload resolution. ' OptionalAttribute is checked for in emit phase. ' ' ParamArrayAttribute ' - emitted as is, no error reported ' - Dev11 incorrectly emits the attribute twice ' ' InAttribute, OutAttribute ' - metadata flag set, no diagnostics reported, don't influence language semantics If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultParameterValueAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DecimalConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DateTimeConstantAttribute) Then ' Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute. DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasInAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.OutAttribute) Then arguments.GetOrCreateData(Of CommonParameterWellKnownAttributeData)().HasOutAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) Then MarshalAsAttributeDecoder(Of CommonParameterWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation).Decode(arguments, AttributeTargets.Parameter, MessageProvider.Instance) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.CallerArgumentExpressionAttribute) Then Dim index = GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex If index = Ordinal Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_CallerArgumentExpressionAttributeSelfReferential, arguments.AttributeSyntaxOpt.Location, Me.Name) ElseIf index = -1 Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_CallerArgumentExpressionAttributeHasInvalidParameterName, arguments.AttributeSyntaxOpt.Location, Me.Name) End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Private Sub DecodeDefaultParameterValueAttribute(description As AttributeDescription, ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attribute = arguments.Attribute Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Debug.Assert(diagnostics IsNot Nothing) Dim value = DecodeDefaultParameterValueAttribute(description, attribute) If Not value.IsBad Then VerifyParamDefaultValueMatchesAttributeIfAny(value, arguments.AttributeSyntaxOpt, diagnostics) End If End Sub ''' <summary> ''' Verify the default value matches the default value from any earlier attribute ''' (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute). ''' If not, report ERR_ParamDefaultValueDiffersFromAttribute. ''' </summary> Protected Sub VerifyParamDefaultValueMatchesAttributeIfAny(value As ConstantValue, syntax As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) Dim data = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing Then Dim attrValue = data.DefaultParameterValue If attrValue <> ConstantValue.Unset AndAlso value <> attrValue Then Binder.ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ParamDefaultValueDiffersFromAttribute) End If End If End Sub Private Function DecodeDefaultParameterValueAttribute(description As AttributeDescription, attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(Not attribute.HasErrors) If description.Equals(AttributeDescription.DefaultParameterValueAttribute) Then Return DecodeDefaultParameterValueAttribute(attribute) ElseIf description.Equals(AttributeDescription.DecimalConstantAttribute) Then Return attribute.DecodeDecimalConstantValue() Else Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute)) Return attribute.DecodeDateTimeConstantValue() End If End Function Private Function DecodeDefaultParameterValueAttribute(attribute As VisualBasicAttributeData) As ConstantValue Debug.Assert(attribute.CommonConstructorArguments.Length = 1) ' the type of the value is the type of the expression in the attribute Dim arg = attribute.CommonConstructorArguments(0) Dim specialType = If(arg.Kind = TypedConstantKind.Enum, DirectCast(arg.TypeInternal, NamedTypeSymbol).EnumUnderlyingType.SpecialType, arg.TypeInternal.SpecialType) Dim constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType) If constantValueDiscriminator = ConstantValueTypeDiscriminator.Bad Then If arg.Kind <> TypedConstantKind.Array AndAlso arg.ValueInternal Is Nothing AndAlso Type.IsReferenceType Then Return ConstantValue.Null End If Return ConstantValue.Bad End If Return ConstantValue.Create(arg.ValueInternal, constantValueDiscriminator) End Function Friend NotOverridable Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing Then Return data.MarshallingInformation End If ' Default marshalling for string parameters of Declare methods (ByRef or ByVal) If Type.IsStringType() Then Dim container As Symbol = ContainingSymbol If container.Kind = SymbolKind.Method Then Dim methodSymbol = DirectCast(container, MethodSymbol) If methodSymbol.MethodKind = MethodKind.DeclareMethod Then Dim info As New MarshalPseudoCustomAttributeData() Debug.Assert(IsByRef) If IsExplicitByRef Then Dim pinvoke As DllImportData = methodSymbol.GetDllImportData() Select Case pinvoke.CharacterSet Case Cci.Constants.CharSet_None, CharSet.Ansi info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_AnsiBStr) Case Cci.Constants.CharSet_Auto info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_TBStr) Case CharSet.Unicode info.SetMarshalAsSimpleType(UnmanagedType.BStr) Case Else Throw ExceptionUtilities.UnexpectedValue(pinvoke.CharacterSet) End Select Else info.SetMarshalAsSimpleType(Cci.Constants.UnmanagedType_VBByRefStr) End If Return info End If End If End If Return Nothing End Get End Property Public NotOverridable Overrides ReadOnly Property IsByRef As Boolean Get If IsExplicitByRef Then Return True End If ' String parameters of Declare methods without explicit MarshalAs attribute are always ByRef, even if they are declared ByVal. If Type.IsStringType() AndAlso ContainingSymbol.Kind = SymbolKind.Method AndAlso DirectCast(ContainingSymbol, MethodSymbol).MethodKind = MethodKind.DeclareMethod Then Dim data = GetEarlyDecodedWellKnownAttributeData() Return data Is Nothing OrElse Not data.HasMarshalAsAttribute End If Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataOut As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasOutAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMetadataIn As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasInAttribute End Get End Property #End Region End Class Friend Enum SourceParameterFlags As Byte [ByVal] = 1 << 0 [ByRef] = 1 << 1 [Optional] = 1 << 2 [ParamArray] = 1 << 3 End Enum End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceSimpleParameterSymbol.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 System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameters declared in source, that is not optional, does not have a default value, ''' attributes, or is a ParamArray. This is a separate class to save memory, since there are LOTS ''' of parameters. ''' </summary> Friend Class SourceSimpleParameterSymbol Inherits SourceParameterSymbol Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location) MyBase.New(container, name, ordinal, type, location) End Sub Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol Return New SourceSimpleParameterSymbol(newContainingSymbol, Name, Ordinal, Type, Location) End Function Private Function GetCorrespondingPartialParameter() As SourceComplexParameterSymbol ' the attributes for partial method implementation are stored on the corresponding definition: Dim method = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If method IsNot Nothing AndAlso method.IsPartialImplementation Then ' partial definition always has complex parameters: Return DirectCast(method.SourcePartialDefinition.Parameters(Me.Ordinal), SourceComplexParameterSymbol) End If Return Nothing End Function Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return Nothing End Get End Property Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetAttributesBag() End If Return CustomAttributesBag(Of VisualBasicAttributeData).Empty End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetEarlyDecodedWellKnownAttributeData() End If Return Nothing End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetDecodedWellKnownAttributeData() End If Return Nothing End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get If Not Location.SourceTree.Options.Features.ContainsKey(InternalSyntax.GetFeatureFlag(InternalSyntax.Feature.CallerArgumentExpression)) Then ' Silently require feature flag for this feature until Aleksey approves. Return -1 End If Dim data = GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get ' SourceSimpleParameterSymbol is never created for a parameter with ByRef modifier. Return False End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceSimpleParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location) End If Return New SourceSimpleParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, customModifiers, refCustomModifiers) End Function Friend NotInheritable Class SourceSimpleParameterSymbolWithCustomModifiers Inherits SourceSimpleParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol 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 System.Collections.Generic Imports System.Collections.ObjectModel Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameters declared in source, that is not optional, does not have a default value, ''' attributes, or is a ParamArray. This is a separate class to save memory, since there are LOTS ''' of parameters. ''' </summary> Friend Class SourceSimpleParameterSymbol Inherits SourceParameterSymbol Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location) MyBase.New(container, name, ordinal, type, location) End Sub Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol Return New SourceSimpleParameterSymbol(newContainingSymbol, Name, Ordinal, Type, Location) End Function Private Function GetCorrespondingPartialParameter() As SourceComplexParameterSymbol ' the attributes for partial method implementation are stored on the corresponding definition: Dim method = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If method IsNot Nothing AndAlso method.IsPartialImplementation Then ' partial definition always has complex parameters: Return DirectCast(method.SourcePartialDefinition.Parameters(Me.Ordinal), SourceComplexParameterSymbol) End If Return Nothing End Function Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return Nothing End Get End Property Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetAttributesBag() End If Return CustomAttributesBag(Of VisualBasicAttributeData).Empty End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetEarlyDecodedWellKnownAttributeData() End If Return Nothing End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData ' the attributes for partial method implementation are stored on the corresponding definition: Dim other = GetCorrespondingPartialParameter() If other IsNot Nothing Then Return other.GetDecodedWellKnownAttributeData() End If Return Nothing End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim data = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Dim data = GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get ' SourceSimpleParameterSymbol is never created for a parameter with ByRef modifier. Return False End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceSimpleParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location) End If Return New SourceSimpleParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, customModifiers, refCustomModifiers) End Function Friend NotInheritable Class SourceSimpleParameterSymbolWithCustomModifiers Inherits SourceSimpleParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Friend Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_CallerArgumentExpression.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 Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_CallerArgumentExpression Inherits BasicTestBase #Region "CallerArgumentExpression - Invocations" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_OldVersionWithFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1), CallerArgumentExpression(p2)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="456").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes_IncorrectCtor() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String, extraParam As Integer) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1, 0), CallerArgumentExpression(p2, 1)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Public Module Program2 Sub Main() Log(123) End Sub Private Const P As String = NameOf(P) Public Sub Log(p As Integer, <CallerArgumentExpression(P)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics().VerifyTypeIL("Program2", " .class public auto ansi sealed Program2 extends [System.Runtime]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private static literal string P = ""P"" // Methods .method public static void Main () cil managed { .custom instance void [System.Runtime]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2050 // Code size 13 (0xd) .maxstack 8 .entrypoint IL_0000: ldc.i4.s 123 IL_0002: ldstr ""123"" IL_0007: call void Program2::Log(int32, string) IL_000c: ret } // end of method Program2::Main .method public static void Log ( int32 p, [opt] string arg ) cil managed { .param [2] = ""<default-arg>"" .custom instance void [System.Runtime]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x205e // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.1 IL_0001: call void [System.Console]System.Console::WriteLine(string) IL_0006: ret } // end of method Program2::Log } // end of class Program2 ") Dim csCompilation = CreateCSharpCompilation("Program2.Log(5 + 2);", referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.NetCoreApp, {compilation.EmitToImageReference()}), compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(csCompilation, expectedOutput:="5 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity_Metadata() Dim il = " .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public static void M ( int32 i, [opt] string s ) cil managed { .param [2] = ""default"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 49 00 00 // I ) // Method begins at RVA 0x2058 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.1 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M(0 + 1) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="0 + 1").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Version16_9_WithoutFeatureFlag() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(' comment _ 123 + _ 5 ' comment ) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 + _ 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_SwapArguments() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(q:=123, p:=124) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine($""{p}, {q}, {arg}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="124, 123, 124").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Module FromFirstAssembly Private Const p As String = NameOf(p) Public Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular16_9) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Module Program Public Sub Main() FromFirstAssembly.Log(2 + 2, 3 + 1) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_ThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M() End Sub Private Const p As String = NameOf(p) <Extension> Public Sub M(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_NotThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const q As String = NameOf(q) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(q)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression * 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionAttribute_ExtensionMethod_IncorrectParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const qq As String = NameOf(qq) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log() End Sub Private Const pp As String = NameOf(pp) Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.Regular16_9), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes3() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes4() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithOverride() Dim source = " Imports System Imports System.Runtime.CompilerServices MustInherit Class Base Const p As String = NameOf(p) Public MustOverride Sub Log_RemoveAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Public MustOverride Sub Log_AddAttributeInOverride(p As Integer, Optional arg As String = ""default"") End Class Class Derived : Inherits Base Const p As String = NameOf(p) Public Overrides Sub Log_AddAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Console.WriteLine(arg) End Sub Public Overrides Sub Log_RemoveAttributeInOverride(p As Integer, Optional arg As String = ""default"") Console.WriteLine(arg) End Sub End Class Class Program Public Shared Sub Main() Dim derived = New Derived() derived.Log_AddAttributeInOverride(5 + 4) derived.Log_RemoveAttributeInOverride(5 + 5) DirectCast(derived, Base).Log_AddAttributeInOverride(5 + 4) DirectCast(derived, Base).Log_RemoveAttributeInOverride(5 + 5) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="5 + 4 default default 5 + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithUserDefinedConversionFromString() Dim source = " Imports System Imports System.Runtime.CompilerServices Class C Public Sub New(s As String) Prop = s End Sub Public ReadOnly Property Prop As String Public Shared Widening Operator CType(s As String) As C Return New C(s) End Operator End Class Class Program Public Shared Sub Main() Log(0) End Sub Const p As String = NameOf(p) Shared Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As C = Nothing) Console.WriteLine(arg Is Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithMultipleOptionalAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) Log(0, target:=callerTargetExp) Log(0, notTarget:=""Not target value"") Log(0, notTarget:=""Not target value"", target:=callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", Optional notTarget As String = ""not target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp caller target value callerTargetExp target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithDifferentParametersReferringToEachOther() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""param1_value"") M(param1:=""param1_value"") M(param2:=""param2_value"") M(param1:=""param1_value"", param2:=""param2_value"") M(param2:=""param2_value"", param1:=""param1_value"") End Sub Sub M(<CallerArgumentExpression(""param2"")> Optional param1 As String = ""param1_default"", <CallerArgumentExpression(""param1"")> Optional param2 As String = ""param2_default"") Console.WriteLine($""param1: {param1}, param2: {param2}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="param1: param1_default, param2: param2_default param1: param1_value, param2: ""param1_value"" param1: param1_value, param2: ""param1_value"" param1: ""param2_value"", param2: param2_value param1: param1_value, param2: param2_value param1: param1_value, param2: param2_value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsCallerMember() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() End Sub Sub M(<CallerMemberName> Optional callerName As String = ""<default-caller-name>"", <CallerArgumentExpression(""callerName"")> Optional argumentExp As String = ""<default-arg-expression>"") Console.WriteLine(callerName) Console.WriteLine(argumentExp) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="Main <default-arg-expression>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""value"") End Sub Sub M(<CallerArgumentExpression(""p"")> Optional p As String = ""<default>"") Console.WriteLine(p) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub M(<CallerArgumentExpression("p")> Optional p As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential_Metadata() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi abstract sealed beforefieldinit C extends [mscorlib]System.Object { // Methods .method public hidebysig static void M ( [opt] string p ) cil managed { .param [1] = ""<default>"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x2050 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C" Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M() C.M("value") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default> value").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Attributes" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123 _ ' comment + 5 ' comment )> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="123 _ ' comment + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly_AttributeConstructor() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Imports System.Reflection <My(2 + 2, 3 + 1)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(<CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub New(<CallerArgumentExpression(p)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const target As String = NameOf(target) Sub New(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Class <My(0)> <My(0, ""caller target value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value ""caller target value""").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsReferringToItself_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const p As String = NameOf(p) Sub New(<CallerArgumentExpression(p)> Optional p As String = ""default"") Console.WriteLine(p) End Sub End Class <My> <My(""value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="default value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub New(<CallerArgumentExpression(p)> Optional p As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionInAttributeConstructor_OptionalAndFieldInitializer() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const a As String = NameOf(a) Sub New(<CallerArgumentExpression(a)> Optional expr_a As String = ""<default0>"", Optional a As String = ""<default1>"") Console.WriteLine($""'{a}', '{expr_a}'"") End Sub Public I1 As Integer Public I2 As Integer Public I3 As Integer End Class <My(I1:=0, I2:=1, I3:=2)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="'<default1>', '<default0>'").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Test various symbols" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIndexers() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Const i As String = NameOf(i) Default Public Property Item(i As Integer, <CallerArgumentExpression(i)> Optional s As String = ""<default-arg>"") As Integer Get Return i End Get Set(value As Integer) Console.WriteLine($""{i}, {s}"") End Set End Property Public Shared Sub Main() Dim p As New Program() p(1+ 1) = 5 p(2+ 2, ""explicit-value"") = 5 End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="2, 1+ 1 4, explicit-value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> ByRef s2 as String) Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation).VerifyDiagnostics().VerifyIL("Program.Main", " { // Code size 27 (0x1b) .maxstack 3 .locals init (String V_0) IL_0000: ldnull IL_0001: ldftn ""Sub Program.MImpl(String, ByRef String)"" IL_0007: newobj ""Sub Program.M..ctor(Object, System.IntPtr)"" IL_000c: ldstr """" IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: ldnull IL_0015: callvirt ""Sub Program.M.EndInvoke(ByRef String, System.IAsyncResult)"" IL_001a: ret } ") End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional ByRef s2 as String = """") Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC33010: 'Delegate' parameters cannot be declared 'Optional'. Delegate Sub M(s1 As String, <CallerArgumentExpression("s1")> Optional ByRef s2 as String = "") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub ComClass() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic Namespace System.Runtime.InteropServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Interface] Or AttributeTargets.[Class] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited:=False)> Public NotInheritable Class GuidAttribute Inherits Attribute Public Sub New(guid As String) Value = guid End Sub Public ReadOnly Property Value As String End Class <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class], Inherited:=False)> Public NotInheritable Class ClassInterfaceAttribute Inherits Attribute Public Sub New(classInterfaceType As ClassInterfaceType) Value = classInterfaceType End Sub Public Sub New(classInterfaceType As Short) Value = CType(classInterfaceType, ClassInterfaceType) End Sub Public ReadOnly Property Value As ClassInterfaceType End Class <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Field Or AttributeTargets.[Property] Or AttributeTargets.[Event], Inherited:=False)> Public NotInheritable Class DispIdAttribute Inherits Attribute Public Sub New(dispId As Integer) Value = dispId End Sub Public ReadOnly Property Value As Integer End Class Public Enum ClassInterfaceType None = 0 AutoDispatch = 1 AutoDual = 2 End Enum End Namespace <ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 ' Use the Region directive to define a section named COM Guids. #Region ""COM GUIDs"" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. You can generate ' these guids using guidgen.exe Public Const ClassId As String = ""7666AC25-855F-4534-BC55-27BF09D49D46"" Public Const InterfaceId As String = ""54388137-8A76-491e-AA3A-853E23AC1217"" Public Const EventsId As String = ""EA329A13-16A0-478d-B41F-47583A761FF2"" #End Region Public Sub New() MyBase.New() End Sub Public Sub M(x As Integer, <CallerArgumentExpression(""x"")> Optional y As String = ""<default>"") Console.WriteLine(y) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) comp1.VerifyDiagnostics() Dim source2 = " Module Program Sub Main() Dim x As ComClass1._ComClass1 = New ComClass1() x.M(1 + 2) End Sub End Module " Dim comp2 = CreateCompilation(source2, references:={comp1.EmitToImageReference()}, TestOptions.ReleaseExe, TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(comp2, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub Tuple() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public Interface ITuple ReadOnly Property Length As Integer Default ReadOnly Property Item(index As Integer) As Object End Interface End Namespace Namespace System Public Structure ValueTuple(Of T1, T2) : Implements ITuple Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) item1 = item1 item2 = item2 End Sub Default Public ReadOnly Property Item(index As Integer) As Object Implements ITuple.Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Length As Integer Implements ITuple.Length Get Throw New NotImplementedException() End Get End Property Public Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional s2 As String = ""<default>"") Console.WriteLine(s2) End Sub End Structure End Namespace Module Program Sub Main() Dim x = New ValueTuple(Of Integer, Integer)(0, 0) x.M(1 + 2) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestOperator() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public specialname static class C op_Addition ( class C left, [opt] int32 right ) cil managed { .param [2] = int32(0) .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 04 6c 65 66 74 00 00 ) // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class C ) 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 C::op_Addition } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() Dim obj As New C() obj = obj + 0 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter3() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter4() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter5() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("x")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter6() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest.WithFeature("CallerArgumentExpression")) CompileAndVerify(compilation, expectedOutput:="New value").VerifyDiagnostics() 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 Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_CallerArgumentExpression Inherits BasicTestBase #Region "CallerArgumentExpression - Invocations" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_OldVersion() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(123) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1), CallerArgumentExpression(p2)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="456").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_MultipleAttributes_IncorrectCtor() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=True, Inherited:=False)> Public NotInheritable Class CallerArgumentExpressionAttribute Inherits Attribute Public Sub New(parameterName As String, extraParam As Integer) ParameterName = parameterName End Sub Public ReadOnly Property ParameterName As String End Class End Namespace Class Program Public Shared Sub Main() Log(123, 456) End Sub Const p1 As String = NameOf(p1) Const p2 As String = NameOf(p2) Private Shared Sub Log(p1 As Integer, p2 As Integer, <CallerArgumentExpression(p1, 0), CallerArgumentExpression(p2, 1)> ByVal Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="<default-arg>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Public Module Program2 Sub Main() Log(123) End Sub Private Const P As String = NameOf(P) Public Sub Log(p As Integer, <CallerArgumentExpression(P)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics().VerifyTypeIL("Program2", " .class public auto ansi sealed Program2 extends [System.Runtime]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field private static literal string P = ""P"" // Methods .method public static void Main () cil managed { .custom instance void [System.Runtime]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2050 // Code size 13 (0xd) .maxstack 8 .entrypoint IL_0000: ldc.i4.s 123 IL_0002: ldstr ""123"" IL_0007: call void Program2::Log(int32, string) IL_000c: ret } // end of method Program2::Main .method public static void Log ( int32 p, [opt] string arg ) cil managed { .param [2] = ""<default-arg>"" .custom instance void [System.Runtime]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x205e // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.1 IL_0001: call void [System.Console]System.Console::WriteLine(string) IL_0006: ret } // end of method Program2::Log } // end of class Program2 ") Dim csCompilation = CreateCSharpCompilation("Program2.Log(5 + 2);", referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.NetCoreApp, {compilation.EmitToImageReference()}), compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(csCompilation, expectedOutput:="5 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_CaseInsensitivity_Metadata() Dim il = " .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public static void M ( int32 i, [opt] string s ) cil managed { .param [2] = ""default"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 49 00 00 // I ) // Method begins at RVA 0x2058 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.1 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M(0 + 1) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="0 + 1").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(' comment _ 123 + _ 5 ' comment ) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="123 + _ 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_SwapArguments() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(q:=123, p:=124) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine($""{p}, {q}, {arg}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="124, 123, 124").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Module FromFirstAssembly Private Const p As String = NameOf(p) Public Sub Log(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular16_9) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Module Program Public Sub Main() FromFirstAssembly.Log(2 + 2, 3 + 1) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_ThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M() End Sub Private Const p As String = NameOf(p) <Extension> Public Sub M(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExtensionMethod_NotThisParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const q As String = NameOf(q) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(q)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="myIntegerExpression * 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionAttribute_ExtensionMethod_IncorrectParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim myIntegerExpression As Integer = 5 myIntegerExpression.M(myIntegerExpression * 2) End Sub Private Const qq As String = NameOf(qq) <Extension> Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Public Sub M(p As Integer, q As Integer, <CallerArgumentExpression(qq)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log() End Sub Private Const pp As String = NameOf(pp) Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="<default>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub Log(<CallerArgumentExpression(pp)> Optional arg As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithMemberNameAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerMemberName> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="Main").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.Regular16_9), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithFilePathAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerFilePath> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(Parse(source, "C:\\Program.cs", options:=TestOptions.RegularLatest), targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="C:\\Program.cs").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As String = ""<default>"") Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes3() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithLineNumberAttributes4() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> <CallerLineNumber> Optional arg As Integer = 0) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="6").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentNonOptionalParameter2() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Log(0+ 0) End Sub Private Const p As String = NameOf(p) Sub Log(p As Integer, <CallerArgumentExpression(p)> arg As String) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.Regular16_9) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC30455: Argument not specified for parameter 'arg' of 'Public Sub Log(p As Integer, arg As String)'. Log(0+ 0) ~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithOverride() Dim source = " Imports System Imports System.Runtime.CompilerServices MustInherit Class Base Const p As String = NameOf(p) Public MustOverride Sub Log_RemoveAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Public MustOverride Sub Log_AddAttributeInOverride(p As Integer, Optional arg As String = ""default"") End Class Class Derived : Inherits Base Const p As String = NameOf(p) Public Overrides Sub Log_AddAttributeInOverride(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""default"") Console.WriteLine(arg) End Sub Public Overrides Sub Log_RemoveAttributeInOverride(p As Integer, Optional arg As String = ""default"") Console.WriteLine(arg) End Sub End Class Class Program Public Shared Sub Main() Dim derived = New Derived() derived.Log_AddAttributeInOverride(5 + 4) derived.Log_RemoveAttributeInOverride(5 + 5) DirectCast(derived, Base).Log_AddAttributeInOverride(5 + 4) DirectCast(derived, Base).Log_RemoveAttributeInOverride(5 + 5) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="5 + 4 default default 5 + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentWithUserDefinedConversionFromString() Dim source = " Imports System Imports System.Runtime.CompilerServices Class C Public Sub New(s As String) Prop = s End Sub Public ReadOnly Property Prop As String Public Shared Widening Operator CType(s As String) As C Return New C(s) End Operator End Class Class Program Public Shared Sub Main() Log(0) End Sub Const p As String = NameOf(p) Shared Sub Log(p As Integer, <CallerArgumentExpression(p)> Optional arg As C = Nothing) Console.WriteLine(arg Is Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithMultipleOptionalAttribute() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() Dim callerTargetExp = ""caller target value"" Log(0) Log(0, callerTargetExp) Log(0, target:=callerTargetExp) Log(0, notTarget:=""Not target value"") Log(0, notTarget:=""Not target value"", target:=callerTargetExp) End Sub Private Const target As String = NameOf(target) Sub Log(p As Integer, Optional target As String = ""target default value"", Optional notTarget As String = ""not target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value callerTargetExp caller target value callerTargetExp target default value arg default value caller target value callerTargetExp").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithDifferentParametersReferringToEachOther() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""param1_value"") M(param1:=""param1_value"") M(param2:=""param2_value"") M(param1:=""param1_value"", param2:=""param2_value"") M(param2:=""param2_value"", param1:=""param1_value"") End Sub Sub M(<CallerArgumentExpression(""param2"")> Optional param1 As String = ""param1_default"", <CallerArgumentExpression(""param1"")> Optional param2 As String = ""param2_default"") Console.WriteLine($""param1: {param1}, param2: {param2}"") End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="param1: param1_default, param2: param2_default param1: param1_value, param2: ""param1_value"" param1: param1_value, param2: ""param1_value"" param1: ""param2_value"", param2: param2_value param1: param1_value, param2: param2_value param1: param1_value, param2: param2_value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsCallerMember() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() End Sub Sub M(<CallerMemberName> Optional callerName As String = ""<default-caller-name>"", <CallerArgumentExpression(""callerName"")> Optional argumentExp As String = ""<default-arg-expression>"") Console.WriteLine(callerName) Console.WriteLine(argumentExp) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="Main <default-arg-expression>").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential() Dim source = " Imports System Imports System.Runtime.CompilerServices Module Program Sub Main() M() M(""value"") End Sub Sub M(<CallerArgumentExpression(""p"")> Optional p As String = ""<default>"") Console.WriteLine(p) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="<default> value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub M(<CallerArgumentExpression("p")> Optional p As String = "<default>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsSelfReferential_Metadata() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi abstract sealed beforefieldinit C extends [mscorlib]System.Object { // Methods .method public hidebysig static void M ( [opt] string p ) cil managed { .param [1] = ""<default>"" .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 01 70 00 00 ) // Method begins at RVA 0x2050 // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call void [mscorlib]System.Console::WriteLine(string) IL_0007: nop IL_0008: ret } // end of method C::M } // end of class C" Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() C.M() C.M("value") End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="<default> value").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Attributes" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="123").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_ExpressionHasTrivia_Attribute() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My(123 _ ' comment + 5 ' comment )> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="123 _ ' comment + 5").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestGoodCallerArgumentExpressionAttribute_DifferentAssembly_AttributeConstructor() Dim source = " Imports System Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(p As Integer, q As Integer, <CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim source2 = " Imports System.Reflection <My(2 + 2, 3 + 1)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source2, references:={ref1, Net451.MicrosoftVisualBasic}, targetFramework:=TargetFramework.NetCoreApp, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="2 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIncorrectParameterNameInCallerArgumentExpressionAttribute_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const p As String = ""p"" Sub New(<CallerArgumentExpression(p)> Optional arg As String = ""<default-arg>"") Console.WriteLine(arg) End Sub End Class <My> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="<default-arg>") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'arg' will have no effect. It is applied with an invalid parameter name. Sub New(<CallerArgumentExpression(p)> Optional arg As String = "<default-arg>") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestCallerArgumentExpressionWithOptionalTargetParameter_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const target As String = NameOf(target) Sub New(p As Integer, Optional target As String = ""target default value"", <CallerArgumentExpression(target)> Optional arg As String = ""arg default value"") Console.WriteLine(target) Console.WriteLine(arg) End Sub End Class <My(0)> <My(0, ""caller target value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="target default value arg default value caller target value ""caller target value""").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionIsReferringToItself_AttributeConstructor() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> Public Class MyAttribute : Inherits Attribute Private Const p As String = NameOf(p) Sub New(<CallerArgumentExpression(p)> Optional p As String = ""default"") Console.WriteLine(p) End Sub End Class <My> <My(""value"")> Public Module Program Sub Main() GetType(Program).GetCustomAttributes(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="default value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'p' will have no effect because it's self-referential. Sub New(<CallerArgumentExpression(p)> Optional p As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestArgumentExpressionInAttributeConstructor_OptionalAndFieldInitializer() Dim source = " Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Public Class MyAttribute : Inherits Attribute Private Const a As String = NameOf(a) Sub New(<CallerArgumentExpression(a)> Optional expr_a As String = ""<default0>"", Optional a As String = ""<default1>"") Console.WriteLine($""'{a}', '{expr_a}'"") End Sub Public I1 As Integer Public I2 As Integer Public I3 As Integer End Class <My(I1:=0, I2:=1, I3:=2)> Public Module Program Sub Main() GetType(Program).GetCustomAttribute(GetType(MyAttribute)) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="'<default1>', '<default0>'").VerifyDiagnostics() End Sub #End Region #Region "CallerArgumentExpression - Test various symbols" <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestIndexers() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Const i As String = NameOf(i) Default Public Property Item(i As Integer, <CallerArgumentExpression(i)> Optional s As String = ""<default-arg>"") As Integer Get Return i End Get Set(value As Integer) Console.WriteLine($""{i}, {s}"") End Set End Property Public Shared Sub Main() Dim p As New Program() p(1+ 1) = 5 p(2+ 2, ""explicit-value"") = 5 End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="2, 1+ 1 4, explicit-value").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> ByRef s2 as String) Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation).VerifyDiagnostics().VerifyIL("Program.Main", " { // Code size 27 (0x1b) .maxstack 3 .locals init (String V_0) IL_0000: ldnull IL_0001: ldftn ""Sub Program.MImpl(String, ByRef String)"" IL_0007: newobj ""Sub Program.M..ctor(Object, System.IntPtr)"" IL_000c: ldstr """" IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: ldnull IL_0015: callvirt ""Sub Program.M.EndInvoke(ByRef String, System.IAsyncResult)"" IL_001a: ret } ") End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestDelegate2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Delegate Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional ByRef s2 as String = """") Shared Sub MImpl(s1 As String, ByRef s2 As String) Console.WriteLine(s1) Console.WriteLine(s2) End Sub Public Shared Sub Main() Dim x As M = AddressOf MImpl x.EndInvoke("""", Nothing) End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC33010: 'Delegate' parameters cannot be declared 'Optional'. Delegate Sub M(s1 As String, <CallerArgumentExpression("s1")> Optional ByRef s2 as String = "") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub ComClass() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic Namespace System.Runtime.InteropServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Interface] Or AttributeTargets.[Class] Or AttributeTargets.[Enum] Or AttributeTargets.Struct Or AttributeTargets.[Delegate], Inherited:=False)> Public NotInheritable Class GuidAttribute Inherits Attribute Public Sub New(guid As String) Value = guid End Sub Public ReadOnly Property Value As String End Class <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class], Inherited:=False)> Public NotInheritable Class ClassInterfaceAttribute Inherits Attribute Public Sub New(classInterfaceType As ClassInterfaceType) Value = classInterfaceType End Sub Public Sub New(classInterfaceType As Short) Value = CType(classInterfaceType, ClassInterfaceType) End Sub Public ReadOnly Property Value As ClassInterfaceType End Class <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Field Or AttributeTargets.[Property] Or AttributeTargets.[Event], Inherited:=False)> Public NotInheritable Class DispIdAttribute Inherits Attribute Public Sub New(dispId As Integer) Value = dispId End Sub Public ReadOnly Property Value As Integer End Class Public Enum ClassInterfaceType None = 0 AutoDispatch = 1 AutoDual = 2 End Enum End Namespace <ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 ' Use the Region directive to define a section named COM Guids. #Region ""COM GUIDs"" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. You can generate ' these guids using guidgen.exe Public Const ClassId As String = ""7666AC25-855F-4534-BC55-27BF09D49D46"" Public Const InterfaceId As String = ""54388137-8A76-491e-AA3A-853E23AC1217"" Public Const EventsId As String = ""EA329A13-16A0-478d-B41F-47583A761FF2"" #End Region Public Sub New() MyBase.New() End Sub Public Sub M(x As Integer, <CallerArgumentExpression(""x"")> Optional y As String = ""<default>"") Console.WriteLine(y) End Sub End Class " Dim comp1 = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.RegularLatest) comp1.VerifyDiagnostics() Dim source2 = " Module Program Sub Main() Dim x As ComClass1._ComClass1 = New ComClass1() x.M(1 + 2) End Sub End Module " Dim comp2 = CreateCompilation(source2, references:={comp1.EmitToImageReference()}, TestOptions.ReleaseExe, TestOptions.RegularLatest) CompileAndVerify(comp2, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub Tuple() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public Interface ITuple ReadOnly Property Length As Integer Default ReadOnly Property Item(index As Integer) As Object End Interface End Namespace Namespace System Public Structure ValueTuple(Of T1, T2) : Implements ITuple Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) item1 = item1 item2 = item2 End Sub Default Public ReadOnly Property Item(index As Integer) As Object Implements ITuple.Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property Length As Integer Implements ITuple.Length Get Throw New NotImplementedException() End Get End Property Public Sub M(s1 As String, <CallerArgumentExpression(""s1"")> Optional s2 As String = ""<default>"") Console.WriteLine(s2) End Sub End Structure End Namespace Module Program Sub Main() Dim x = New ValueTuple(Of Integer, Integer)(0, 0) x.M(1 + 2) End Sub End Module " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="1 + 2").VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestOperator() Dim il = ".class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi C extends [mscorlib]System.Object { // Methods .method public specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor .method public specialname static class C op_Addition ( class C left, [opt] int32 right ) cil managed { .param [2] = int32(0) .custom instance void [mscorlib]System.Runtime.CompilerServices.CallerArgumentExpressionAttribute::.ctor(string) = ( 01 00 04 6c 65 66 74 00 00 ) // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class C ) 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 C::op_Addition } // end of class C " Dim source = <compilation> <file name="c.vb"><![CDATA[ Module Program Sub Main() Dim obj As New C() obj = obj + 0 End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il, options:=TestOptions.ReleaseExe, includeVbRuntime:=True, parseOptions:=TestOptions.RegularLatest) compilation.VerifyDiagnostics() End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter1() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter2() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="New value") compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> value As String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter3() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression("""")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42505: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect. It is applied with an invalid parameter name. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter4() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""value"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC42504: The CallerArgumentExpressionAttribute applied to parameter 'value' will have no effect because it's self-referential. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("value")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter5() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> Optional value As String = ""default"") Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) compilation.AssertTheseDiagnostics( <expected><![CDATA[ BC31065: 'Set' parameter cannot be declared 'Optional'. Set(<CallerArgumentExpression("x")> Optional value As String = "default") ~~~~~~~~ ]]></expected>) End Sub <ConditionalFact(GetType(CoreClrOnly))> Public Sub TestSetter6() Dim source As String = " Imports System Imports System.Runtime.CompilerServices Class Program Public Property P(x As String) As String Get Return ""Return getter"" End Get Set(<CallerArgumentExpression(""x"")> value As String) Console.WriteLine(value) End Set End Property Public Shared Sub Main() Dim prog As New Program() prog.P(""xvalue"") = ""New value"" End Sub End Class " Dim compilation = CreateCompilation(source, targetFramework:=TargetFramework.NetCoreApp, references:={Net451.MicrosoftVisualBasic}, options:=TestOptions.ReleaseExe, parseOptions:=TestOptions.RegularLatest) CompileAndVerify(compilation, expectedOutput:="New value").VerifyDiagnostics() End Sub #End Region End Class End Namespace
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/CommandLine/CommandLineDiagnosticFormatter.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 System.Text Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class CommandLineDiagnosticFormatter Inherits VisualBasicDiagnosticFormatter Private ReadOnly _baseDirectory As String Private ReadOnly _getAdditionalTextFiles As Func(Of ImmutableArray(Of AdditionalTextFile)) Friend Sub New(baseDirectory As String, getAdditionalTextFiles As Func(Of ImmutableArray(Of AdditionalTextFile))) _baseDirectory = baseDirectory _getAdditionalTextFiles = getAdditionalTextFiles End Sub ' Returns a diagnostic message in string. ' VB has a special implementation that prints out a squiggle under the error span as well as a diagnostic message. ' e.g., ' c:\Roslyn\Temp\a.vb(5) : warning BC42024: Unused local variable: 'x'. ' ' Dim x As Integer ' ~ ' Public Overrides Function Format(diagnostic As Diagnostic, Optional formatter As IFormatProvider = Nothing) As String ' Builds a diagnostic message ' Dev12 vbc prints raw paths -- relative and not normalized, so we don't need to customize the base implementation. Dim text As SourceText = Nothing Dim diagnosticSpanOpt = GetDiagnosticSpanAndFileText(diagnostic, text) If Not diagnosticSpanOpt.HasValue OrElse text Is Nothing OrElse text.Length < diagnosticSpanOpt.Value.End Then ' Diagnostic either has Location.None OR an invalid location OR invalid file contents. ' For all these cases, format the diagnostic as a no-location project level diagnostic. ' Strip location, if required. If diagnostic.Location <> Location.None Then diagnostic = diagnostic.WithLocation(Location.None) End If ' Add "vbc : " command line prefix to the start of the command line diagnostics which do not have a location to match the ' behavior of native compiler. This allows MSBuild output to be consistent whether Roslyn is installed or not. Return VisualBasicCompiler.VbcCommandLinePrefix & MyBase.Format(diagnostic, formatter) End If Dim baseMessage = MyBase.Format(diagnostic, formatter) Dim sb As New StringBuilder() sb.AppendLine(baseMessage) ' the squiggles are displayed for the original (unmapped) location Dim sourceSpan = diagnosticSpanOpt.Value Dim sourceSpanStart = sourceSpan.Start Dim sourceSpanEnd = sourceSpan.End Dim linenumber = text.Lines.IndexOf(sourceSpanStart) Dim line = text.Lines(linenumber) If sourceSpan.IsEmpty AndAlso line.Start = sourceSpanEnd AndAlso linenumber > 0 Then ' Sometimes there is something missing at the end of the line, then the error is reported with an empty span ' beyond the end of the line, which makes it appear that the span starts at the beginning of the next line. ' Let's go back to the previous line in this case. linenumber -= 1 line = text.Lines(linenumber) End If While (line.Start < sourceSpanEnd) ' Builds the original text line sb.AppendLine() sb.AppendLine(line.ToString().Replace(vbTab, " ")) ' normalize tabs with 4 spaces ' Builds leading spaces up to the error span For position = Math.Min(sourceSpanStart, line.Start) To Math.Min(line.End, sourceSpanStart) - 1 If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append(" "c, 4) Else sb.Append(" ") End If Next ' Builds squiggles If sourceSpan.IsEmpty Then sb.Append("~") Else For position = Math.Max(sourceSpanStart, line.Start) To Math.Min(If(sourceSpanEnd = sourceSpanStart, sourceSpanEnd, sourceSpanEnd - 1), line.End - 1) If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append("~"c, 4) Else sb.Append("~") End If Next End If ' Builds trailing spaces up to the end of this line For position = Math.Min(sourceSpanEnd, line.End) To line.End - 1 If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append(" "c, 4) Else sb.Append(" ") End If Next ' The error span can continue over multiple lines linenumber = linenumber + 1 If linenumber >= text.Lines.Count Then ' Exit the loop when we reach the end line (0-based) Exit While End If line = text.Lines(linenumber) End While Return sb.ToString() End Function Friend Overrides Function FormatSourcePath(path As String, basePath As String, formatter As IFormatProvider) As String Return If(FileUtilities.NormalizeRelativePath(path, basePath, _baseDirectory), path) End Function Private Function GetDiagnosticSpanAndFileText(diagnostic As Diagnostic, <Out> ByRef text As SourceText) As TextSpan? If diagnostic.Location.IsInSource Then text = diagnostic.Location.SourceTree.GetText() Return diagnostic.Location.SourceSpan End If If diagnostic.Location.Kind = LocationKind.ExternalFile Then Dim path = diagnostic.Location.GetLineSpan().Path If path IsNot Nothing Then For Each additionalTextFile In _getAdditionalTextFiles() If path.Equals(additionalTextFile.Path) Then Try text = additionalTextFile.GetText() Catch text = Nothing End Try Return diagnostic.Location.SourceSpan End If Next End If End If text = Nothing Return Nothing 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 System.Text Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class CommandLineDiagnosticFormatter Inherits VisualBasicDiagnosticFormatter Private ReadOnly _baseDirectory As String Private ReadOnly _getAdditionalTextFiles As Func(Of ImmutableArray(Of AdditionalTextFile)) Friend Sub New(baseDirectory As String, getAdditionalTextFiles As Func(Of ImmutableArray(Of AdditionalTextFile))) _baseDirectory = baseDirectory _getAdditionalTextFiles = getAdditionalTextFiles End Sub ' Returns a diagnostic message in string. ' VB has a special implementation that prints out a squiggle under the error span as well as a diagnostic message. ' e.g., ' c:\Roslyn\Temp\a.vb(5) : warning BC42024: Unused local variable: 'x'. ' ' Dim x As Integer ' ~ ' Public Overrides Function Format(diagnostic As Diagnostic, Optional formatter As IFormatProvider = Nothing) As String ' Builds a diagnostic message ' Dev12 vbc prints raw paths -- relative and not normalized, so we don't need to customize the base implementation. Dim text As SourceText = Nothing Dim diagnosticSpanOpt = GetDiagnosticSpanAndFileText(diagnostic, text) If Not diagnosticSpanOpt.HasValue OrElse text Is Nothing OrElse text.Length < diagnosticSpanOpt.Value.End Then ' Diagnostic either has Location.None OR an invalid location OR invalid file contents. ' For all these cases, format the diagnostic as a no-location project level diagnostic. ' Strip location, if required. If diagnostic.Location <> Location.None Then diagnostic = diagnostic.WithLocation(Location.None) End If ' Add "vbc : " command line prefix to the start of the command line diagnostics which do not have a location to match the ' behavior of native compiler. This allows MSBuild output to be consistent whether Roslyn is installed or not. Return VisualBasicCompiler.VbcCommandLinePrefix & MyBase.Format(diagnostic, formatter) End If Dim baseMessage = MyBase.Format(diagnostic, formatter) Dim sb As New StringBuilder() sb.AppendLine(baseMessage) ' the squiggles are displayed for the original (unmapped) location Dim sourceSpan = diagnosticSpanOpt.Value Dim sourceSpanStart = sourceSpan.Start Dim sourceSpanEnd = sourceSpan.End Dim linenumber = text.Lines.IndexOf(sourceSpanStart) Dim line = text.Lines(linenumber) If sourceSpan.IsEmpty AndAlso line.Start = sourceSpanEnd AndAlso linenumber > 0 Then ' Sometimes there is something missing at the end of the line, then the error is reported with an empty span ' beyond the end of the line, which makes it appear that the span starts at the beginning of the next line. ' Let's go back to the previous line in this case. linenumber -= 1 line = text.Lines(linenumber) End If While (line.Start < sourceSpanEnd) ' Builds the original text line sb.AppendLine() sb.AppendLine(line.ToString().Replace(vbTab, " ")) ' normalize tabs with 4 spaces ' Builds leading spaces up to the error span For position = Math.Min(sourceSpanStart, line.Start) To Math.Min(line.End, sourceSpanStart) - 1 If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append(" "c, 4) Else sb.Append(" ") End If Next ' Builds squiggles If sourceSpan.IsEmpty Then sb.Append("~") Else For position = Math.Max(sourceSpanStart, line.Start) To Math.Min(If(sourceSpanEnd = sourceSpanStart, sourceSpanEnd, sourceSpanEnd - 1), line.End - 1) If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append("~"c, 4) Else sb.Append("~") End If Next End If ' Builds trailing spaces up to the end of this line For position = Math.Min(sourceSpanEnd, line.End) To line.End - 1 If (text(position) = vbTab) Then ' normalize tabs with 4 spaces sb.Append(" "c, 4) Else sb.Append(" ") End If Next ' The error span can continue over multiple lines linenumber = linenumber + 1 If linenumber >= text.Lines.Count Then ' Exit the loop when we reach the end line (0-based) Exit While End If line = text.Lines(linenumber) End While Return sb.ToString() End Function Friend Overrides Function FormatSourcePath(path As String, basePath As String, formatter As IFormatProvider) As String Return If(FileUtilities.NormalizeRelativePath(path, basePath, _baseDirectory), path) End Function Private Function GetDiagnosticSpanAndFileText(diagnostic As Diagnostic, <Out> ByRef text As SourceText) As TextSpan? If diagnostic.Location.IsInSource Then text = diagnostic.Location.SourceTree.GetText() Return diagnostic.Location.SourceSpan End If If diagnostic.Location.Kind = LocationKind.ExternalFile Then Dim path = diagnostic.Location.GetLineSpan().Path If path IsNot Nothing Then For Each additionalTextFile In _getAdditionalTextFiles() If path.Equals(additionalTextFile.Path) Then Try text = additionalTextFile.GetText() Catch text = Nothing End Try Return diagnostic.Location.SourceSpan End If Next End If End If text = Nothing Return Nothing End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Emit/SynthesizedPrivateImplementationDetailsSharedConstructor.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.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SynthesizedPrivateImplementationDetailsSharedConstructor Inherits SynthesizedGlobalMethodBase Private ReadOnly _containingModule As SourceModuleSymbol Private ReadOnly _privateImplementationType As PrivateImplementationDetails Private ReadOnly _voidType As TypeSymbol Friend Sub New( containingModule As SourceModuleSymbol, privateImplementationType As PrivateImplementationDetails, voidType As NamedTypeSymbol ) MyBase.New(containingModule, WellKnownMemberNames.StaticConstructorName, privateImplementationType) _containingModule = containingModule _privateImplementationType = privateImplementationType _voidType = voidType End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _voidType End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.SharedConstructor End Get End Property Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing Dim factory As New SyntheticBoundNodeFactory(Me, Me, VisualBasicSyntaxTree.Dummy.GetRoot(), compilationState, diagnostics) Dim body As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance() ' Initialize the payload root for each kind of dynamic analysis instrumentation. ' A payload root is an array of arrays of per-method instrumentation payloads. ' For each kind of instrumentation: ' ' payloadRoot = New T(MaximumMethodDefIndex)() {} ' ' where T Is the type of the payload at each instrumentation point, and MaximumMethodDefIndex is the ' index portion of the greatest method definition token in the compilation. This guarantees that any ' method can use the index portion of its own method definition token as an index into the payload array. For Each payloadRoot As KeyValuePair(Of Integer, InstrumentationPayloadRootField) In _privateImplementationType.GetInstrumentationPayloadRoots() Dim analysisKind As Integer = payloadRoot.Key Dim payloadArrayType As ArrayTypeSymbol = DirectCast(payloadRoot.Value.Type.GetInternalSymbol(), ArrayTypeSymbol) body.Add( factory.Assignment( factory.InstrumentationPayloadRoot(analysisKind, payloadArrayType, isLValue:=True), factory.Array(payloadArrayType.ElementType, ImmutableArray.Create(factory.MaximumMethodDefIndex()), ImmutableArray(Of BoundExpression).Empty))) Next ' Initialize the module version ID (MVID) field. Dynamic instrumentation requires the MVID of the executing module, and this field makes that accessible. ' MVID = New Guid(ModuleVersionIdString) Dim guidConstructor As MethodSymbol = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) If guidConstructor IsNot Nothing Then body.Add( factory.Assignment( factory.ModuleVersionId(isLValue:=True), factory.[New](guidConstructor, factory.ModuleVersionIdString()))) End If body.Add(factory.Return()) Return factory.Block(body.ToImmutableAndFree()) End Function Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _containingModule 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.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SynthesizedPrivateImplementationDetailsSharedConstructor Inherits SynthesizedGlobalMethodBase Private ReadOnly _containingModule As SourceModuleSymbol Private ReadOnly _privateImplementationType As PrivateImplementationDetails Private ReadOnly _voidType As TypeSymbol Friend Sub New( containingModule As SourceModuleSymbol, privateImplementationType As PrivateImplementationDetails, voidType As NamedTypeSymbol ) MyBase.New(containingModule, WellKnownMemberNames.StaticConstructorName, privateImplementationType) _containingModule = containingModule _privateImplementationType = privateImplementationType _voidType = voidType End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _voidType End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.SharedConstructor End Get End Property Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing Dim factory As New SyntheticBoundNodeFactory(Me, Me, VisualBasicSyntaxTree.Dummy.GetRoot(), compilationState, diagnostics) Dim body As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance() ' Initialize the payload root for each kind of dynamic analysis instrumentation. ' A payload root is an array of arrays of per-method instrumentation payloads. ' For each kind of instrumentation: ' ' payloadRoot = New T(MaximumMethodDefIndex)() {} ' ' where T Is the type of the payload at each instrumentation point, and MaximumMethodDefIndex is the ' index portion of the greatest method definition token in the compilation. This guarantees that any ' method can use the index portion of its own method definition token as an index into the payload array. For Each payloadRoot As KeyValuePair(Of Integer, InstrumentationPayloadRootField) In _privateImplementationType.GetInstrumentationPayloadRoots() Dim analysisKind As Integer = payloadRoot.Key Dim payloadArrayType As ArrayTypeSymbol = DirectCast(payloadRoot.Value.Type.GetInternalSymbol(), ArrayTypeSymbol) body.Add( factory.Assignment( factory.InstrumentationPayloadRoot(analysisKind, payloadArrayType, isLValue:=True), factory.Array(payloadArrayType.ElementType, ImmutableArray.Create(factory.MaximumMethodDefIndex()), ImmutableArray(Of BoundExpression).Empty))) Next ' Initialize the module version ID (MVID) field. Dynamic instrumentation requires the MVID of the executing module, and this field makes that accessible. ' MVID = New Guid(ModuleVersionIdString) Dim guidConstructor As MethodSymbol = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) If guidConstructor IsNot Nothing Then body.Add( factory.Assignment( factory.ModuleVersionId(isLValue:=True), factory.[New](guidConstructor, factory.ModuleVersionIdString()))) End If body.Add(factory.Return()) Return factory.Block(body.ToImmutableAndFree()) End Function Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _containingModule End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/VisualBasic/Impl/CodeModel/Extenders/GenericExtender.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.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders <ComVisible(True)> <ComDefaultInterface(GetType(IVBGenericExtender))> Public Class GenericExtender Implements IVBGenericExtender Friend Shared Function Create(codeType As AbstractCodeType) As IVBGenericExtender Dim result = New GenericExtender(codeType) Return CType(ComAggregate.CreateAggregatedObject(result), IVBGenericExtender) End Function Private ReadOnly _codeType As ParentHandle(Of AbstractCodeType) Private Sub New(codeType As AbstractCodeType) _codeType = New ParentHandle(Of AbstractCodeType)(codeType) End Sub Private Function GetTypesCount(baseType As Boolean) As Integer Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol) If baseType Then Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Enum Return 1 Case TypeKind.Interface Return typeSymbol.Interfaces.Length End Select Else Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Structure Return typeSymbol.Interfaces.Length End Select End If Throw Exceptions.ThrowEInvalidArg() End Function Private Function GetGenericName(baseType As Boolean, index As Integer) As String Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol) If baseType Then Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Enum If index = 0 Then Dim baseTypeSymbol = typeSymbol.BaseType If baseTypeSymbol IsNot Nothing Then Return baseTypeSymbol.ToDisplayString() End If End If Return Nothing Case TypeKind.Interface Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length, typeSymbol.Interfaces(index).ToDisplayString(), Nothing) End Select Else Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Structure Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length, typeSymbol.Interfaces(index).ToDisplayString(), Nothing) Case TypeKind.Delegate, TypeKind.Enum Return Nothing End Select End If Throw Exceptions.ThrowEInvalidArg() End Function Public ReadOnly Property GetBaseGenericName(index As Integer) As String Implements IVBGenericExtender.GetBaseGenericName Get ' NOTE: index is 1-based. Return GetGenericName(baseType:=True, index:=index - 1) End Get End Property Public ReadOnly Property GetBaseTypesCount As Integer Implements IVBGenericExtender.GetBaseTypesCount Get Return GetTypesCount(baseType:=True) End Get End Property Public ReadOnly Property GetImplementedTypesCount As Integer Implements IVBGenericExtender.GetImplementedTypesCount Get Return GetTypesCount(baseType:=False) End Get End Property Public ReadOnly Property GetImplTypeGenericName(index As Integer) As String Implements IVBGenericExtender.GetImplTypeGenericName Get ' NOTE: index is 1-based. Return GetGenericName(baseType:=False, index:=index - 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 System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders <ComVisible(True)> <ComDefaultInterface(GetType(IVBGenericExtender))> Public Class GenericExtender Implements IVBGenericExtender Friend Shared Function Create(codeType As AbstractCodeType) As IVBGenericExtender Dim result = New GenericExtender(codeType) Return CType(ComAggregate.CreateAggregatedObject(result), IVBGenericExtender) End Function Private ReadOnly _codeType As ParentHandle(Of AbstractCodeType) Private Sub New(codeType As AbstractCodeType) _codeType = New ParentHandle(Of AbstractCodeType)(codeType) End Sub Private Function GetTypesCount(baseType As Boolean) As Integer Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol) If baseType Then Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Enum Return 1 Case TypeKind.Interface Return typeSymbol.Interfaces.Length End Select Else Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Structure Return typeSymbol.Interfaces.Length End Select End If Throw Exceptions.ThrowEInvalidArg() End Function Private Function GetGenericName(baseType As Boolean, index As Integer) As String Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol) If baseType Then Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Enum If index = 0 Then Dim baseTypeSymbol = typeSymbol.BaseType If baseTypeSymbol IsNot Nothing Then Return baseTypeSymbol.ToDisplayString() End If End If Return Nothing Case TypeKind.Interface Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length, typeSymbol.Interfaces(index).ToDisplayString(), Nothing) End Select Else Select Case typeSymbol.TypeKind Case TypeKind.Class, TypeKind.Structure Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length, typeSymbol.Interfaces(index).ToDisplayString(), Nothing) Case TypeKind.Delegate, TypeKind.Enum Return Nothing End Select End If Throw Exceptions.ThrowEInvalidArg() End Function Public ReadOnly Property GetBaseGenericName(index As Integer) As String Implements IVBGenericExtender.GetBaseGenericName Get ' NOTE: index is 1-based. Return GetGenericName(baseType:=True, index:=index - 1) End Get End Property Public ReadOnly Property GetBaseTypesCount As Integer Implements IVBGenericExtender.GetBaseTypesCount Get Return GetTypesCount(baseType:=True) End Get End Property Public ReadOnly Property GetImplementedTypesCount As Integer Implements IVBGenericExtender.GetImplementedTypesCount Get Return GetTypesCount(baseType:=False) End Get End Property Public ReadOnly Property GetImplTypeGenericName(index As Integer) As String Implements IVBGenericExtender.GetImplTypeGenericName Get ' NOTE: index is 1-based. Return GetGenericName(baseType:=False, index:=index - 1) End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_CSAssignments.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 Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = 42; } int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { x = 42; } int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithObjectCreation() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = new System.Object(); } System.Object x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Object</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithEnumMember() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = System.DayOfWeek.Friday; } private System.DayOfWeek x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.DayOfWeek</Type> </Literal> </Expression> <Name>Friday</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.X = 42; } public int X { get; set; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { X = 42; } public int X { get; set; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldThroughPropertyWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.X.x = 42; } public C X { get; set; } private int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldThroughPropertyWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { X.x = 42; } public C X { get; set; } private int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_AssignLocalsWithField() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 42; x = y; } private int y = 100; } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>y</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_CompoundAdd() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 1; x += 41; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">41</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_CompoundSubtract() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 42; x -= 41; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Local> <Quote line="6">x -= 41;</Quote> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ArrayElementAccess() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int[] x = new int[42]; x[0] = 10; var y = x[1]; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>x</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment> <Expression> <ArrayElementAccess> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </ArrayElementAccess> </Expression> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <Local line="7"> <Type>System.Int32</Type> <Name>y</Name> <Expression> <ArrayElementAccess> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </ArrayElementAccess> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(743120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743120")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyOffParameter() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M(System.Text.StringBuilder builder) { builder.Capacity = 10; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="local"> <Name>builder</Name> </NameRef> </Expression> <Name>Capacity</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_NullableValue() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int? i = 0; int? j = null; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Nullable`1[System.Int32]</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Local line="6"> <Type>System.Nullable`1[System.Int32]</Type> <Name>j</Name> <Expression> <Literal> <Null/> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric1() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;int&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.Int32]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Int32]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric2() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new Dictionary&lt;string, List&lt;int&gt;&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric3() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;string[]&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.String[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric4() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;string[,,]&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer1() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int x) { int* i = &amp;x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Quote line="5">int* i = &amp;x;</Quote> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer2() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int* x) { int* i = x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32*</Type> <Name>i</Name> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer3() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int** x) { int** i = x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32**</Type> <Name>i</Name> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_TypeConfluence() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using L = System.Collections.Generic.List&lt;byte*[]&gt;; class C { $$unsafe void M() { var l = new L(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.Byte*[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Byte*[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(887584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887584")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_EscapedNames() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum E { @true, @false } class C { private E e; void $$M() { e = E.@true; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="12"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>e</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>E</Type> </Literal> </Expression> <Name>true</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(1126037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1126037")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ControlChar() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public char Char { get; set; } void $$M() { Char = '\u0011'; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="7"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Char</Name> </NameRef> </Expression> <Expression> <Cast> <Type>System.Char</Type> <Expression> <Literal> <Number type="System.UInt16">17</Number> </Literal> </Expression> </Cast> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(4312, "https://github.com/dotnet/roslyn/issues/4312")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyAssignedWithEmptyArray() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private object[] Series { get; set } $$void M() { this.Series = new object[0] {}; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="7"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Series</Name> </NameRef> </Expression> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Object</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>0</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <Array></Array> </Literal> </Expression> </NewArray> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_RoundTrippedDoubles() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void $$M() { double d = 9.2233720368547758E+18D; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Double</Type> <Name>d</Name> <Expression> <Literal> <Number type="System.Double">9.2233720368547758E+18</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_RoundTrippedSingles() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void $$M() { float s = 0.333333343F; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Single</Type> <Name>s</Name> <Expression> <Literal> <Number type="System.Single">0.333333343</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub End Class End Namespace
' 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 Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = 42; } int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { x = 42; } int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithObjectCreation() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = new System.Object(); } System.Object x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Object</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldWithEnumMember() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.x = System.DayOfWeek.Friday; } private System.DayOfWeek x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.DayOfWeek</Type> </Literal> </Expression> <Name>Friday</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.X = 42; } public int X { get; set; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { X = 42; } public int X { get; set; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldThroughPropertyWithThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.X.x = 42; } public C X { get; set; } private int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_FieldThroughPropertyWithoutThis() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { X.x = 42; } public C X { get; set; } private int x; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>X</Name> </NameRef> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_AssignLocalsWithField() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 42; x = y; } private int y = 100; } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>y</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_CompoundAdd() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 1; x += 41; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">41</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_CompoundSubtract() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int x = 42; x -= 41; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32</Type> <Name>x</Name> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Local> <Quote line="6">x -= 41;</Quote> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ArrayElementAccess() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int[] x = new int[42]; x[0] = 10; var y = x[1]; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Name>x</Name> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Int32</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">42</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Local> <ExpressionStatement line="6"> <Expression> <Assignment> <Expression> <ArrayElementAccess> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </ArrayElementAccess> </Expression> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <Local line="7"> <Type>System.Int32</Type> <Name>y</Name> <Expression> <ArrayElementAccess> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </ArrayElementAccess> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(743120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743120")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyOffParameter() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M(System.Text.StringBuilder builder) { builder.Capacity = 10; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="local"> <Name>builder</Name> </NameRef> </Expression> <Name>Capacity</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_NullableValue() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { int? i = 0; int? j = null; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Nullable`1[System.Int32]</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Local line="6"> <Type>System.Nullable`1[System.Int32]</Type> <Name>j</Name> <Expression> <Literal> <Null/> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric1() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;int&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.Int32]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Int32]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric2() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new Dictionary&lt;string, List&lt;int&gt;&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric3() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;string[]&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.String[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ClosedGeneric4() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Collections.Generic; public class C { $$void M() { var l = new List&lt;string[,,]&gt;(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer1() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int x) { int* i = &amp;x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Quote line="5">int* i = &amp;x;</Quote> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer2() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int* x) { int* i = x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32*</Type> <Name>i</Name> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_Pointer3() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$unsafe void M(int** x) { int** i = x; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Int32**</Type> <Name>i</Name> <Expression> <NameRef variablekind="local"> <Name>x</Name> </NameRef> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_TypeConfluence() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using L = System.Collections.Generic.List&lt;byte*[]&gt;; class C { $$unsafe void M() { var l = new L(); } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="7"> <Type>System.Collections.Generic.List`1[System.Byte*[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Byte*[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(887584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887584")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_EscapedNames() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum E { @true, @false } class C { private E e; void $$M() { e = E.@true; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="12"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>e</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>E</Type> </Literal> </Expression> <Name>true</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(1126037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1126037")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_ControlChar() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public char Char { get; set; } void $$M() { Char = '\u0011'; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="7"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Char</Name> </NameRef> </Expression> <Expression> <Cast> <Type>System.Char</Type> <Expression> <Literal> <Number type="System.UInt16">17</Number> </Literal> </Expression> </Cast> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(4312, "https://github.com/dotnet/roslyn/issues/4312")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_PropertyAssignedWithEmptyArray() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private object[] Series { get; set } $$void M() { this.Series = new object[0] {}; } } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="7"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Series</Name> </NameRef> </Expression> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Object</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>0</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <Array></Array> </Literal> </Expression> </NewArray> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_RoundTrippedDoubles() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void $$M() { double d = 9.2233720368547758E+18D; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Double</Type> <Name>d</Name> <Expression> <Literal> <Number type="System.Double">9.2233720368547758E+18</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSAssignments_RoundTrippedSingles() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void $$M() { float s = 0.333333343F; } } </Document> </Project> </Workspace> Dim expected = <Block> <Local line="5"> <Type>System.Single</Type> <Name>s</Name> <Expression> <Literal> <Number type="System.Single">0.333333343</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/Test2/Expansion/LambdaParameterExpansionTests.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 Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class LambdaParameterExpansionTests Inherits AbstractExpansionTest <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithNoParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action a = {|Expand:() => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code> using System; class C { void M() { Action a = () => { }; } } </code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithSingleParameter_NoParens() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int> a = {|Expand:x => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int> a = (global::System.Int32 x) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithSingleParameter_WithParens() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int> a = {|Expand:(x) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int> a = (global::System.Int32 x) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithTwoParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int, int> a = {|Expand:(x, y) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int, int> a = (global::System.Int32 x, global::System.Int32 y) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithThreeParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int, int, int> a = {|Expand:(x, y, z) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int, int, int> a = (global::System.Int32 x, global::System.Int32 y, global::System.Int32 z) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) 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 Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion Public Class LambdaParameterExpansionTests Inherits AbstractExpansionTest <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithNoParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action a = {|Expand:() => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code> using System; class C { void M() { Action a = () => { }; } } </code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithSingleParameter_NoParens() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int> a = {|Expand:x => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int> a = (global::System.Int32 x) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithSingleParameter_WithParens() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int> a = {|Expand:(x) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int> a = (global::System.Int32 x) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithTwoParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int, int> a = {|Expand:(x, y) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int, int> a = (global::System.Int32 x, global::System.Int32 y) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Expansion)> Public Async Function TestCSharp_ExpandLambdaWithThreeParameters() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class C { void M() { Action<int, int, int> a = {|Expand:(x, y, z) => { }|}; } } ]]></Document> </Project> </Workspace> Dim expected = <code><![CDATA[ using System; class C { void M() { Action<int, int, int> a = (global::System.Int32 x, global::System.Int32 y, global::System.Int32 z) => { }; } } ]]></code> Await TestAsync(input, expected, expandParameter:=True) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/VisualBasic/Impl/Venus/ContainedLanguageStaticEventBinding.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.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Module ContainedLanguageStaticEventBinding ''' <summary> ''' Find all the methods that handle events (though "Handles" clauses). ''' </summary> ''' <returns></returns> Public Function GetStaticEventBindings(document As Document, className As String, objectName As String, cancellationToken As CancellationToken) As IEnumerable(Of Tuple(Of String, String, String)) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim methods = type.GetMembers(). Where(Function(m) m.CanBeReferencedByName AndAlso m.Kind = SymbolKind.Method). Cast(Of IMethodSymbol)() Dim methodAndMethodSyntaxesWithHandles = methods. Select(Function(m) Tuple.Create(m, GetMethodStatement(m))). Where(Function(t) t.Item2.HandlesClause IsNot Nothing). ToArray() If Not methodAndMethodSyntaxesWithHandles.Any() Then Return SpecializedCollections.EmptyEnumerable(Of Tuple(Of String, String, String))() End If Dim result As New List(Of Tuple(Of String, String, String))() For Each methodAndMethodSyntax In methodAndMethodSyntaxesWithHandles For Each handleClauseItem In methodAndMethodSyntax.Item2.HandlesClause.Events If handleClauseItem.EventContainer.ToString() = objectName OrElse (String.IsNullOrEmpty(objectName) AndAlso handleClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword)) Then result.Add(Tuple.Create(handleClauseItem.EventMember.Identifier.ToString(), methodAndMethodSyntax.Item2.Identifier.ToString(), ContainedLanguageCodeSupport.ConstructMemberId(methodAndMethodSyntax.Item1))) End If Next Next Return result End Function Public Sub AddStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) If HandlesEvent(GetMethodStatement(memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextSynchronously(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) AddStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.AddHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Sub RemoveStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) If Not HandlesEvent(GetMethodStatement(memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextSynchronously(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) RemoveStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.RemoveHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Function HandlesEvent(methodStatement As MethodStatementSyntax, objectName As String, eventName As String) As Boolean If methodStatement.HandlesClause Is Nothing Then Return False End If For Each handlesClauseItem In methodStatement.HandlesClause.Events If handlesClauseItem.EventMember.ToString() = eventName Then If String.IsNullOrEmpty(objectName) AndAlso handlesClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword) Then Return True ElseIf handlesClauseItem.EventContainer.ToString() = objectName Then Return True End If End If Next Return False End Function Private Function GetMemberBlockOrBegin(member As ISymbol) As SyntaxNode Return member.DeclaringSyntaxReferences.Select(Function(r) r.GetSyntax()).FirstOrDefault() End Function Private Function GetMethodStatement(member As ISymbol) As MethodStatementSyntax Dim node = GetMemberBlockOrBegin(member) If node.Kind = SyntaxKind.SubBlock OrElse node.Kind = SyntaxKind.FunctionBlock Then Return DirectCast(DirectCast(node, MethodBlockSyntax).BlockStatement, MethodStatementSyntax) ElseIf node.Kind = SyntaxKind.SubStatement OrElse node.Kind = SyntaxKind.FunctionStatement Then Return DirectCast(node, MethodStatementSyntax) Else Throw New InvalidOperationException() End If 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 Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Module ContainedLanguageStaticEventBinding ''' <summary> ''' Find all the methods that handle events (though "Handles" clauses). ''' </summary> ''' <returns></returns> Public Function GetStaticEventBindings(document As Document, className As String, objectName As String, cancellationToken As CancellationToken) As IEnumerable(Of Tuple(Of String, String, String)) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim methods = type.GetMembers(). Where(Function(m) m.CanBeReferencedByName AndAlso m.Kind = SymbolKind.Method). Cast(Of IMethodSymbol)() Dim methodAndMethodSyntaxesWithHandles = methods. Select(Function(m) Tuple.Create(m, GetMethodStatement(m))). Where(Function(t) t.Item2.HandlesClause IsNot Nothing). ToArray() If Not methodAndMethodSyntaxesWithHandles.Any() Then Return SpecializedCollections.EmptyEnumerable(Of Tuple(Of String, String, String))() End If Dim result As New List(Of Tuple(Of String, String, String))() For Each methodAndMethodSyntax In methodAndMethodSyntaxesWithHandles For Each handleClauseItem In methodAndMethodSyntax.Item2.HandlesClause.Events If handleClauseItem.EventContainer.ToString() = objectName OrElse (String.IsNullOrEmpty(objectName) AndAlso handleClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword)) Then result.Add(Tuple.Create(handleClauseItem.EventMember.Identifier.ToString(), methodAndMethodSyntax.Item2.Identifier.ToString(), ContainedLanguageCodeSupport.ConstructMemberId(methodAndMethodSyntax.Item1))) End If Next Next Return result End Function Public Sub AddStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) If HandlesEvent(GetMethodStatement(memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextSynchronously(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) AddStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.AddHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Sub RemoveStaticEventBinding(document As Document, visualStudioWorkspace As VisualStudioWorkspace, className As String, memberId As String, objectName As String, nameOfEvent As String, cancellationToken As CancellationToken) Dim type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className) Dim memberSymbol = ContainedLanguageCodeSupport.LookupMemberId(type, memberId) Dim targetDocument = document.Project.Solution.GetDocument(memberSymbol.Locations.First().SourceTree) If Not HandlesEvent(GetMethodStatement(memberSymbol), objectName, nameOfEvent) Then Return End If Dim textBuffer = targetDocument.GetTextSynchronously(cancellationToken).Container.TryGetTextBuffer() If textBuffer Is Nothing Then Using visualStudioWorkspace.OpenInvisibleEditor(targetDocument.Id) targetDocument = visualStudioWorkspace.CurrentSolution.GetDocument(targetDocument.Id) RemoveStaticEventBinding(targetDocument, visualStudioWorkspace, className, memberId, objectName, nameOfEvent, cancellationToken) End Using Else Dim memberStatement = GetMemberBlockOrBegin(memberSymbol) Dim codeModel = targetDocument.Project.LanguageServices.GetService(Of ICodeModelService)() codeModel.RemoveHandlesClause(targetDocument, objectName & "." & nameOfEvent, memberStatement, cancellationToken) End If End Sub Public Function HandlesEvent(methodStatement As MethodStatementSyntax, objectName As String, eventName As String) As Boolean If methodStatement.HandlesClause Is Nothing Then Return False End If For Each handlesClauseItem In methodStatement.HandlesClause.Events If handlesClauseItem.EventMember.ToString() = eventName Then If String.IsNullOrEmpty(objectName) AndAlso handlesClauseItem.EventContainer.IsKind(SyntaxKind.MeKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword) Then Return True ElseIf handlesClauseItem.EventContainer.ToString() = objectName Then Return True End If End If Next Return False End Function Private Function GetMemberBlockOrBegin(member As ISymbol) As SyntaxNode Return member.DeclaringSyntaxReferences.Select(Function(r) r.GetSyntax()).FirstOrDefault() End Function Private Function GetMethodStatement(member As ISymbol) As MethodStatementSyntax Dim node = GetMemberBlockOrBegin(member) If node.Kind = SyntaxKind.SubBlock OrElse node.Kind = SyntaxKind.FunctionBlock Then Return DirectCast(DirectCast(node, MethodBlockSyntax).BlockStatement, MethodStatementSyntax) ElseIf node.Kind = SyntaxKind.SubStatement OrElse node.Kind = SyntaxKind.FunctionStatement Then Return DirectCast(node, MethodStatementSyntax) Else Throw New InvalidOperationException() End If End Function End Module End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_NoOptions() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) M(TODO) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleLocal() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_MultipleLocals() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 Dim y = 8 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 Dim y = 8 M(y) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, a As Integer) M(1, x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleField() As Task Dim markup = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M(a As Integer) M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleProperty() As Task Dim markup = <Text><![CDATA[ Class C Property X As Integer Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Property X As Integer Sub M(a As Integer) M(X) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable() As Task Dim markup = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M$$() Dim d As D M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M(b As B) Dim d As D M(d) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) 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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_NoOptions() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) M(TODO) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleLocal() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_MultipleLocals() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 Dim y = 8 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 Dim y = 8 M(y) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, a As Integer) M(1, x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleField() As Task Dim markup = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M(a As Integer) M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleProperty() As Task Dim markup = <Text><![CDATA[ Class C Property X As Integer Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Property X As Integer Sub M(a As Integer) M(X) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable() As Task Dim markup = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M$$() Dim d As D M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M(b As B) Dim d As D M(d) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/Core/Test/ProjectSystemShim/ConvertedVisualBasicProjectOptionsTests.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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim Public Class ConvertedVisualBasicProjectOptionsTests <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() Dim convertedOptions = GetConvertedOptions(ruleSetGeneralOption:=ReportDiagnostic.Warn, commandLineGeneralOption:=WarningLevel.WARN_AsError) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=0, actual:=convertedOptions.SpecificDiagnosticOptions.Count) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions(commandLineGeneralOption:=WarningLevel.WARN_AsError, ruleSetSpecificOptions:=ruleSetSpecificOptions) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions(commandLineGeneralOption:=WarningLevel.WARN_AsError, ruleSetSpecificOptions:=ruleSetSpecificOptions) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Info, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnAsErrors:="Test001") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusResetsRules() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnNotAsErrors:="Test001") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnNotAsErrors:="Test001;Test002") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=2, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=convertedOptions.SpecificDiagnosticOptions("Test002")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTurnsOffAllButErrors() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Error}, {"Test002", ReportDiagnostic.Warn}, {"Test003", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_None) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=3, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test002")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test003")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificNoWarnAlwaysWins() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineWarnAsErrors:="Test001", commandLineNoWarns:="Test001") Assert.Equal(expected:=ReportDiagnostic.Default, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub Private Shared Function GetConvertedOptions( Optional ruleSetGeneralOption As ReportDiagnostic = ReportDiagnostic.Default, Optional ruleSetSpecificOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing, Optional commandLineGeneralOption As WarningLevel = WarningLevel.WARN_Regular, Optional commandLineWarnAsErrors As String = "", Optional commandLineWarnNotAsErrors As String = "", Optional commandLineNoWarns As String = "") As VisualBasicCompilationOptions ruleSetSpecificOptions = If(ruleSetSpecificOptions, ImmutableDictionary(Of String, ReportDiagnostic).Empty) Dim compilerOptions = New VBCompilerOptions With { .WarningLevel = commandLineGeneralOption, .wszWarningsAsErrors = commandLineWarnAsErrors, .wszWarningsNotAsErrors = commandLineWarnNotAsErrors, .wszDisabledWarnings = commandLineNoWarns } Dim compilerHost = New MockCompilerHost("C:\SDK") Return VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions( New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) _ .WithParseOptions(VisualBasicParseOptions.Default), compilerOptions, New MockRuleSetFile(ruleSetGeneralOption, ruleSetSpecificOptions)) 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.IO Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim Public Class ConvertedVisualBasicProjectOptionsTests <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() Dim convertedOptions = GetConvertedOptions(ruleSetGeneralOption:=ReportDiagnostic.Warn, commandLineGeneralOption:=WarningLevel.WARN_AsError) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=0, actual:=convertedOptions.SpecificDiagnosticOptions.Count) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions(commandLineGeneralOption:=WarningLevel.WARN_AsError, ruleSetSpecificOptions:=ruleSetSpecificOptions) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions(commandLineGeneralOption:=WarningLevel.WARN_AsError, ruleSetSpecificOptions:=ruleSetSpecificOptions) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Info, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnAsErrors:="Test001") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusResetsRules() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnNotAsErrors:="Test001") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_AsError, commandLineWarnNotAsErrors:="Test001;Test002") Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=2, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=convertedOptions.SpecificDiagnosticOptions("Test002")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTurnsOffAllButErrors() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Error}, {"Test002", ReportDiagnostic.Warn}, {"Test003", ReportDiagnostic.Info} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineGeneralOption:=WarningLevel.WARN_None) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=3, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test002")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test003")) End Sub <WpfFact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificNoWarnAlwaysWins() Dim ruleSetSpecificOptions = New Dictionary(Of String, ReportDiagnostic) From { {"Test001", ReportDiagnostic.Warn} }.ToImmutableDictionary() Dim convertedOptions = GetConvertedOptions( ruleSetSpecificOptions:=ruleSetSpecificOptions, commandLineWarnAsErrors:="Test001", commandLineNoWarns:="Test001") Assert.Equal(expected:=ReportDiagnostic.Default, actual:=convertedOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=convertedOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=convertedOptions.SpecificDiagnosticOptions("Test001")) End Sub Private Shared Function GetConvertedOptions( Optional ruleSetGeneralOption As ReportDiagnostic = ReportDiagnostic.Default, Optional ruleSetSpecificOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing, Optional commandLineGeneralOption As WarningLevel = WarningLevel.WARN_Regular, Optional commandLineWarnAsErrors As String = "", Optional commandLineWarnNotAsErrors As String = "", Optional commandLineNoWarns As String = "") As VisualBasicCompilationOptions ruleSetSpecificOptions = If(ruleSetSpecificOptions, ImmutableDictionary(Of String, ReportDiagnostic).Empty) Dim compilerOptions = New VBCompilerOptions With { .WarningLevel = commandLineGeneralOption, .wszWarningsAsErrors = commandLineWarnAsErrors, .wszWarningsNotAsErrors = commandLineWarnNotAsErrors, .wszDisabledWarnings = commandLineNoWarns } Dim compilerHost = New MockCompilerHost("C:\SDK") Return VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions( New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) _ .WithParseOptions(VisualBasicParseOptions.Default), compilerOptions, New MockRuleSetFile(ruleSetGeneralOption, ruleSetSpecificOptions)) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/Test2/GoToDefinition/VisualBasicGoToDefinitionTests.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.UnitTests.GoToDefinition <[UseExportProvider]> Public Class VisualBasicGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "Normal Visual Basic Tests" <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> public class MyClass1 public property [|Prop1|] as integer end class class Program sub Main() dim instance = new MyClass1() dim x as new With { instance.$$Prop1 } end sub end class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] End Class Class OtherClass Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as Integer = 12$$3 </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as String = "wo$$ow" </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(541105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541105")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicPropertyBackingField() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property [|P|] As Integer Sub M() Me.$$_P = 10 End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Outer Class [|Inner|] End Class Dim obj as In$$ner End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class OtherClass Dim obj As SomeClass End Class </Document> <Document> Class OtherClass2 Dim obj As Some$$Class End Class </Document> <Document> Class [|SomeClass|] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> DummyClass End Class </Document> <Document> Partial Class [|OtherClass|] Dim a As Integer End Class </Document> <Document> Partial Class [|OtherClass|] Dim b As Integer End Class </Document> <Document> Class ConsumingClass Dim obj As Other$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As Some$$Class End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class Customer Private Sub [|OnNameChanged|]() End Sub End Class </Document> <Document> Partial Class Customer Sub New() Dim x As New Customer() x.OnNameChanged$$() End Sub Partial Private Sub OnNameChanged() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchLeft() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As $$SomeClass End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchRight() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMe() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() MyClass.Goo() $$Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() $$MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyBase() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|B|] Sub New() End Sub End Class Class C Inherits B Sub New() $$MyBase.New() MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenSubDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Sub [|Method|]() End Sub End Class Class Derived Inherits Base Overr$$ides Sub Method() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenFunctionDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Function [|Method|]() As Integer Return 1 End Function End Class Class Derived Inherits Base Overr$$ides Function Method() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenPropertyDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Property [|Number|] As Integer End Class Class Derived Inherits Base Overr$$ides Property Number As Integer End Class </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Venus Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> #ExternalSource ("Default.aspx", 1) Class [|Program|] Sub Main(args As String()) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTestThroughExecuteCommand() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim i As String = "1" i.Test$$Ext() End Sub End Class Module Ex <System.Runtime.CompilerServices.Extension()> Public Sub TestExt(Of T)(ex As T) End Sub <System.Runtime.CompilerServices.Extension()> Public Sub [|TestExt|](ex As string) End Sub End Module]]>] </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(543218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543218")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicQueryRangeVariable() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q3 = From [|num|] In arr Select $$num End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoConstant() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$200 [|200|]: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(10132, "https://github.com/dotnet/roslyn/issues/10132")> <WorkItem(545661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545661")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageParameterizedPropertyOverride() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Class A Public Overridable ReadOnly Property X(y As Integer) As Integer [|Get|] End Get End Property End Class </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class B : A { public override int get_X(int y) { return base.$$get_X(y); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageNavigationToVBModuleMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class C { static void N() { A.$$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationVB() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class SomeClass End Class C$$lass OtherClass Dim obj As SomeClass End Class </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(902119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902119")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnInferredFieldInitializer() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class2 Sub Test() Dim var1 = New With {Key .var2 = "Bob", Class2.va$$r3} End Sub Shared Property [|var3|]() As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(885151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/885151")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionGlobalImportAlias() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <CompilationOptions> <GlobalImport>Goo = Importable.ImportMe</GlobalImport> </CompilationOptions> <Document> Public Class Class2 Sub Test() Dim x as Go$$o End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace Importable Public Class [|ImportMe|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Exit() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit$$ Select End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Select() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit Select$$ End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Exit Sub$$ End Sub[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M() As Integer Exit Sub$$ End Function[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue$$ While End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue While$$ End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() While True Exit While$$ End While[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue$$ For Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For index As Integer = 1 To 5 Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For Each element In Nothing Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For Each element In Nothing Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do While True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do While True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Until True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do Until True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopWhile_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop While True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopUntil_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop Until True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTry() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTryInCatch() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Catch Exception Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Partial Sub M() End Sub [||]Partial Private Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Partial Private Sub M() Return$$ End Sub Partial Sub M() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSubLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Sub() Return$$ End Sub End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Function M() As Int Return$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M([|x|] As Integer) As Integer Return x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Iterator Function M() As IEnumerable(Of Integer) Yield$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Iterator Function M([|x|] As Integer) As IEnumerable(Of Integer) Yield x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunctionLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Function() As Int Return$$ 1 End Function End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInConstructor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub New() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInOperator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Shared Operator +(ByVal i As Integer) As Integer Return$$ 1 End Operator End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Return$$ 1 End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Set Return$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Exit Property$$ End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property P() As Integer [||]Set Exit Property$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInAddHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]AddHandler(ByVal value As EventHandler) Return$$ End AddHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRemoveHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RemoveHandler(ByVal value As EventHandler) Return$$ End RemoveHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRaiseEvent() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Return$$ End RaiseEvent End Event End Class </Document> </Project> </Workspace> Test(workspace) 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.UnitTests.GoToDefinition <[UseExportProvider]> Public Class VisualBasicGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "Normal Visual Basic Tests" <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> public class MyClass1 public property [|Prop1|] as integer end class class Program sub Main() dim instance = new MyClass1() dim x as new With { instance.$$Prop1 } end sub end class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] End Class Class OtherClass Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as Integer = 12$$3 </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as String = "wo$$ow" </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(541105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541105")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicPropertyBackingField() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property [|P|] As Integer Sub M() Me.$$_P = 10 End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Outer Class [|Inner|] End Class Dim obj as In$$ner End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class OtherClass Dim obj As SomeClass End Class </Document> <Document> Class OtherClass2 Dim obj As Some$$Class End Class </Document> <Document> Class [|SomeClass|] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> DummyClass End Class </Document> <Document> Partial Class [|OtherClass|] Dim a As Integer End Class </Document> <Document> Partial Class [|OtherClass|] Dim b As Integer End Class </Document> <Document> Class ConsumingClass Dim obj As Other$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As Some$$Class End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class Customer Private Sub [|OnNameChanged|]() End Sub End Class </Document> <Document> Partial Class Customer Sub New() Dim x As New Customer() x.OnNameChanged$$() End Sub Partial Private Sub OnNameChanged() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchLeft() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As $$SomeClass End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchRight() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMe() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() MyClass.Goo() $$Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() $$MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyBase() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|B|] Sub New() End Sub End Class Class C Inherits B Sub New() $$MyBase.New() MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenSubDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Sub [|Method|]() End Sub End Class Class Derived Inherits Base Overr$$ides Sub Method() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenFunctionDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Function [|Method|]() As Integer Return 1 End Function End Class Class Derived Inherits Base Overr$$ides Function Method() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenPropertyDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Property [|Number|] As Integer End Class Class Derived Inherits Base Overr$$ides Property Number As Integer End Class </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Venus Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> #ExternalSource ("Default.aspx", 1) Class [|Program|] Sub Main(args As String()) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTestThroughExecuteCommand() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim i As String = "1" i.Test$$Ext() End Sub End Class Module Ex <System.Runtime.CompilerServices.Extension()> Public Sub TestExt(Of T)(ex As T) End Sub <System.Runtime.CompilerServices.Extension()> Public Sub [|TestExt|](ex As string) End Sub End Module]]>] </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(543218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543218")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicQueryRangeVariable() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q3 = From [|num|] In arr Select $$num End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoConstant() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$200 [|200|]: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(10132, "https://github.com/dotnet/roslyn/issues/10132")> <WorkItem(545661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545661")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageParameterizedPropertyOverride() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Class A Public Overridable ReadOnly Property X(y As Integer) As Integer [|Get|] End Get End Property End Class </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class B : A { public override int get_X(int y) { return base.$$get_X(y); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageNavigationToVBModuleMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class C { static void N() { A.$$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationVB() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class SomeClass End Class C$$lass OtherClass Dim obj As SomeClass End Class </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(902119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902119")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnInferredFieldInitializer() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class2 Sub Test() Dim var1 = New With {Key .var2 = "Bob", Class2.va$$r3} End Sub Shared Property [|var3|]() As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(885151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/885151")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionGlobalImportAlias() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <CompilationOptions> <GlobalImport>Goo = Importable.ImportMe</GlobalImport> </CompilationOptions> <Document> Public Class Class2 Sub Test() Dim x as Go$$o End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace Importable Public Class [|ImportMe|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Exit() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit$$ Select End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Select() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit Select$$ End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Exit Sub$$ End Sub[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M() As Integer Exit Sub$$ End Function[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue$$ While End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue While$$ End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() While True Exit While$$ End While[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue$$ For Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For index As Integer = 1 To 5 Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For Each element In Nothing Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For Each element In Nothing Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do While True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do While True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Until True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do Until True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopWhile_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop While True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopUntil_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop Until True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTry() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTryInCatch() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Catch Exception Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Partial Sub M() End Sub [||]Partial Private Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Partial Private Sub M() Return$$ End Sub Partial Sub M() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSubLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Sub() Return$$ End Sub End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Function M() As Int Return$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M([|x|] As Integer) As Integer Return x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Iterator Function M() As IEnumerable(Of Integer) Yield$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Iterator Function M([|x|] As Integer) As IEnumerable(Of Integer) Yield x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunctionLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Function() As Int Return$$ 1 End Function End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInConstructor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub New() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInOperator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Shared Operator +(ByVal i As Integer) As Integer Return$$ 1 End Operator End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Return$$ 1 End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Set Return$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Exit Property$$ End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property P() As Integer [||]Set Exit Property$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInAddHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]AddHandler(ByVal value As EventHandler) Return$$ End AddHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRemoveHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RemoveHandler(ByVal value As EventHandler) Return$$ End RemoveHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRaiseEvent() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Return$$ End RaiseEvent End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./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
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ReadWriteWalker.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.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records reads and writes of all variables, both inside and outside the region. ''' </summary> Friend Class ReadWriteWalker Inherits AbstractRegionDataFlowPass Friend Overloads Shared Sub Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef readInside As IEnumerable(Of Symbol), ByRef writtenInside As IEnumerable(Of Symbol), ByRef readOutside As IEnumerable(Of Symbol), ByRef writtenOutside As IEnumerable(Of Symbol), ByRef captured As IEnumerable(Of Symbol), ByRef capturedInside As IEnumerable(Of Symbol), ByRef capturedOutside As IEnumerable(Of Symbol)) Dim walker = New ReadWriteWalker(info, region) Try If walker.Analyze() Then readInside = walker._readInside writtenInside = walker._writtenInside readOutside = walker._readOutside writtenOutside = walker._writtenOutside captured = walker._captured capturedInside = walker._capturedInside capturedOutside = walker._capturedOutside Else readInside = Enumerable.Empty(Of Symbol)() writtenInside = readInside readOutside = readInside writtenOutside = readInside captured = readInside capturedInside = readInside capturedOutside = readInside End If Finally walker.Free() End Try End Sub Private ReadOnly _readInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _writtenInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _readOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _writtenOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _captured As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _capturedInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _capturedOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private _currentMethodOrLambda As Symbol Private _currentQueryLambda As BoundQueryLambda Protected Overrides Sub NoteRead(variable As Symbol) If IsCompilerGeneratedTempLocal(variable) Then MyBase.NoteRead(variable) Else Select Case Me._regionPlace Case RegionPlace.Before, RegionPlace.After _readOutside.Add(variable) Case RegionPlace.Inside _readInside.Add(variable) Case Else Throw ExceptionUtilities.UnexpectedValue(Me._regionPlace) End Select MyBase.NoteRead(variable) CheckCaptured(variable) End If End Sub Protected Overrides Sub NoteWrite(variable As Symbol, value As BoundExpression) If IsCompilerGeneratedTempLocal(variable) Then MyBase.NoteWrite(variable, value) Else Select Case Me._regionPlace Case RegionPlace.Before, RegionPlace.After _writtenOutside.Add(variable) Case RegionPlace.Inside _writtenInside.Add(variable) Case Else Throw ExceptionUtilities.UnexpectedValue(Me._regionPlace) End Select MyBase.NoteWrite(variable, value) CheckCaptured(variable) End If End Sub ' range variables are only returned in the captured set if inside the region Private Sub NoteCaptured(variable As Symbol) If _regionPlace = RegionPlace.Inside Then _capturedInside.Add(variable) _captured.Add(variable) ElseIf variable.Kind <> SymbolKind.RangeVariable Then _capturedOutside.Add(variable) _captured.Add(variable) End If End Sub Protected Overrides Sub NoteRead(fieldAccess As BoundFieldAccess) MyBase.NoteRead(fieldAccess) If (Me._regionPlace <> RegionPlace.Inside AndAlso fieldAccess.Syntax.Span.Contains(_region)) Then NoteReceiverRead(fieldAccess) End Sub Protected Overrides Sub NoteWrite(node As BoundExpression, value As BoundExpression) MyBase.NoteWrite(node, value) If node.Kind = BoundKind.FieldAccess Then NoteReceiverWritten(CType(node, BoundFieldAccess)) End Sub Private Sub NoteReceiverRead(fieldAccess As BoundFieldAccess) NoteReceiverReadOrWritten(fieldAccess, Me._readInside) End Sub Private Sub NoteReceiverWritten(fieldAccess As BoundFieldAccess) NoteReceiverReadOrWritten(fieldAccess, Me._writtenInside) End Sub Private Sub NoteReceiverReadOrWritten(fieldAccess As BoundFieldAccess, readOrWritten As HashSet(Of Symbol)) If fieldAccess.FieldSymbol.IsShared Then Return If fieldAccess.FieldSymbol.ContainingType.IsReferenceType Then Return Dim receiver = fieldAccess.ReceiverOpt If receiver Is Nothing Then Return Dim receiverSyntax = receiver.Syntax If receiverSyntax Is Nothing Then Return Select Case receiver.Kind Case BoundKind.Local If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundLocal).LocalSymbol) Case BoundKind.MeReference If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(Me.MeParameter) Case BoundKind.MyBaseReference If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(Me.MeParameter) Case BoundKind.Parameter If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundParameter).ParameterSymbol) Case BoundKind.RangeVariable If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundRangeVariable).RangeVariable) Case BoundKind.FieldAccess If receiver.Type.IsStructureType AndAlso receiverSyntax.Span.OverlapsWith(_region) Then NoteReceiverReadOrWritten(CType(receiver, BoundFieldAccess), readOrWritten) End Select End Sub Private Shared Function IsCompilerGeneratedTempLocal(variable As Symbol) As Boolean Return TypeOf (variable) Is SynthesizedLocal End Function Private Sub CheckCaptured(variable As Symbol) ' Query range variables are read-only, even if they are captured at the end, they are ' effectively captured ByValue, so IDE probably doesn't have to know about the capture ' at all. Select Case variable.Kind Case SymbolKind.Local Dim local = DirectCast(variable, LocalSymbol) If Not local.IsConst AndAlso Me._currentMethodOrLambda <> local.ContainingSymbol Then Me.NoteCaptured(local) End If Case SymbolKind.Parameter Dim param = DirectCast(variable, ParameterSymbol) If Me._currentMethodOrLambda <> param.ContainingSymbol Then Me.NoteCaptured(param) End If Case SymbolKind.RangeVariable Dim range = DirectCast(variable, RangeVariableSymbol) If Me._currentMethodOrLambda <> range.ContainingSymbol AndAlso Me._currentQueryLambda IsNot Nothing AndAlso ' might be Nothing in error scenarios (Me._currentMethodOrLambda <> Me._currentQueryLambda.LambdaSymbol OrElse Not Me._currentQueryLambda.RangeVariables.Contains(range)) Then Me.NoteCaptured(range) ' Range variables only captured if in region End If End Select End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode Dim previousMethod = Me._currentMethodOrLambda Me._currentMethodOrLambda = node.LambdaSymbol Dim result = MyBase.VisitLambda(node) Me._currentMethodOrLambda = previousMethod Return result End Function Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode Dim previousMethod = Me._currentMethodOrLambda Me._currentMethodOrLambda = node.LambdaSymbol Dim previousQueryLambda = Me._currentQueryLambda Me._currentQueryLambda = node Dim result = MyBase.VisitQueryLambda(node) Me._currentMethodOrLambda = previousMethod Me._currentQueryLambda = previousQueryLambda Return result End Function Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode If Not node.WasCompilerGenerated AndAlso node.RangeVariableOpt IsNot Nothing Then ' Adding range variables into a scope, note write for them. Debug.Assert(node.RangeVariables.Length = 1) NoteWrite(node.RangeVariableOpt, Nothing) End If VisitRvalue(node.Source) Return Nothing End Function Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode If Not node.WasCompilerGenerated Then NoteWrite(node.RangeVariable, Nothing) End If VisitRvalue(node.Value) Return Nothing End Function Private Overloads Function Analyze() As Boolean Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) _currentMethodOrLambda = symbol 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.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records reads and writes of all variables, both inside and outside the region. ''' </summary> Friend Class ReadWriteWalker Inherits AbstractRegionDataFlowPass Friend Overloads Shared Sub Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef readInside As IEnumerable(Of Symbol), ByRef writtenInside As IEnumerable(Of Symbol), ByRef readOutside As IEnumerable(Of Symbol), ByRef writtenOutside As IEnumerable(Of Symbol), ByRef captured As IEnumerable(Of Symbol), ByRef capturedInside As IEnumerable(Of Symbol), ByRef capturedOutside As IEnumerable(Of Symbol)) Dim walker = New ReadWriteWalker(info, region) Try If walker.Analyze() Then readInside = walker._readInside writtenInside = walker._writtenInside readOutside = walker._readOutside writtenOutside = walker._writtenOutside captured = walker._captured capturedInside = walker._capturedInside capturedOutside = walker._capturedOutside Else readInside = Enumerable.Empty(Of Symbol)() writtenInside = readInside readOutside = readInside writtenOutside = readInside captured = readInside capturedInside = readInside capturedOutside = readInside End If Finally walker.Free() End Try End Sub Private ReadOnly _readInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _writtenInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _readOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _writtenOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _captured As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _capturedInside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private ReadOnly _capturedOutside As HashSet(Of Symbol) = New HashSet(Of Symbol)() Private _currentMethodOrLambda As Symbol Private _currentQueryLambda As BoundQueryLambda Protected Overrides Sub NoteRead(variable As Symbol) If IsCompilerGeneratedTempLocal(variable) Then MyBase.NoteRead(variable) Else Select Case Me._regionPlace Case RegionPlace.Before, RegionPlace.After _readOutside.Add(variable) Case RegionPlace.Inside _readInside.Add(variable) Case Else Throw ExceptionUtilities.UnexpectedValue(Me._regionPlace) End Select MyBase.NoteRead(variable) CheckCaptured(variable) End If End Sub Protected Overrides Sub NoteWrite(variable As Symbol, value As BoundExpression) If IsCompilerGeneratedTempLocal(variable) Then MyBase.NoteWrite(variable, value) Else Select Case Me._regionPlace Case RegionPlace.Before, RegionPlace.After _writtenOutside.Add(variable) Case RegionPlace.Inside _writtenInside.Add(variable) Case Else Throw ExceptionUtilities.UnexpectedValue(Me._regionPlace) End Select MyBase.NoteWrite(variable, value) CheckCaptured(variable) End If End Sub ' range variables are only returned in the captured set if inside the region Private Sub NoteCaptured(variable As Symbol) If _regionPlace = RegionPlace.Inside Then _capturedInside.Add(variable) _captured.Add(variable) ElseIf variable.Kind <> SymbolKind.RangeVariable Then _capturedOutside.Add(variable) _captured.Add(variable) End If End Sub Protected Overrides Sub NoteRead(fieldAccess As BoundFieldAccess) MyBase.NoteRead(fieldAccess) If (Me._regionPlace <> RegionPlace.Inside AndAlso fieldAccess.Syntax.Span.Contains(_region)) Then NoteReceiverRead(fieldAccess) End Sub Protected Overrides Sub NoteWrite(node As BoundExpression, value As BoundExpression) MyBase.NoteWrite(node, value) If node.Kind = BoundKind.FieldAccess Then NoteReceiverWritten(CType(node, BoundFieldAccess)) End Sub Private Sub NoteReceiverRead(fieldAccess As BoundFieldAccess) NoteReceiverReadOrWritten(fieldAccess, Me._readInside) End Sub Private Sub NoteReceiverWritten(fieldAccess As BoundFieldAccess) NoteReceiverReadOrWritten(fieldAccess, Me._writtenInside) End Sub Private Sub NoteReceiverReadOrWritten(fieldAccess As BoundFieldAccess, readOrWritten As HashSet(Of Symbol)) If fieldAccess.FieldSymbol.IsShared Then Return If fieldAccess.FieldSymbol.ContainingType.IsReferenceType Then Return Dim receiver = fieldAccess.ReceiverOpt If receiver Is Nothing Then Return Dim receiverSyntax = receiver.Syntax If receiverSyntax Is Nothing Then Return Select Case receiver.Kind Case BoundKind.Local If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundLocal).LocalSymbol) Case BoundKind.MeReference If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(Me.MeParameter) Case BoundKind.MyBaseReference If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(Me.MeParameter) Case BoundKind.Parameter If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundParameter).ParameterSymbol) Case BoundKind.RangeVariable If _region.Contains(receiverSyntax.Span) Then readOrWritten.Add(CType(receiver, BoundRangeVariable).RangeVariable) Case BoundKind.FieldAccess If receiver.Type.IsStructureType AndAlso receiverSyntax.Span.OverlapsWith(_region) Then NoteReceiverReadOrWritten(CType(receiver, BoundFieldAccess), readOrWritten) End Select End Sub Private Shared Function IsCompilerGeneratedTempLocal(variable As Symbol) As Boolean Return TypeOf (variable) Is SynthesizedLocal End Function Private Sub CheckCaptured(variable As Symbol) ' Query range variables are read-only, even if they are captured at the end, they are ' effectively captured ByValue, so IDE probably doesn't have to know about the capture ' at all. Select Case variable.Kind Case SymbolKind.Local Dim local = DirectCast(variable, LocalSymbol) If Not local.IsConst AndAlso Me._currentMethodOrLambda <> local.ContainingSymbol Then Me.NoteCaptured(local) End If Case SymbolKind.Parameter Dim param = DirectCast(variable, ParameterSymbol) If Me._currentMethodOrLambda <> param.ContainingSymbol Then Me.NoteCaptured(param) End If Case SymbolKind.RangeVariable Dim range = DirectCast(variable, RangeVariableSymbol) If Me._currentMethodOrLambda <> range.ContainingSymbol AndAlso Me._currentQueryLambda IsNot Nothing AndAlso ' might be Nothing in error scenarios (Me._currentMethodOrLambda <> Me._currentQueryLambda.LambdaSymbol OrElse Not Me._currentQueryLambda.RangeVariables.Contains(range)) Then Me.NoteCaptured(range) ' Range variables only captured if in region End If End Select End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode Dim previousMethod = Me._currentMethodOrLambda Me._currentMethodOrLambda = node.LambdaSymbol Dim result = MyBase.VisitLambda(node) Me._currentMethodOrLambda = previousMethod Return result End Function Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode Dim previousMethod = Me._currentMethodOrLambda Me._currentMethodOrLambda = node.LambdaSymbol Dim previousQueryLambda = Me._currentQueryLambda Me._currentQueryLambda = node Dim result = MyBase.VisitQueryLambda(node) Me._currentMethodOrLambda = previousMethod Me._currentQueryLambda = previousQueryLambda Return result End Function Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode If Not node.WasCompilerGenerated AndAlso node.RangeVariableOpt IsNot Nothing Then ' Adding range variables into a scope, note write for them. Debug.Assert(node.RangeVariables.Length = 1) NoteWrite(node.RangeVariableOpt, Nothing) End If VisitRvalue(node.Source) Return Nothing End Function Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode If Not node.WasCompilerGenerated Then NoteWrite(node.RangeVariable, Nothing) End If VisitRvalue(node.Value) Return Nothing End Function Private Overloads Function Analyze() As Boolean Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) _currentMethodOrLambda = symbol End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegate_ParameterSymbol.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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private NotInheritable Class AnonymousTypeOrDelegateParameterSymbol Inherits SynthesizedParameterSymbol Public ReadOnly CorrespondingInvokeParameterOrProperty As Integer Public Sub New( container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, Optional correspondingInvokeParameterOrProperty As Integer = -1 ) MyBase.New(container, type, ordinal, isByRef, name) Me.CorrespondingInvokeParameterOrProperty = correspondingInvokeParameterOrProperty End Sub Public Overrides ReadOnly Property MetadataName As String Get If CorrespondingInvokeParameterOrProperty <> -1 Then Return DirectCast(_container.ContainingSymbol, AnonymousTypeOrDelegateTemplateSymbol).GetAdjustedName(CorrespondingInvokeParameterOrProperty) End If Return MyBase.MetadataName End Get End Property 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.Generic Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private NotInheritable Class AnonymousTypeOrDelegateParameterSymbol Inherits SynthesizedParameterSymbol Public ReadOnly CorrespondingInvokeParameterOrProperty As Integer Public Sub New( container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, Optional correspondingInvokeParameterOrProperty As Integer = -1 ) MyBase.New(container, type, ordinal, isByRef, name) Me.CorrespondingInvokeParameterOrProperty = correspondingInvokeParameterOrProperty End Sub Public Overrides ReadOnly Property MetadataName As String Get If CorrespondingInvokeParameterOrProperty <> -1 Then Return DirectCast(_container.ContainingSymbol, AnonymousTypeOrDelegateTemplateSymbol).GetAdjustedName(CorrespondingInvokeParameterOrProperty) End If Return MyBase.MetadataName End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/Test2/IntelliSense/SignatureHelpControllerTests.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.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Projection Imports Moq Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class SignatureHelpControllerTests <WpfFact> Public Sub InvokeSignatureHelpWithoutDocumentShouldNotStartNewSession() Dim emptyProvider = New Mock(Of IDocumentProvider)(MockBehavior.Strict) emptyProvider.Setup(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken))).Returns(DirectCast(Nothing, Document)) Dim controller As Controller = CreateController(documentProvider:=emptyProvider) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) controller.WaitForController() Assert.Equal(0, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> Public Sub InvokeSignatureHelpWithDocumentShouldStartNewSession() Dim controller = CreateController() GetMocks(controller).Presenter.Verify(Function(p) p.CreateSession(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of ISignatureHelpSession)), Times.Once) End Sub <WpfFact> Public Sub EmptyModelShouldStopSession() Dim presenterSession = New Mock(Of ISignatureHelpPresenterSession)(MockBehavior.Strict) presenterSession.Setup(Sub(p) p.Dismiss()) Dim controller = CreateController(presenterSession:=presenterSession, items:={}, waitForPresentation:=True) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub UpKeyShouldDismissWhenThereIsOnlyOneItem() Dim controller = CreateController(items:=CreateItems(1), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub UpKeyShouldNavigateWhenThereAreMultipleItems() Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectPreviousItem()) Dim handled = controller.TryHandleUpKey() Assert.True(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.SelectPreviousItem(), Times.Once) End Sub <WpfFact> <WorkItem(985007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985007")> Public Sub UpKeyShouldNotCrashWhenSessionIsDismissed() ' Create a provider that will return an empty state when queried the second time Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.IsTriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.IsRetriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing))) Dim controller = CreateController(provider:=slowProvider.Object, waitForPresentation:=True) ' Now force an update to the model that will result in stopping the session slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(Of SignatureHelpItems)(Nothing)) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), " "c), Sub() GetMocks(controller).Buffer.Insert(0, " "), TestCommandExecutionContext.Create()) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() ' this will block on the model being updated which should dismiss the session Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Sub DownKeyShouldNotBlockOnModelComputation() Dim mre = New ManualResetEvent(False) Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=False) Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() mre.WaitOne() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) GetMocks(controller).PresenterSession.Setup(Function(p) p.EditorSessionIsActive).Returns(False) Dim handled = controller.TryHandleDownKey() Assert.False(handled) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Sub UpKeyShouldNotBlockOnModelComputation() Dim mre = New ManualResetEvent(False) Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=False) Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() mre.WaitOne() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) GetMocks(controller).PresenterSession.Setup(Function(p) p.EditorSessionIsActive).Returns(False) Dim handled = controller.TryHandleUpKey() Assert.False(handled) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Async Function UpKeyShouldBlockOnRecomputationAfterPresentation() As Task Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim threadingContext = exportProvider.GetExportedValue(Of IThreadingContext)() Dim worker = Async Function() Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.IsTriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.IsRetriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing))) Await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync() Dim controller = CreateController(provider:=slowProvider.Object, waitForPresentation:=True) ' Update session so that providers are requeried. ' SlowProvider now blocks on the checkpoint's task. Dim checkpoint = New Checkpoint() slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() checkpoint.Task.Wait() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 2), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) Await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync() DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), " "c), Sub() GetMocks(controller).Buffer.Insert(0, " "), TestCommandExecutionContext.Create()) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectPreviousItem()) Dim handled = threadingContext.JoinableTaskFactory.RunAsync(Async Function() Await Task.Yield() ' Send the controller an up key, which should block on the computation Return controller.TryHandleUpKey() End Function) checkpoint.Release() ' Allow slowprovider to finish Await handled.JoinAsync().ConfigureAwait(False) ' We expect 2 calls to the presenter (because we had an existing presentation session when we started the second computation). Assert.True(handled.Task.Result) GetMocks(controller).PresenterSession.Verify(Sub(p) p.PresentItems(It.IsAny(Of ITrackingSpan), It.IsAny(Of IList(Of SignatureHelpItem)), It.IsAny(Of SignatureHelpItem), It.IsAny(Of Integer?)), Times.Exactly(2)) End Function Await worker().ConfigureAwait(False) End Function <WpfFact> Public Sub DownKeyShouldNavigateWhenThereAreMultipleItems() Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectNextItem()) Dim handled = controller.TryHandleDownKey() Assert.True(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.SelectNextItem(), Times.Once) End Sub <WorkItem(1181, "https://github.com/dotnet/roslyn/issues/1181")> <WpfFact> Public Sub UpAndDownKeysShouldStillNavigateWhenDuplicateItemsAreFiltered() Dim item = CreateItems(1).Single() Dim controller = CreateController(items:={item, item}, waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub CaretMoveWithActiveSessionShouldRecomputeModel() Dim controller = CreateController(waitForPresentation:=True) Mock.Get(GetMocks(controller).View.Object.Caret).Raise(Sub(c) AddHandler c.PositionChanged, Nothing, New CaretPositionChangedEventArgs(Nothing, Nothing, Nothing)) controller.WaitForController() ' GetItemsAsync is called once initially, and then once as a result of handling the PositionChanged event Assert.Equal(2, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> Public Sub RetriggerActiveSessionOnClosingBrace() Dim controller = CreateController(waitForPresentation:=True) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), ")"c), Sub() GetMocks(controller).Buffer.Insert(0, ")"), TestCommandExecutionContext.Create()) controller.WaitForController() ' GetItemsAsync is called once initially, and then once as a result of handling the typechar command Assert.Equal(2, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> <WorkItem(959116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/959116")> Public Sub TypingNonTriggerCharacterShouldNotRequestDocument() Dim controller = CreateController(triggerSession:=False) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), "a"c), Sub() GetMocks(controller).Buffer.Insert(0, "a"), TestCommandExecutionContext.Create()) GetMocks(controller).DocumentProvider.Verify(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken)), Times.Never) End Sub Private Shared ReadOnly s_controllerMocksMap As New ConditionalWeakTable(Of Controller, ControllerMocks) Private Shared Function GetMocks(controller As Controller) As ControllerMocks Dim result As ControllerMocks = Nothing Roslyn.Utilities.Contract.ThrowIfFalse(s_controllerMocksMap.TryGetValue(controller, result)) Return result End Function Private Shared Function CreateController(Optional documentProvider As Mock(Of IDocumentProvider) = Nothing, Optional presenterSession As Mock(Of ISignatureHelpPresenterSession) = Nothing, Optional items As IList(Of SignatureHelpItem) = Nothing, Optional provider As ISignatureHelpProvider = Nothing, Optional waitForPresentation As Boolean = False, Optional triggerSession As Boolean = True) As Controller Dim document As Document = (Function() Dim workspace = TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#"> <Document> </Document> </Project> </Workspace>) Return workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id) End Function)() Dim threadingContext = DirectCast(document.Project.Solution.Workspace, TestWorkspace).GetService(Of IThreadingContext) Dim bufferFactory As ITextBufferFactoryService = DirectCast(document.Project.Solution.Workspace, TestWorkspace).GetService(Of ITextBufferFactoryService) Dim buffer = bufferFactory.CreateTextBuffer() Dim view = CreateMockTextView(buffer) Dim asyncListener = AsynchronousOperationListenerProvider.NullListener If documentProvider Is Nothing Then documentProvider = New Mock(Of IDocumentProvider)(MockBehavior.Strict) documentProvider.Setup(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken))).Returns(document) End If If provider Is Nothing Then items = If(items, CreateItems(1)) provider = New MockSignatureHelpProvider(items) End If Dim presenter = New Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession))(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock} presenterSession = If(presenterSession, New Mock(Of ISignatureHelpPresenterSession)(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock}) presenter.Setup(Function(p) p.CreateSession(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of ISignatureHelpSession))).Returns(presenterSession.Object) presenterSession.Setup(Sub(p) p.PresentItems(It.IsAny(Of ITrackingSpan), It.IsAny(Of IList(Of SignatureHelpItem)), It.IsAny(Of SignatureHelpItem), It.IsAny(Of Integer?))) _ .Callback(Sub() presenterSession.SetupGet(Function(p) p.EditorSessionIsActive).Returns(True)) Dim mockCompletionBroker = New Mock(Of IAsyncCompletionBroker)(MockBehavior.Strict) mockCompletionBroker.Setup(Function(b) b.GetSession(It.IsAny(Of ITextView))).Returns(DirectCast(Nothing, IAsyncCompletionSession)) Dim controller = New Controller( threadingContext, view.Object, buffer, presenter.Object, asyncListener, documentProvider.Object, {provider}, mockCompletionBroker.Object) s_controllerMocksMap.Add(controller, New ControllerMocks( view, buffer, presenter, presenterSession, asyncListener, documentProvider, TryCast(provider, MockSignatureHelpProvider))) If triggerSession Then DirectCast(controller, IChainedCommandHandler(Of InvokeSignatureHelpCommandArgs)).ExecuteCommand( New InvokeSignatureHelpCommandArgs(view.Object, buffer), Nothing, TestCommandExecutionContext.Create()) If waitForPresentation Then controller.WaitForController() End If End If Return controller End Function Private Shared Function CreateItems(count As Integer) As IList(Of SignatureHelpItem) Return Enumerable.Range(0, count).Select(Function(i) New SignatureHelpItem(isVariadic:=False, documentationFactory:=Nothing, prefixParts:=New List(Of TaggedText), separatorParts:={}, suffixParts:={}, parameters:={}, descriptionParts:={})).ToList() End Function Friend Class MockSignatureHelpProvider Implements ISignatureHelpProvider Private ReadOnly _items As IList(Of SignatureHelpItem) Public Sub New(items As IList(Of SignatureHelpItem)) Me._items = items End Sub Public Property GetItemsCount As Integer Public Function GetItemsAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems) Implements ISignatureHelpProvider.GetItemsAsync GetItemsCount += 1 Return Task.FromResult(If(_items.Any(), New SignatureHelpItems(_items, TextSpan.FromBounds(position, position), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing), Nothing)) End Function Public Function IsTriggerCharacter(ch As Char) As Boolean Implements ISignatureHelpProvider.IsTriggerCharacter Return ch = "("c End Function Public Function IsRetriggerCharacter(ch As Char) As Boolean Implements ISignatureHelpProvider.IsRetriggerCharacter Return ch = ")"c End Function End Class Private Shared Function CreateMockTextView(buffer As ITextBuffer) As Mock(Of ITextView) Dim caret = New Mock(Of ITextCaret)(MockBehavior.Strict) caret.Setup(Function(c) c.Position).Returns(Function() New CaretPosition(New VirtualSnapshotPoint(buffer.CurrentSnapshot, buffer.CurrentSnapshot.Length), CreateMock(Of IMappingPoint), PositionAffinity.Predecessor)) Dim view = New Mock(Of ITextView)(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock} view.Setup(Function(v) v.Caret).Returns(caret.Object) view.Setup(Function(v) v.TextBuffer).Returns(buffer) view.Setup(Function(v) v.TextSnapshot).Returns(buffer.CurrentSnapshot) Dim bufferGraph = New Mock(Of IBufferGraph)(MockBehavior.Strict) view.Setup(Function(v) v.BufferGraph).Returns(bufferGraph.Object) Return view End Function Private Shared Function CreateMock(Of T As Class)() As T Dim mock = New Mock(Of T)(MockBehavior.Strict) Return mock.Object End Function Private Class ControllerMocks Public ReadOnly View As Mock(Of ITextView) Public ReadOnly Buffer As ITextBuffer Public ReadOnly Presenter As Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)) Public ReadOnly PresenterSession As Mock(Of ISignatureHelpPresenterSession) Public ReadOnly AsyncListener As IAsynchronousOperationListener Public ReadOnly DocumentProvider As Mock(Of IDocumentProvider) Public ReadOnly Provider As MockSignatureHelpProvider Public Sub New(view As Mock(Of ITextView), buffer As ITextBuffer, presenter As Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)), presenterSession As Mock(Of ISignatureHelpPresenterSession), asyncListener As IAsynchronousOperationListener, documentProvider As Mock(Of IDocumentProvider), provider As MockSignatureHelpProvider) Me.View = view Me.Buffer = buffer Me.Presenter = presenter Me.PresenterSession = presenterSession Me.AsyncListener = asyncListener Me.DocumentProvider = documentProvider Me.Provider = provider 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.Runtime.CompilerServices Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Projection Imports Moq Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class SignatureHelpControllerTests <WpfFact> Public Sub InvokeSignatureHelpWithoutDocumentShouldNotStartNewSession() Dim emptyProvider = New Mock(Of IDocumentProvider)(MockBehavior.Strict) emptyProvider.Setup(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken))).Returns(DirectCast(Nothing, Document)) Dim controller As Controller = CreateController(documentProvider:=emptyProvider) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) controller.WaitForController() Assert.Equal(0, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> Public Sub InvokeSignatureHelpWithDocumentShouldStartNewSession() Dim controller = CreateController() GetMocks(controller).Presenter.Verify(Function(p) p.CreateSession(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of ISignatureHelpSession)), Times.Once) End Sub <WpfFact> Public Sub EmptyModelShouldStopSession() Dim presenterSession = New Mock(Of ISignatureHelpPresenterSession)(MockBehavior.Strict) presenterSession.Setup(Sub(p) p.Dismiss()) Dim controller = CreateController(presenterSession:=presenterSession, items:={}, waitForPresentation:=True) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub UpKeyShouldDismissWhenThereIsOnlyOneItem() Dim controller = CreateController(items:=CreateItems(1), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub UpKeyShouldNavigateWhenThereAreMultipleItems() Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectPreviousItem()) Dim handled = controller.TryHandleUpKey() Assert.True(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.SelectPreviousItem(), Times.Once) End Sub <WpfFact> <WorkItem(985007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985007")> Public Sub UpKeyShouldNotCrashWhenSessionIsDismissed() ' Create a provider that will return an empty state when queried the second time Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.IsTriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.IsRetriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing))) Dim controller = CreateController(provider:=slowProvider.Object, waitForPresentation:=True) ' Now force an update to the model that will result in stopping the session slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(Of SignatureHelpItems)(Nothing)) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), " "c), Sub() GetMocks(controller).Buffer.Insert(0, " "), TestCommandExecutionContext.Create()) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() ' this will block on the model being updated which should dismiss the session Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Sub DownKeyShouldNotBlockOnModelComputation() Dim mre = New ManualResetEvent(False) Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=False) Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() mre.WaitOne() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) GetMocks(controller).PresenterSession.Setup(Function(p) p.EditorSessionIsActive).Returns(False) Dim handled = controller.TryHandleDownKey() Assert.False(handled) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Sub UpKeyShouldNotBlockOnModelComputation() Dim mre = New ManualResetEvent(False) Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=False) Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() mre.WaitOne() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) GetMocks(controller).PresenterSession.Setup(Function(p) p.EditorSessionIsActive).Returns(False) Dim handled = controller.TryHandleUpKey() Assert.False(handled) End Sub <WpfFact> <WorkItem(179726, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workItems?id=179726&_a=edit")> Public Async Function UpKeyShouldBlockOnRecomputationAfterPresentation() As Task Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim threadingContext = exportProvider.GetExportedValue(Of IThreadingContext)() Dim worker = Async Function() Dim slowProvider = New Mock(Of ISignatureHelpProvider)(MockBehavior.Strict) slowProvider.Setup(Function(p) p.IsTriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.IsRetriggerCharacter(" "c)).Returns(True) slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 0), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing))) Await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync() Dim controller = CreateController(provider:=slowProvider.Object, waitForPresentation:=True) ' Update session so that providers are requeried. ' SlowProvider now blocks on the checkpoint's task. Dim checkpoint = New Checkpoint() slowProvider.Setup(Function(p) p.GetItemsAsync(It.IsAny(Of Document), It.IsAny(Of Integer), It.IsAny(Of SignatureHelpTriggerInfo), It.IsAny(Of CancellationToken))) _ .Returns(Function() checkpoint.Task.Wait() Return Task.FromResult(New SignatureHelpItems(CreateItems(2), TextSpan.FromBounds(0, 2), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing)) End Function) Await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync() DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), " "c), Sub() GetMocks(controller).Buffer.Insert(0, " "), TestCommandExecutionContext.Create()) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectPreviousItem()) Dim handled = threadingContext.JoinableTaskFactory.RunAsync(Async Function() Await Task.Yield() ' Send the controller an up key, which should block on the computation Return controller.TryHandleUpKey() End Function) checkpoint.Release() ' Allow slowprovider to finish Await handled.JoinAsync().ConfigureAwait(False) ' We expect 2 calls to the presenter (because we had an existing presentation session when we started the second computation). Assert.True(handled.Task.Result) GetMocks(controller).PresenterSession.Verify(Sub(p) p.PresentItems(It.IsAny(Of ITrackingSpan), It.IsAny(Of IList(Of SignatureHelpItem)), It.IsAny(Of SignatureHelpItem), It.IsAny(Of Integer?)), Times.Exactly(2)) End Function Await worker().ConfigureAwait(False) End Function <WpfFact> Public Sub DownKeyShouldNavigateWhenThereAreMultipleItems() Dim controller = CreateController(items:=CreateItems(2), waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.SelectNextItem()) Dim handled = controller.TryHandleDownKey() Assert.True(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.SelectNextItem(), Times.Once) End Sub <WorkItem(1181, "https://github.com/dotnet/roslyn/issues/1181")> <WpfFact> Public Sub UpAndDownKeysShouldStillNavigateWhenDuplicateItemsAreFiltered() Dim item = CreateItems(1).Single() Dim controller = CreateController(items:={item, item}, waitForPresentation:=True) GetMocks(controller).PresenterSession.Setup(Sub(p) p.Dismiss()) Dim handled = controller.TryHandleUpKey() Assert.False(handled) GetMocks(controller).PresenterSession.Verify(Sub(p) p.Dismiss(), Times.Once) End Sub <WpfFact> Public Sub CaretMoveWithActiveSessionShouldRecomputeModel() Dim controller = CreateController(waitForPresentation:=True) Mock.Get(GetMocks(controller).View.Object.Caret).Raise(Sub(c) AddHandler c.PositionChanged, Nothing, New CaretPositionChangedEventArgs(Nothing, Nothing, Nothing)) controller.WaitForController() ' GetItemsAsync is called once initially, and then once as a result of handling the PositionChanged event Assert.Equal(2, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> Public Sub RetriggerActiveSessionOnClosingBrace() Dim controller = CreateController(waitForPresentation:=True) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), ")"c), Sub() GetMocks(controller).Buffer.Insert(0, ")"), TestCommandExecutionContext.Create()) controller.WaitForController() ' GetItemsAsync is called once initially, and then once as a result of handling the typechar command Assert.Equal(2, GetMocks(controller).Provider.GetItemsCount) End Sub <WpfFact> <WorkItem(959116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/959116")> Public Sub TypingNonTriggerCharacterShouldNotRequestDocument() Dim controller = CreateController(triggerSession:=False) DirectCast(controller, IChainedCommandHandler(Of TypeCharCommandArgs)).ExecuteCommand( New TypeCharCommandArgs(CreateMock(Of ITextView), CreateMock(Of ITextBuffer), "a"c), Sub() GetMocks(controller).Buffer.Insert(0, "a"), TestCommandExecutionContext.Create()) GetMocks(controller).DocumentProvider.Verify(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken)), Times.Never) End Sub Private Shared ReadOnly s_controllerMocksMap As New ConditionalWeakTable(Of Controller, ControllerMocks) Private Shared Function GetMocks(controller As Controller) As ControllerMocks Dim result As ControllerMocks = Nothing Roslyn.Utilities.Contract.ThrowIfFalse(s_controllerMocksMap.TryGetValue(controller, result)) Return result End Function Private Shared Function CreateController(Optional documentProvider As Mock(Of IDocumentProvider) = Nothing, Optional presenterSession As Mock(Of ISignatureHelpPresenterSession) = Nothing, Optional items As IList(Of SignatureHelpItem) = Nothing, Optional provider As ISignatureHelpProvider = Nothing, Optional waitForPresentation As Boolean = False, Optional triggerSession As Boolean = True) As Controller Dim document As Document = (Function() Dim workspace = TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#"> <Document> </Document> </Project> </Workspace>) Return workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id) End Function)() Dim threadingContext = DirectCast(document.Project.Solution.Workspace, TestWorkspace).GetService(Of IThreadingContext) Dim bufferFactory As ITextBufferFactoryService = DirectCast(document.Project.Solution.Workspace, TestWorkspace).GetService(Of ITextBufferFactoryService) Dim buffer = bufferFactory.CreateTextBuffer() Dim view = CreateMockTextView(buffer) Dim asyncListener = AsynchronousOperationListenerProvider.NullListener If documentProvider Is Nothing Then documentProvider = New Mock(Of IDocumentProvider)(MockBehavior.Strict) documentProvider.Setup(Function(p) p.GetDocument(It.IsAny(Of ITextSnapshot), It.IsAny(Of CancellationToken))).Returns(document) End If If provider Is Nothing Then items = If(items, CreateItems(1)) provider = New MockSignatureHelpProvider(items) End If Dim presenter = New Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession))(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock} presenterSession = If(presenterSession, New Mock(Of ISignatureHelpPresenterSession)(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock}) presenter.Setup(Function(p) p.CreateSession(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of ISignatureHelpSession))).Returns(presenterSession.Object) presenterSession.Setup(Sub(p) p.PresentItems(It.IsAny(Of ITrackingSpan), It.IsAny(Of IList(Of SignatureHelpItem)), It.IsAny(Of SignatureHelpItem), It.IsAny(Of Integer?))) _ .Callback(Sub() presenterSession.SetupGet(Function(p) p.EditorSessionIsActive).Returns(True)) Dim mockCompletionBroker = New Mock(Of IAsyncCompletionBroker)(MockBehavior.Strict) mockCompletionBroker.Setup(Function(b) b.GetSession(It.IsAny(Of ITextView))).Returns(DirectCast(Nothing, IAsyncCompletionSession)) Dim controller = New Controller( threadingContext, view.Object, buffer, presenter.Object, asyncListener, documentProvider.Object, {provider}, mockCompletionBroker.Object) s_controllerMocksMap.Add(controller, New ControllerMocks( view, buffer, presenter, presenterSession, asyncListener, documentProvider, TryCast(provider, MockSignatureHelpProvider))) If triggerSession Then DirectCast(controller, IChainedCommandHandler(Of InvokeSignatureHelpCommandArgs)).ExecuteCommand( New InvokeSignatureHelpCommandArgs(view.Object, buffer), Nothing, TestCommandExecutionContext.Create()) If waitForPresentation Then controller.WaitForController() End If End If Return controller End Function Private Shared Function CreateItems(count As Integer) As IList(Of SignatureHelpItem) Return Enumerable.Range(0, count).Select(Function(i) New SignatureHelpItem(isVariadic:=False, documentationFactory:=Nothing, prefixParts:=New List(Of TaggedText), separatorParts:={}, suffixParts:={}, parameters:={}, descriptionParts:={})).ToList() End Function Friend Class MockSignatureHelpProvider Implements ISignatureHelpProvider Private ReadOnly _items As IList(Of SignatureHelpItem) Public Sub New(items As IList(Of SignatureHelpItem)) Me._items = items End Sub Public Property GetItemsCount As Integer Public Function GetItemsAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems) Implements ISignatureHelpProvider.GetItemsAsync GetItemsCount += 1 Return Task.FromResult(If(_items.Any(), New SignatureHelpItems(_items, TextSpan.FromBounds(position, position), selectedItem:=0, argumentIndex:=0, argumentCount:=0, argumentName:=Nothing), Nothing)) End Function Public Function IsTriggerCharacter(ch As Char) As Boolean Implements ISignatureHelpProvider.IsTriggerCharacter Return ch = "("c End Function Public Function IsRetriggerCharacter(ch As Char) As Boolean Implements ISignatureHelpProvider.IsRetriggerCharacter Return ch = ")"c End Function End Class Private Shared Function CreateMockTextView(buffer As ITextBuffer) As Mock(Of ITextView) Dim caret = New Mock(Of ITextCaret)(MockBehavior.Strict) caret.Setup(Function(c) c.Position).Returns(Function() New CaretPosition(New VirtualSnapshotPoint(buffer.CurrentSnapshot, buffer.CurrentSnapshot.Length), CreateMock(Of IMappingPoint), PositionAffinity.Predecessor)) Dim view = New Mock(Of ITextView)(MockBehavior.Strict) With {.DefaultValue = DefaultValue.Mock} view.Setup(Function(v) v.Caret).Returns(caret.Object) view.Setup(Function(v) v.TextBuffer).Returns(buffer) view.Setup(Function(v) v.TextSnapshot).Returns(buffer.CurrentSnapshot) Dim bufferGraph = New Mock(Of IBufferGraph)(MockBehavior.Strict) view.Setup(Function(v) v.BufferGraph).Returns(bufferGraph.Object) Return view End Function Private Shared Function CreateMock(Of T As Class)() As T Dim mock = New Mock(Of T)(MockBehavior.Strict) Return mock.Object End Function Private Class ControllerMocks Public ReadOnly View As Mock(Of ITextView) Public ReadOnly Buffer As ITextBuffer Public ReadOnly Presenter As Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)) Public ReadOnly PresenterSession As Mock(Of ISignatureHelpPresenterSession) Public ReadOnly AsyncListener As IAsynchronousOperationListener Public ReadOnly DocumentProvider As Mock(Of IDocumentProvider) Public ReadOnly Provider As MockSignatureHelpProvider Public Sub New(view As Mock(Of ITextView), buffer As ITextBuffer, presenter As Mock(Of IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)), presenterSession As Mock(Of ISignatureHelpPresenterSession), asyncListener As IAsynchronousOperationListener, documentProvider As Mock(Of IDocumentProvider), provider As MockSignatureHelpProvider) Me.View = view Me.Buffer = buffer Me.Presenter = presenter Me.PresenterSession = presenterSession Me.AsyncListener = asyncListener Me.DocumentProvider = documentProvider Me.Provider = provider End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/EventHandling/RaiseEventKeywordRecommender.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.EventHandling ''' <summary> ''' Recommends the "RaiseEvent" keyword. ''' </summary> Friend Class RaiseEventKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsSingleLineStatementContext OrElse context.IsMultiLineStatementContext Then Return ImmutableArray.Create(New RecommendedKeyword("RaiseEvent", VBFeaturesResources.Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket)) ElseIf context.CanDeclareCustomEventAccessor(SyntaxKind.RaiseEventAccessorBlock) Then Return ImmutableArray.Create(New RecommendedKeyword("RaiseEvent", VBFeaturesResources.Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent)) Else Return ImmutableArray(Of RecommendedKeyword).Empty End If 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.EventHandling ''' <summary> ''' Recommends the "RaiseEvent" keyword. ''' </summary> Friend Class RaiseEventKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsSingleLineStatementContext OrElse context.IsMultiLineStatementContext Then Return ImmutableArray.Create(New RecommendedKeyword("RaiseEvent", VBFeaturesResources.Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket)) ElseIf context.CanDeclareCustomEventAccessor(SyntaxKind.RaiseEventAccessorBlock) Then Return ImmutableArray.Create(New RecommendedKeyword("RaiseEvent", VBFeaturesResources.Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent)) Else Return ImmutableArray(Of RecommendedKeyword).Empty End If End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasicTest/NavigateTo/NavigateToTests.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.Editor.Implementation.NavigateTo Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Language.NavigateTo.Interfaces Imports Microsoft.VisualStudio.Text.PatternMatching Imports Roslyn.Test.EditorUtilities.NavigateTo #Disable Warning BC40000 ' MatchKind is obsolete Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NavigateTo <Trait(Traits.Feature, Traits.Features.NavigateTo)> Public Class NavigateToTests Inherits AbstractNavigateToTests Protected Overrides ReadOnly Property Language As String = "vb" Protected Overrides Function CreateWorkspace(content As String, exportProvider As ExportProvider) As TestWorkspace Return TestWorkspace.CreateVisualBasic(content, exportProvider:=exportProvider) End Function <Theory> <CombinatorialData> Public Async Function TestNoItemsForEmptyFile(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "", Async Function(w) Assert.Empty(Await _aggregator.GetItemsAsync("Hello")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class [Class] End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("class")).Single() VerifyNavigateToResultItem(item, "Class", "[|Class|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) item = (Await _aggregator.GetItemsAsync("[class]")).Single() VerifyNavigateToResultItem(item, "Class", "[|Class|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindNestedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Alpha Class Beta Class Gamma End Class End Class End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Gamma")).Single() VerifyNavigateToResultItem(item, "Gamma", "[|Gamma|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMemberInANestedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Alpha Class Beta Class Gamma Sub DoSomething() End Sub End Class End Class End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Alpha.Beta.Gamma", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindGenericConstrainedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo(Of M As IComparable) End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|](Of M)", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindGenericConstrainedMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo(Of M As IComparable) Public Sub Bar(Of T As IComparable)() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|](Of T)()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo(Of M)", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Public Class Goo Private a As Integer End Class Partial Class Goo Private b As Integer End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Goo")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClassInNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Bar Class Goo End Class End Namespace", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindStruct(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Structure Bar End Structure", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("B")).Single() VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Structure, Glyph.StructureInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindEnum(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Enum Colors Red Green Blue End Enum", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("C")).Single() VerifyNavigateToResultItem(item, "Colors", "[|C|]olors", PatternMatchKind.Prefix, NavigateToItemKind.Enum, Glyph.EnumInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindEnumMember(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Enum Colors Red Green Blue End Enum", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() VerifyNavigateToResultItem(item, "Green", "[|G|]reen", PatternMatchKind.Prefix, NavigateToItemKind.EnumItem, Glyph.EnumMemberPublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField1(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Ba")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField2(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("ba")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField3(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Assert.Empty(Await _aggregator.GetItemsAsync("ar")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimField(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private [string] As String End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("string")).Single() VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("[string]")).Single() VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindConstField(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Const bar As String = ""bar"" End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("bar")).Single() VerifyNavigateToResultItem(item, "bar", "[|bar|]", PatternMatchKind.Exact, NavigateToItemKind.Constant, Glyph.ConstantPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindIndexer(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private arr As Integer() Default Public Property Item(ByVal i As Integer) As Integer Get Return arr(i) End Get Set(ByVal value As Integer) arr(i) = value End Set End Property End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Item")).Single() VerifyNavigateToResultItem(item, "Item", "[|Item|](Integer)", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> <WorkItem(780993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780993")> Public Async Function TestFindEvent(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Public Event Bar as EventHandler End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]", PatternMatchKind.Exact, NavigateToItemKind.Event, Glyph.EventPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindNormalProperty(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Property Name As String Get Return String.Empty End Get Set(value As String) End Set End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Name")).Single() VerifyNavigateToResultItem(item, "Name", "[|Name|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindAutoImplementedProperty(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Property Name As String End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Name")).Single() VerifyNavigateToResultItem(item, "Name", "[|Name|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub DoSomething() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub [Sub]() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("sub")).Single() VerifyNavigateToResultItem(item, "Sub", "[|Sub|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("[sub]")).Single() VerifyNavigateToResultItem(item, "Sub", "[|Sub|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindParameterizedMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub DoSomething(ByVal i As Integer, s As String) End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(Integer, String)", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindConstructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Sub New() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single(Function(i) i.Kind = NavigateToItemKind.Method) VerifyNavigateToResultItem(item, "Goo", "[|Goo|].New()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindStaticConstructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Shared Sub New() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single(Function(i) i.Kind = NavigateToItemKind.Method) VerifyNavigateToResultItem(item, "Goo", "[|Goo|].New()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindDestructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Finalize")).Single() VerifyNavigateToResultItem(item, "Finalize", "[|Finalize|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodProtected, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("Dispose")).Single() VerifyNavigateToResultItem(item, "Dispose", "[|Dispose|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethods(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Partial Private Sub Bar() End Sub End Class Partial Class Goo Private Sub Bar() End Sub End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Bar")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethodDefinitionOnly(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Partial Private Sub Bar() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_1_2, "Goo", "test1.vb", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethodImplementationOnly(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Private Sub Bar() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindOverriddenMethods(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class BaseGoo Public Overridable Sub Bar() End Sub End Class Class DerivedGoo Inherits BaseGoo Public Overrides Sub Bar() MyBase.Bar() End Sub End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Bar")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern1(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("B.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern2(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { } Dim items = (Await _aggregator.GetItemsAsync("C.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern3(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("B.B.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern4(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("Baz.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern5(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("G.B.B.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern6(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) Dim items = (Await _aggregator.GetItemsAsync("F.F.B.B.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> <WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")> Public Async Function TestDottedPattern7(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz(of X, Y, Z) sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("Baz.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindInterface(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Public Interface IGoo End Interface", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("IG")).Single() VerifyNavigateToResultItem(item, "IGoo", "[|IG|]oo", PatternMatchKind.Prefix, NavigateToItemKind.Interface, Glyph.InterfacePublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindDelegateInNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Goo Delegate Sub DoStuff() End Namespace", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DoStuff")).Single() VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", PatternMatchKind.Exact, NavigateToItemKind.Delegate, Glyph.DelegateInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindLambdaExpression(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Dim sqr As Func(Of Integer, Integer) = Function(x) x*x End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("sqr")).Single() VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindModule(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Module ModuleTest End Module", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("MT")).Single() VerifyNavigateToResultItem(item, "ModuleTest", "[|M|]odule[|T|]est", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Module, Glyph.ModuleInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindLineContinuationMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Public Sub Bar(x as Integer, y as Integer) End Sub", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|](Integer, Integer)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindArray(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private itemArray as object() End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("itemArray")).Single VerifyNavigateToResultItem(item, "itemArray", "[|itemArray|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClassAndMethodWithSameName(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo End Class Class Test Private Sub Goo() End Sub End Class", Async Function(w) Dim expectedItems = New List(Of NavigateToItem) From { New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Goo", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Goo")).ToList() VerifyNavigateToResultItems(expectedItems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMethodNestedInGenericTypes(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class A(Of T) Class B Structure C(Of U) Sub M() End Sub End Structure End Class End Class", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("M")).Single VerifyNavigateToResultItem(item, "M", "[|M|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "A(Of T).B.C(Of U)", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindAbstractMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "MustInherit Class A Public MustOverride Sub M() End Class", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("M")).Single VerifyNavigateToResultItem(item, "M", "[|M|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "A", "Test")) End Function) End Function <WorkItem(1111131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1111131")> <Theory> <CombinatorialData> Public Async Function TestFindClassInNamespaceWithGlobalPrefix(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Global.MyNS Public Class C End Class End Namespace", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("C")).Single VerifyNavigateToResultItem(item, "C", "[|C|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <WorkItem(1121267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1121267")> <Theory> <CombinatorialData> Public Async Function TestFindClassInGlobalNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Global Public Class C(Of T) End Class End Namespace", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("C")).Single VerifyNavigateToResultItem(item, "C", "[|C|](Of T)", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <WorkItem(1834, "https://github.com/dotnet/roslyn/issues/1834")> <Theory> <CombinatorialData> Public Async Function TestConstructorNotParentedByTypeBlock(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Module Program End Module Public Sub New() End Sub", Async Function(w) Assert.Equal(0, (Await _aggregator.GetItemsAsync("New")).Count) Dim item = (Await _aggregator.GetItemsAsync("Program")).Single VerifyNavigateToResultItem(item, "Program", "[|Program|]", PatternMatchKind.Exact, NavigateToItemKind.Module, Glyph.ModuleInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestStartStopSanity(testHost As TestHost, composition As Composition) As Task ' Verify that multiple calls to start/stop don't blow up Await TestAsync(testHost, composition, "Public Class Goo End Class", Async Function(w) ' Do one query Assert.Single(Await _aggregator.GetItemsAsync("Goo")) _provider.StopSearch() ' Do the same query again, and make sure nothing was left over Assert.Single(Await _aggregator.GetItemsAsync("Goo")) _provider.StopSearch() ' Dispose the provider _provider.Dispose() End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDescriptionItems(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, " Public Class Goo End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() Dim itemDisplay As INavigateToItemDisplay = item.DisplayFactory.CreateItemDisplay(item) Dim descriptionItems = itemDisplay.DescriptionItems Dim assertDescription As Action(Of String, String) = Sub(label, value) Dim descriptionItem = descriptionItems.Single(Function(i) i.Category.Single().Text = label) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub assertDescription("File:", w.Documents.Single().Name) assertDescription("Line:", "2") assertDescription("Project:", "Test") End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDescriptionItemsFilePath(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="goo\Test1.vb"> Public Class Goo End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() Dim itemDisplay As INavigateToItemDisplay = item.DisplayFactory.CreateItemDisplay(item) Dim descriptionItems = itemDisplay.DescriptionItems Dim assertDescription As Action(Of String, String) = Sub(label, value) Dim descriptionItem = descriptionItems.Single(Function(i) i.Category.Single().Text = label) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub assertDescription("File:", workspace.Documents.Single().FilePath) assertDescription("Line:", "2") assertDescription("Project:", "VisualBasicAssembly1") End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeTrivialPartialContainerWithMultipleNestedTypes(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner1 End Class Public Partial Class Inner2 End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeWhenAllAreTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Partial Class Inner1 End Class End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner2 End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem), Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Sub Goo2 End Sub End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonTrivialPartialContainerWithNestedType(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Sub Goo2 End Sub Public Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludePartialWithNoContents(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonPartialOnlyContainingNestedTypes(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Class Outer Public Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function End Class End Namespace #Enable Warning BC40000 ' MatchKind is obsolete
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Language.NavigateTo.Interfaces Imports Microsoft.VisualStudio.Text.PatternMatching Imports Roslyn.Test.EditorUtilities.NavigateTo #Disable Warning BC40000 ' MatchKind is obsolete Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NavigateTo <Trait(Traits.Feature, Traits.Features.NavigateTo)> Public Class NavigateToTests Inherits AbstractNavigateToTests Protected Overrides ReadOnly Property Language As String = "vb" Protected Overrides Function CreateWorkspace(content As String, exportProvider As ExportProvider) As TestWorkspace Return TestWorkspace.CreateVisualBasic(content, exportProvider:=exportProvider) End Function <Theory> <CombinatorialData> Public Async Function TestNoItemsForEmptyFile(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "", Async Function(w) Assert.Empty(Await _aggregator.GetItemsAsync("Hello")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class [Class] End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("class")).Single() VerifyNavigateToResultItem(item, "Class", "[|Class|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) item = (Await _aggregator.GetItemsAsync("[class]")).Single() VerifyNavigateToResultItem(item, "Class", "[|Class|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindNestedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Alpha Class Beta Class Gamma End Class End Class End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Gamma")).Single() VerifyNavigateToResultItem(item, "Gamma", "[|Gamma|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMemberInANestedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Alpha Class Beta Class Gamma Sub DoSomething() End Sub End Class End Class End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Alpha.Beta.Gamma", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindGenericConstrainedClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo(Of M As IComparable) End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|](Of M)", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindGenericConstrainedMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo(Of M As IComparable) Public Sub Bar(Of T As IComparable)() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|](Of T)()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo(Of M)", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialClass(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Public Class Goo Private a As Integer End Class Partial Class Goo Private b As Integer End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Goo")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClassInNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Bar Class Goo End Class End Namespace", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single() VerifyNavigateToResultItem(item, "Goo", "[|Goo|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindStruct(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Structure Bar End Structure", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("B")).Single() VerifyNavigateToResultItem(item, "Bar", "[|B|]ar", PatternMatchKind.Prefix, NavigateToItemKind.Structure, Glyph.StructureInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindEnum(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Enum Colors Red Green Blue End Enum", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("C")).Single() VerifyNavigateToResultItem(item, "Colors", "[|C|]olors", PatternMatchKind.Prefix, NavigateToItemKind.Enum, Glyph.EnumInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindEnumMember(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Enum Colors Red Green Blue End Enum", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() VerifyNavigateToResultItem(item, "Green", "[|G|]reen", PatternMatchKind.Prefix, NavigateToItemKind.EnumItem, Glyph.EnumMemberPublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField1(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Ba")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField2(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("ba")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Ba|]r", PatternMatchKind.Prefix, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindField3(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Bar As Integer End Class", Async Function(w) Assert.Empty(Await _aggregator.GetItemsAsync("ar")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimField(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private [string] As String End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("string")).Single() VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("[string]")).Single() VerifyNavigateToResultItem(item, "string", "[|string|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindConstField(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Const bar As String = ""bar"" End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("bar")).Single() VerifyNavigateToResultItem(item, "bar", "[|bar|]", PatternMatchKind.Exact, NavigateToItemKind.Constant, Glyph.ConstantPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindIndexer(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private arr As Integer() Default Public Property Item(ByVal i As Integer) As Integer Get Return arr(i) End Get Set(ByVal value As Integer) arr(i) = value End Set End Property End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Item")).Single() VerifyNavigateToResultItem(item, "Item", "[|Item|](Integer)", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> <WorkItem(780993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780993")> Public Async Function TestFindEvent(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Public Event Bar as EventHandler End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]", PatternMatchKind.Exact, NavigateToItemKind.Event, Glyph.EventPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindNormalProperty(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Property Name As String Get Return String.Empty End Get Set(value As String) End Set End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Name")).Single() VerifyNavigateToResultItem(item, "Name", "[|Name|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindAutoImplementedProperty(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Property Name As String End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Name")).Single() VerifyNavigateToResultItem(item, "Name", "[|Name|]", PatternMatchKind.Exact, NavigateToItemKind.Property, Glyph.PropertyPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub DoSomething() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething()", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindVerbatimMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub [Sub]() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("sub")).Single() VerifyNavigateToResultItem(item, "Sub", "[|Sub|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("[sub]")).Single() VerifyNavigateToResultItem(item, "Sub", "[|Sub|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindParameterizedMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private Sub DoSomething(ByVal i As Integer, s As String) End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DS")).Single() VerifyNavigateToResultItem(item, "DoSomething", "[|D|]o[|S|]omething(Integer, String)", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindConstructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Sub New() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single(Function(i) i.Kind = NavigateToItemKind.Method) VerifyNavigateToResultItem(item, "Goo", "[|Goo|].New()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindStaticConstructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Shared Sub New() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Goo")).Single(Function(i) i.Kind = NavigateToItemKind.Method) VerifyNavigateToResultItem(item, "Goo", "[|Goo|].New()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindDestructor(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Finalize")).Single() VerifyNavigateToResultItem(item, "Finalize", "[|Finalize|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodProtected, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) item = (Await _aggregator.GetItemsAsync("Dispose")).Single() VerifyNavigateToResultItem(item, "Dispose", "[|Dispose|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethods(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Partial Private Sub Bar() End Sub End Class Partial Class Goo Private Sub Bar() End Sub End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Bar")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethodDefinitionOnly(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Partial Private Sub Bar() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_1_2, "Goo", "test1.vb", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindPartialMethodImplementationOnly(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Partial Class Goo Private Sub Bar() End Sub End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPrivate, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindOverriddenMethods(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class BaseGoo Public Overridable Sub Bar() End Sub End Class Class DerivedGoo Inherits BaseGoo Public Overrides Sub Bar() MyBase.Bar() End Sub End Class", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Bar", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Bar")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern1(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("B.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern2(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { } Dim items = (Await _aggregator.GetItemsAsync("C.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern3(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("B.B.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern4(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("Baz.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern5(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("G.B.B.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDottedPattern6(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) Dim items = (Await _aggregator.GetItemsAsync("F.F.B.B.Quux")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> <WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")> Public Async Function TestDottedPattern7(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "namespace Goo namespace Bar class Baz(of X, Y, Z) sub Quux() end sub end class end namespace end namespace", Async Function(w) Dim expecteditems = New List(Of NavigateToItem) From { New NavigateToItem("Quux", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyPrefixPatternMatch, Nothing) } Dim items = (Await _aggregator.GetItemsAsync("Baz.Q")).ToList() VerifyNavigateToResultItems(expecteditems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindInterface(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Public Interface IGoo End Interface", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("IG")).Single() VerifyNavigateToResultItem(item, "IGoo", "[|IG|]oo", PatternMatchKind.Prefix, NavigateToItemKind.Interface, Glyph.InterfacePublic) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindDelegateInNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Goo Delegate Sub DoStuff() End Namespace", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("DoStuff")).Single() VerifyNavigateToResultItem(item, "DoStuff", "[|DoStuff|]", PatternMatchKind.Exact, NavigateToItemKind.Delegate, Glyph.DelegateInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindLambdaExpression(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Dim sqr As Func(Of Integer, Integer) = Function(x) x*x End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("sqr")).Single() VerifyNavigateToResultItem(item, "sqr", "[|sqr|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindModule(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Module ModuleTest End Module", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("MT")).Single() VerifyNavigateToResultItem(item, "ModuleTest", "[|M|]odule[|T|]est", PatternMatchKind.CamelCaseExact, NavigateToItemKind.Module, Glyph.ModuleInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindLineContinuationMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Public Sub Bar(x as Integer, y as Integer) End Sub", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("Bar")).Single() VerifyNavigateToResultItem(item, "Bar", "[|Bar|](Integer, Integer)", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindArray(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo Private itemArray as object() End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("itemArray")).Single VerifyNavigateToResultItem(item, "itemArray", "[|itemArray|]", PatternMatchKind.Exact, NavigateToItemKind.Field, Glyph.FieldPrivate, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "Goo", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindClassAndMethodWithSameName(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class Goo End Class Class Test Private Sub Goo() End Sub End Class", Async Function(w) Dim expectedItems = New List(Of NavigateToItem) From { New NavigateToItem("Goo", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Goo", NavigateToItemKind.Method, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) } Dim items As List(Of NavigateToItem) = (Await _aggregator.GetItemsAsync("Goo")).ToList() VerifyNavigateToResultItems(expectedItems, items) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindMethodNestedInGenericTypes(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Class A(Of T) Class B Structure C(Of U) Sub M() End Sub End Structure End Class End Class", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("M")).Single VerifyNavigateToResultItem(item, "M", "[|M|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "A(Of T).B.C(Of U)", "Test")) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestFindAbstractMethod(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "MustInherit Class A Public MustOverride Sub M() End Class", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("M")).Single VerifyNavigateToResultItem(item, "M", "[|M|]()", PatternMatchKind.Exact, NavigateToItemKind.Method, Glyph.MethodPublic, additionalInfo:=String.Format(FeaturesResources.in_0_project_1, "A", "Test")) End Function) End Function <WorkItem(1111131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1111131")> <Theory> <CombinatorialData> Public Async Function TestFindClassInNamespaceWithGlobalPrefix(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Global.MyNS Public Class C End Class End Namespace", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("C")).Single VerifyNavigateToResultItem(item, "C", "[|C|]", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <WorkItem(1121267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1121267")> <Theory> <CombinatorialData> Public Async Function TestFindClassInGlobalNamespace(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Namespace Global Public Class C(Of T) End Class End Namespace", Async Function(w) Dim item = (Await _aggregator.GetItemsAsync("C")).Single VerifyNavigateToResultItem(item, "C", "[|C|](Of T)", PatternMatchKind.Exact, NavigateToItemKind.Class, Glyph.ClassPublic) End Function) End Function <WorkItem(1834, "https://github.com/dotnet/roslyn/issues/1834")> <Theory> <CombinatorialData> Public Async Function TestConstructorNotParentedByTypeBlock(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, "Module Program End Module Public Sub New() End Sub", Async Function(w) Assert.Equal(0, (Await _aggregator.GetItemsAsync("New")).Count) Dim item = (Await _aggregator.GetItemsAsync("Program")).Single VerifyNavigateToResultItem(item, "Program", "[|Program|]", PatternMatchKind.Exact, NavigateToItemKind.Module, Glyph.ModuleInternal) End Function) End Function <Theory> <CombinatorialData> Public Async Function TestStartStopSanity(testHost As TestHost, composition As Composition) As Task ' Verify that multiple calls to start/stop don't blow up Await TestAsync(testHost, composition, "Public Class Goo End Class", Async Function(w) ' Do one query Assert.Single(Await _aggregator.GetItemsAsync("Goo")) _provider.StopSearch() ' Do the same query again, and make sure nothing was left over Assert.Single(Await _aggregator.GetItemsAsync("Goo")) _provider.StopSearch() ' Dispose the provider _provider.Dispose() End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDescriptionItems(testHost As TestHost, composition As Composition) As Task Await TestAsync(testHost, composition, " Public Class Goo End Class", Async Function(w) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() Dim itemDisplay As INavigateToItemDisplay = item.DisplayFactory.CreateItemDisplay(item) Dim descriptionItems = itemDisplay.DescriptionItems Dim assertDescription As Action(Of String, String) = Sub(label, value) Dim descriptionItem = descriptionItems.Single(Function(i) i.Category.Single().Text = label) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub assertDescription("File:", w.Documents.Single().Name) assertDescription("Line:", "2") assertDescription("Project:", "Test") End Function) End Function <Theory> <CombinatorialData> Public Async Function TestDescriptionItemsFilePath(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="goo\Test1.vb"> Public Class Goo End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) Dim item As NavigateToItem = (Await _aggregator.GetItemsAsync("G")).Single() Dim itemDisplay As INavigateToItemDisplay = item.DisplayFactory.CreateItemDisplay(item) Dim descriptionItems = itemDisplay.DescriptionItems Dim assertDescription As Action(Of String, String) = Sub(label, value) Dim descriptionItem = descriptionItems.Single(Function(i) i.Category.Single().Text = label) Assert.Equal(value, descriptionItem.Details.Single().Text) End Sub assertDescription("File:", workspace.Documents.Single().FilePath) assertDescription("Line:", "2") assertDescription("Project:", "VisualBasicAssembly1") End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeTrivialPartialContainerWithMultipleNestedTypes(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner1 End Class Public Partial Class Inner2 End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoNotIncludeWhenAllAreTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Partial Class Inner1 End Class End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Partial Class Inner2 End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem), Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonTrivialPartialContainer(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Sub Goo2 End Sub End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonTrivialPartialContainerWithNestedType(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer Public Sub Goo End Sub End Class </Document> <Document FilePath="Test2.vb"> Public Partial Class Outer Public Sub Goo2 End Sub Public Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing), New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludePartialWithNoContents(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Partial Class Outer End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function <Theory> <CombinatorialData> Public Async Function DoIncludeNonPartialOnlyContainingNestedTypes(testHost As TestHost, composition As Composition) As Task Using workspace = CreateWorkspace( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Test1.vb"> Public Class Outer Public Class Inner End Class End Class </Document> </Project> </Workspace>, testHost, DefaultComposition) _provider = New NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService(Of IThreadingContext)()) _aggregator = New NavigateToTestAggregator(_provider) VerifyNavigateToResultItems( New List(Of NavigateToItem) From { New NavigateToItem("Outer", NavigateToItemKind.Class, "vb", Nothing, Nothing, s_emptyExactPatternMatch, Nothing) }, Await _aggregator.GetItemsAsync("Outer")) End Using End Function End Class End Namespace #Enable Warning BC40000 ' MatchKind is obsolete
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Flags.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 Partial Friend NotInheritable Class LocalRewriter <Flags> Friend Enum RewritingFlags As Byte [Default] = 0 AllowSequencePoints = 1 AllowEndOfMethodReturnWithExpression = 2 AllowCatchWithErrorLineNumberReference = 4 AllowOmissionOfConditionalCalls = 8 End Enum Private ReadOnly _flags As RewritingFlags 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 Partial Friend NotInheritable Class LocalRewriter <Flags> Friend Enum RewritingFlags As Byte [Default] = 0 AllowSequencePoints = 1 AllowEndOfMethodReturnWithExpression = 2 AllowCatchWithErrorLineNumberReference = 4 AllowOmissionOfConditionalCalls = 8 End Enum Private ReadOnly _flags As RewritingFlags End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder_Compat.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private Shared Function CrefReferenceIsLegalForLegacyMode(nameFromCref As TypeSyntax) As Boolean Select Case nameFromCref.Kind Case SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.PredefinedType Return True Case Else Return False End Select End Function Private Function BindNameInsideCrefReferenceInLegacyMode(nameFromCref As TypeSyntax, preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) ' This binding mode is used for cref-references without signatures and ' emulate Dev11 behavior If Not CrefReferenceIsLegalForLegacyMode(nameFromCref) Then Return ImmutableArray(Of Symbol).Empty End If ' The name which is either an upper-level (parent is the cref attribute) ' or is part of upper-level qualified name should be searched. All other ' names will be bound using regular BindType calls Dim name As VisualBasicSyntaxNode = nameFromCref.Parent While name IsNot Nothing And name.Kind <> SyntaxKind.CrefReference If name.Kind <> SyntaxKind.QualifiedName Then ' Not a top-level name or a top-level qualified name part Dim result As Symbol = If(preserveAliases, BindTypeOrAliasSyntax(nameFromCref, BindingDiagnosticBag.Discarded), BindTypeSyntax(nameFromCref, BindingDiagnosticBag.Discarded)) Return ImmutableArray.Create(Of Symbol)(result) End If name = name.Parent End While Debug.Assert(name IsNot Nothing) ' This is an upper-level name, we check is it has any ' diagnostics and if it does we return empty symbol set If nameFromCref.ContainsDiagnostics() Then Return ImmutableArray(Of Symbol).Empty End If Dim symbols = ArrayBuilder(Of Symbol).GetInstance() Select Case nameFromCref.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName BindSimpleNameForCref(DirectCast(nameFromCref, SimpleNameSyntax), symbols, preserveAliases, useSiteInfo, False) Case SyntaxKind.PredefinedType BindPredefinedTypeForCref(DirectCast(nameFromCref, PredefinedTypeSyntax), symbols) Case SyntaxKind.QualifiedName BindQualifiedNameForCref(DirectCast(nameFromCref, QualifiedNameSyntax), symbols, preserveAliases, useSiteInfo) Case Else Throw ExceptionUtilities.UnexpectedValue(nameFromCref.Kind) End Select RemoveOverriddenMethodsAndProperties(symbols) Return symbols.ToImmutableAndFree() End Function Private Sub BindQualifiedNameForCref(node As QualifiedNameSyntax, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim allowColorColor As Boolean = True Dim left As NameSyntax = node.Left Select Case left.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName BindSimpleNameForCref(DirectCast(left, SimpleNameSyntax), symbols, preserveAliases, useSiteInfo, True) Case SyntaxKind.QualifiedName BindQualifiedNameForCref(DirectCast(left, QualifiedNameSyntax), symbols, preserveAliases, useSiteInfo) allowColorColor = False Case SyntaxKind.GlobalName symbols.Add(Me.Compilation.GlobalNamespace) Case Else Throw ExceptionUtilities.UnexpectedValue(left.Kind) End Select If symbols.Count <> 1 Then ' This is an error, we don't know what symbol to search for the right name ' It does not matter if the ambiguous symbols were actually found symbols.Clear() Return End If Dim singleSymbol As Symbol = symbols(0) symbols.Clear() ' We found one single symbol, we need to search for the 'right' ' name in the context of this symbol Dim right As SimpleNameSyntax = node.Right If right.Kind = SyntaxKind.GenericName Then ' Generic name Dim genericName = DirectCast(right, GenericNameSyntax) BindSimpleNameForCref(genericName.Identifier.ValueText, genericName.TypeArgumentList.Arguments.Count, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) If symbols.Count <> 1 Then ' Don't do any construction in case nothing was found or ' there is ambiguity Return End If symbols(0) = ConstructGenericSymbolWithTypeArgumentsForCref(symbols(0), genericName) Else ' Simple identifier name Debug.Assert(right.Kind = SyntaxKind.IdentifierName) Dim identifierName As String = DirectCast(right, IdentifierNameSyntax).Identifier.ValueText ' Search for 0 arity first BindSimpleNameForCref(identifierName, 0, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) If symbols.Count > 0 Then Return End If ' Search with any arity, if we find the single result, it is going to be ' selected as the right one, otherwise we will return ambiguous result BindSimpleNameForCref(identifierName, -1, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) End If End Sub Private Sub LookupSimpleNameInContainingSymbol(containingSymbol As Symbol, allowColorColor As Boolean, name As String, arity As Integer, preserveAliases As Boolean, lookupResult As LookupResult, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) lAgain: Select Case containingSymbol.Kind Case SymbolKind.Namespace LookupMember(lookupResult, DirectCast(containingSymbol, NamespaceSymbol), name, arity, options, useSiteInfo) Case SymbolKind.Alias If Not preserveAliases Then containingSymbol = DirectCast(containingSymbol, AliasSymbol).Target GoTo lAgain End If Case SymbolKind.NamedType, SymbolKind.ArrayType LookupMember(lookupResult, DirectCast(containingSymbol, TypeSymbol), name, arity, options, useSiteInfo) Case SymbolKind.Property If allowColorColor Then ' Check for Color Color case Dim [property] = DirectCast(containingSymbol, PropertySymbol) Dim propertyType As TypeSymbol = [property].Type If IdentifierComparison.Equals([property].Name, propertyType.Name) Then containingSymbol = propertyType GoTo lAgain End If End If Case SymbolKind.Field If allowColorColor Then ' Check for Color Color case Dim field = DirectCast(containingSymbol, FieldSymbol) Dim fieldType As TypeSymbol = field.Type If IdentifierComparison.Equals(field.Name, fieldType.Name) Then containingSymbol = fieldType GoTo lAgain End If End If Case SymbolKind.Method If allowColorColor Then ' Check for Color Color case Dim method = DirectCast(containingSymbol, MethodSymbol) If Not method.IsSub Then Dim returnType As TypeSymbol = method.ReturnType If IdentifierComparison.Equals(method.Name, returnType.Name) Then containingSymbol = returnType GoTo lAgain End If End If End If Case Else ' Nothing can be found in context of these symbols End Select End Sub Private Sub BindSimpleNameForCref(name As String, arity As Integer, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional containingSymbol As Symbol = Nothing, Optional allowColorColor As Boolean = False, Optional typeOrNamespaceOnly As Boolean = False) Debug.Assert(Not String.IsNullOrEmpty(name)) If String.IsNullOrEmpty(name) Then ' Return an empty symbol collection in error scenario Return End If Dim options = LookupOptions.UseBaseReferenceAccessibility Or LookupOptions.MustNotBeReturnValueVariable Or LookupOptions.IgnoreExtensionMethods Or LookupOptions.MustNotBeLocalOrParameter Or LookupOptions.NoSystemObjectLookupForInterfaces Or LookupOptions.IgnoreAccessibility If arity < 0 Then options = options Or LookupOptions.AllMethodsOfAnyArity End If If typeOrNamespaceOnly Then options = options Or LookupOptions.NamespacesOrTypesOnly End If Dim lookupResult As LookupResult = LookupResult.GetInstance() If containingSymbol Is Nothing Then Me.Lookup(lookupResult, name, arity, options, useSiteInfo) Else LookupSimpleNameInContainingSymbol(containingSymbol, allowColorColor, name, arity, preserveAliases, lookupResult, options, useSiteInfo) End If If Not lookupResult.IsGoodOrAmbiguous OrElse Not lookupResult.HasSymbol Then lookupResult.Free() Return End If CreateGoodOrAmbiguousFromLookupResultAndFree(lookupResult, symbols, preserveAliases) End Sub Private Sub BindSimpleNameForCref(node As SimpleNameSyntax, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), typeOrNamespaceOnly As Boolean) ' Name syntax of Cref should not have diagnostics If node.ContainsDiagnostics Then ' Return an empty symbol collection in case there is any syntax diagnostics Return End If If node.Kind = SyntaxKind.GenericName Then ' Generic name Dim genericName = DirectCast(node, GenericNameSyntax) BindSimpleNameForCref(genericName.Identifier.ValueText, genericName.TypeArgumentList.Arguments.Count, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) If symbols.Count <> 1 Then ' Don't do any construction in case nothing was found or there is an ambiguity Return End If symbols(0) = ConstructGenericSymbolWithTypeArgumentsForCref(symbols(0), genericName) Else ' Simple identifier name Debug.Assert(node.Kind = SyntaxKind.IdentifierName) Dim identifier As SyntaxToken = DirectCast(node, IdentifierNameSyntax).Identifier Dim identifierName As String = identifier.ValueText ' Search for 0 arity first BindSimpleNameForCref(identifierName, 0, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) If symbols.Count > 0 Then Return End If ' Search with any arity, if we find the single result, it is going to be ' selected as the right one, otherwise we will return ambiguous result BindSimpleNameForCref(identifierName, -1, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) End If End Sub Private Sub BindPredefinedTypeForCref(node As PredefinedTypeSyntax, symbols As ArrayBuilder(Of Symbol)) ' Name syntax of Cref should not have diagnostics If node.ContainsDiagnostics Then ' Return an empty symbol collection in case there is any syntax diagnostics Return End If Dim type As SpecialType Select Case node.Keyword.Kind Case SyntaxKind.ObjectKeyword type = SpecialType.System_Object Case SyntaxKind.BooleanKeyword type = SpecialType.System_Boolean Case SyntaxKind.DateKeyword type = SpecialType.System_DateTime Case SyntaxKind.CharKeyword type = SpecialType.System_Char Case SyntaxKind.StringKeyword type = SpecialType.System_String Case SyntaxKind.DecimalKeyword type = SpecialType.System_Decimal Case SyntaxKind.ByteKeyword type = SpecialType.System_Byte Case SyntaxKind.SByteKeyword type = SpecialType.System_SByte Case SyntaxKind.UShortKeyword type = SpecialType.System_UInt16 Case SyntaxKind.ShortKeyword type = SpecialType.System_Int16 Case SyntaxKind.UIntegerKeyword type = SpecialType.System_UInt32 Case SyntaxKind.IntegerKeyword type = SpecialType.System_Int32 Case SyntaxKind.ULongKeyword type = SpecialType.System_UInt64 Case SyntaxKind.LongKeyword type = SpecialType.System_Int64 Case SyntaxKind.SingleKeyword type = SpecialType.System_Single Case SyntaxKind.DoubleKeyword type = SpecialType.System_Double Case Else Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind) End Select ' We discard diagnostics in case symbols.Add(Me.GetSpecialType(type, node, BindingDiagnosticBag.Discarded)) End Sub Private Function ConstructGenericSymbolWithTypeArgumentsForCref(genericSymbol As Symbol, genericName As GenericNameSyntax) As Symbol Select Case genericSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(genericSymbol, MethodSymbol) Debug.Assert(method.Arity = genericName.TypeArgumentList.Arguments.Count) Return method.Construct(BingTypeArgumentsForCref(genericName.TypeArgumentList.Arguments)) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim type = DirectCast(genericSymbol, NamedTypeSymbol) Debug.Assert(type.Arity = genericName.TypeArgumentList.Arguments.Count) Return type.Construct(BingTypeArgumentsForCref(genericName.TypeArgumentList.Arguments)) Case SymbolKind.Alias Dim [alias] = DirectCast(genericSymbol, AliasSymbol) Return ConstructGenericSymbolWithTypeArgumentsForCref([alias].Target, genericName) Case Else Throw ExceptionUtilities.UnexpectedValue(genericSymbol.Kind) End Select End Function Private Function BingTypeArgumentsForCref(args As SeparatedSyntaxList(Of TypeSyntax)) As ImmutableArray(Of TypeSymbol) Dim result(args.Count - 1) As TypeSymbol For i = 0 To args.Count - 1 result(i) = Me.BindTypeSyntax(args(i), BindingDiagnosticBag.Discarded) Next Return result.AsImmutableOrNull() End Function Private Shared Sub CreateGoodOrAmbiguousFromLookupResultAndFree(lookupResult As LookupResult, result As ArrayBuilder(Of Symbol), preserveAliases As Boolean) Dim di As DiagnosticInfo = lookupResult.Diagnostic If TypeOf di Is AmbiguousSymbolDiagnostic Then ' Several ambiguous symbols wrapped in 'AmbiguousSymbolDiagnostic' Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous) Debug.Assert(lookupResult.Symbols.Count = 1) Dim symbols As ImmutableArray(Of Symbol) = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols Debug.Assert(symbols.Length > 1) If preserveAliases Then result.AddRange(symbols) Else For Each sym In symbols result.Add(UnwrapAlias(sym)) Next End If Else If preserveAliases Then result.AddRange(lookupResult.Symbols) Else For Each sym In lookupResult.Symbols result.Add(sym.UnwrapAlias()) Next End If End If lookupResult.Free() 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.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private Shared Function CrefReferenceIsLegalForLegacyMode(nameFromCref As TypeSyntax) As Boolean Select Case nameFromCref.Kind Case SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.PredefinedType Return True Case Else Return False End Select End Function Private Function BindNameInsideCrefReferenceInLegacyMode(nameFromCref As TypeSyntax, preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of Symbol) ' This binding mode is used for cref-references without signatures and ' emulate Dev11 behavior If Not CrefReferenceIsLegalForLegacyMode(nameFromCref) Then Return ImmutableArray(Of Symbol).Empty End If ' The name which is either an upper-level (parent is the cref attribute) ' or is part of upper-level qualified name should be searched. All other ' names will be bound using regular BindType calls Dim name As VisualBasicSyntaxNode = nameFromCref.Parent While name IsNot Nothing And name.Kind <> SyntaxKind.CrefReference If name.Kind <> SyntaxKind.QualifiedName Then ' Not a top-level name or a top-level qualified name part Dim result As Symbol = If(preserveAliases, BindTypeOrAliasSyntax(nameFromCref, BindingDiagnosticBag.Discarded), BindTypeSyntax(nameFromCref, BindingDiagnosticBag.Discarded)) Return ImmutableArray.Create(Of Symbol)(result) End If name = name.Parent End While Debug.Assert(name IsNot Nothing) ' This is an upper-level name, we check is it has any ' diagnostics and if it does we return empty symbol set If nameFromCref.ContainsDiagnostics() Then Return ImmutableArray(Of Symbol).Empty End If Dim symbols = ArrayBuilder(Of Symbol).GetInstance() Select Case nameFromCref.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName BindSimpleNameForCref(DirectCast(nameFromCref, SimpleNameSyntax), symbols, preserveAliases, useSiteInfo, False) Case SyntaxKind.PredefinedType BindPredefinedTypeForCref(DirectCast(nameFromCref, PredefinedTypeSyntax), symbols) Case SyntaxKind.QualifiedName BindQualifiedNameForCref(DirectCast(nameFromCref, QualifiedNameSyntax), symbols, preserveAliases, useSiteInfo) Case Else Throw ExceptionUtilities.UnexpectedValue(nameFromCref.Kind) End Select RemoveOverriddenMethodsAndProperties(symbols) Return symbols.ToImmutableAndFree() End Function Private Sub BindQualifiedNameForCref(node As QualifiedNameSyntax, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim allowColorColor As Boolean = True Dim left As NameSyntax = node.Left Select Case left.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName BindSimpleNameForCref(DirectCast(left, SimpleNameSyntax), symbols, preserveAliases, useSiteInfo, True) Case SyntaxKind.QualifiedName BindQualifiedNameForCref(DirectCast(left, QualifiedNameSyntax), symbols, preserveAliases, useSiteInfo) allowColorColor = False Case SyntaxKind.GlobalName symbols.Add(Me.Compilation.GlobalNamespace) Case Else Throw ExceptionUtilities.UnexpectedValue(left.Kind) End Select If symbols.Count <> 1 Then ' This is an error, we don't know what symbol to search for the right name ' It does not matter if the ambiguous symbols were actually found symbols.Clear() Return End If Dim singleSymbol As Symbol = symbols(0) symbols.Clear() ' We found one single symbol, we need to search for the 'right' ' name in the context of this symbol Dim right As SimpleNameSyntax = node.Right If right.Kind = SyntaxKind.GenericName Then ' Generic name Dim genericName = DirectCast(right, GenericNameSyntax) BindSimpleNameForCref(genericName.Identifier.ValueText, genericName.TypeArgumentList.Arguments.Count, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) If symbols.Count <> 1 Then ' Don't do any construction in case nothing was found or ' there is ambiguity Return End If symbols(0) = ConstructGenericSymbolWithTypeArgumentsForCref(symbols(0), genericName) Else ' Simple identifier name Debug.Assert(right.Kind = SyntaxKind.IdentifierName) Dim identifierName As String = DirectCast(right, IdentifierNameSyntax).Identifier.ValueText ' Search for 0 arity first BindSimpleNameForCref(identifierName, 0, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) If symbols.Count > 0 Then Return End If ' Search with any arity, if we find the single result, it is going to be ' selected as the right one, otherwise we will return ambiguous result BindSimpleNameForCref(identifierName, -1, symbols, preserveAliases, useSiteInfo, containingSymbol:=singleSymbol, allowColorColor:=allowColorColor) End If End Sub Private Sub LookupSimpleNameInContainingSymbol(containingSymbol As Symbol, allowColorColor As Boolean, name As String, arity As Integer, preserveAliases As Boolean, lookupResult As LookupResult, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) lAgain: Select Case containingSymbol.Kind Case SymbolKind.Namespace LookupMember(lookupResult, DirectCast(containingSymbol, NamespaceSymbol), name, arity, options, useSiteInfo) Case SymbolKind.Alias If Not preserveAliases Then containingSymbol = DirectCast(containingSymbol, AliasSymbol).Target GoTo lAgain End If Case SymbolKind.NamedType, SymbolKind.ArrayType LookupMember(lookupResult, DirectCast(containingSymbol, TypeSymbol), name, arity, options, useSiteInfo) Case SymbolKind.Property If allowColorColor Then ' Check for Color Color case Dim [property] = DirectCast(containingSymbol, PropertySymbol) Dim propertyType As TypeSymbol = [property].Type If IdentifierComparison.Equals([property].Name, propertyType.Name) Then containingSymbol = propertyType GoTo lAgain End If End If Case SymbolKind.Field If allowColorColor Then ' Check for Color Color case Dim field = DirectCast(containingSymbol, FieldSymbol) Dim fieldType As TypeSymbol = field.Type If IdentifierComparison.Equals(field.Name, fieldType.Name) Then containingSymbol = fieldType GoTo lAgain End If End If Case SymbolKind.Method If allowColorColor Then ' Check for Color Color case Dim method = DirectCast(containingSymbol, MethodSymbol) If Not method.IsSub Then Dim returnType As TypeSymbol = method.ReturnType If IdentifierComparison.Equals(method.Name, returnType.Name) Then containingSymbol = returnType GoTo lAgain End If End If End If Case Else ' Nothing can be found in context of these symbols End Select End Sub Private Sub BindSimpleNameForCref(name As String, arity As Integer, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional containingSymbol As Symbol = Nothing, Optional allowColorColor As Boolean = False, Optional typeOrNamespaceOnly As Boolean = False) Debug.Assert(Not String.IsNullOrEmpty(name)) If String.IsNullOrEmpty(name) Then ' Return an empty symbol collection in error scenario Return End If Dim options = LookupOptions.UseBaseReferenceAccessibility Or LookupOptions.MustNotBeReturnValueVariable Or LookupOptions.IgnoreExtensionMethods Or LookupOptions.MustNotBeLocalOrParameter Or LookupOptions.NoSystemObjectLookupForInterfaces Or LookupOptions.IgnoreAccessibility If arity < 0 Then options = options Or LookupOptions.AllMethodsOfAnyArity End If If typeOrNamespaceOnly Then options = options Or LookupOptions.NamespacesOrTypesOnly End If Dim lookupResult As LookupResult = LookupResult.GetInstance() If containingSymbol Is Nothing Then Me.Lookup(lookupResult, name, arity, options, useSiteInfo) Else LookupSimpleNameInContainingSymbol(containingSymbol, allowColorColor, name, arity, preserveAliases, lookupResult, options, useSiteInfo) End If If Not lookupResult.IsGoodOrAmbiguous OrElse Not lookupResult.HasSymbol Then lookupResult.Free() Return End If CreateGoodOrAmbiguousFromLookupResultAndFree(lookupResult, symbols, preserveAliases) End Sub Private Sub BindSimpleNameForCref(node As SimpleNameSyntax, symbols As ArrayBuilder(Of Symbol), preserveAliases As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), typeOrNamespaceOnly As Boolean) ' Name syntax of Cref should not have diagnostics If node.ContainsDiagnostics Then ' Return an empty symbol collection in case there is any syntax diagnostics Return End If If node.Kind = SyntaxKind.GenericName Then ' Generic name Dim genericName = DirectCast(node, GenericNameSyntax) BindSimpleNameForCref(genericName.Identifier.ValueText, genericName.TypeArgumentList.Arguments.Count, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) If symbols.Count <> 1 Then ' Don't do any construction in case nothing was found or there is an ambiguity Return End If symbols(0) = ConstructGenericSymbolWithTypeArgumentsForCref(symbols(0), genericName) Else ' Simple identifier name Debug.Assert(node.Kind = SyntaxKind.IdentifierName) Dim identifier As SyntaxToken = DirectCast(node, IdentifierNameSyntax).Identifier Dim identifierName As String = identifier.ValueText ' Search for 0 arity first BindSimpleNameForCref(identifierName, 0, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) If symbols.Count > 0 Then Return End If ' Search with any arity, if we find the single result, it is going to be ' selected as the right one, otherwise we will return ambiguous result BindSimpleNameForCref(identifierName, -1, symbols, preserveAliases, useSiteInfo, typeOrNamespaceOnly:=typeOrNamespaceOnly) End If End Sub Private Sub BindPredefinedTypeForCref(node As PredefinedTypeSyntax, symbols As ArrayBuilder(Of Symbol)) ' Name syntax of Cref should not have diagnostics If node.ContainsDiagnostics Then ' Return an empty symbol collection in case there is any syntax diagnostics Return End If Dim type As SpecialType Select Case node.Keyword.Kind Case SyntaxKind.ObjectKeyword type = SpecialType.System_Object Case SyntaxKind.BooleanKeyword type = SpecialType.System_Boolean Case SyntaxKind.DateKeyword type = SpecialType.System_DateTime Case SyntaxKind.CharKeyword type = SpecialType.System_Char Case SyntaxKind.StringKeyword type = SpecialType.System_String Case SyntaxKind.DecimalKeyword type = SpecialType.System_Decimal Case SyntaxKind.ByteKeyword type = SpecialType.System_Byte Case SyntaxKind.SByteKeyword type = SpecialType.System_SByte Case SyntaxKind.UShortKeyword type = SpecialType.System_UInt16 Case SyntaxKind.ShortKeyword type = SpecialType.System_Int16 Case SyntaxKind.UIntegerKeyword type = SpecialType.System_UInt32 Case SyntaxKind.IntegerKeyword type = SpecialType.System_Int32 Case SyntaxKind.ULongKeyword type = SpecialType.System_UInt64 Case SyntaxKind.LongKeyword type = SpecialType.System_Int64 Case SyntaxKind.SingleKeyword type = SpecialType.System_Single Case SyntaxKind.DoubleKeyword type = SpecialType.System_Double Case Else Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind) End Select ' We discard diagnostics in case symbols.Add(Me.GetSpecialType(type, node, BindingDiagnosticBag.Discarded)) End Sub Private Function ConstructGenericSymbolWithTypeArgumentsForCref(genericSymbol As Symbol, genericName As GenericNameSyntax) As Symbol Select Case genericSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(genericSymbol, MethodSymbol) Debug.Assert(method.Arity = genericName.TypeArgumentList.Arguments.Count) Return method.Construct(BingTypeArgumentsForCref(genericName.TypeArgumentList.Arguments)) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim type = DirectCast(genericSymbol, NamedTypeSymbol) Debug.Assert(type.Arity = genericName.TypeArgumentList.Arguments.Count) Return type.Construct(BingTypeArgumentsForCref(genericName.TypeArgumentList.Arguments)) Case SymbolKind.Alias Dim [alias] = DirectCast(genericSymbol, AliasSymbol) Return ConstructGenericSymbolWithTypeArgumentsForCref([alias].Target, genericName) Case Else Throw ExceptionUtilities.UnexpectedValue(genericSymbol.Kind) End Select End Function Private Function BingTypeArgumentsForCref(args As SeparatedSyntaxList(Of TypeSyntax)) As ImmutableArray(Of TypeSymbol) Dim result(args.Count - 1) As TypeSymbol For i = 0 To args.Count - 1 result(i) = Me.BindTypeSyntax(args(i), BindingDiagnosticBag.Discarded) Next Return result.AsImmutableOrNull() End Function Private Shared Sub CreateGoodOrAmbiguousFromLookupResultAndFree(lookupResult As LookupResult, result As ArrayBuilder(Of Symbol), preserveAliases As Boolean) Dim di As DiagnosticInfo = lookupResult.Diagnostic If TypeOf di Is AmbiguousSymbolDiagnostic Then ' Several ambiguous symbols wrapped in 'AmbiguousSymbolDiagnostic' Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous) Debug.Assert(lookupResult.Symbols.Count = 1) Dim symbols As ImmutableArray(Of Symbol) = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols Debug.Assert(symbols.Length > 1) If preserveAliases Then result.AddRange(symbols) Else For Each sym In symbols result.Add(UnwrapAlias(sym)) Next End If Else If preserveAliases Then result.AddRange(lookupResult.Symbols) Else For Each sym In lookupResult.Symbols result.Add(sym.UnwrapAlias()) Next End If End If lookupResult.Free() End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageServiceFactory.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.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Rename Namespace Microsoft.CodeAnalysis.VisualBasic.Rename <ExportLanguageServiceFactory(GetType(IRenameRewriterLanguageService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicRenameRewriterLanguageServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return VisualBasicRenameRewriterLanguageService.Instance 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 Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Rename Namespace Microsoft.CodeAnalysis.VisualBasic.Rename <ExportLanguageServiceFactory(GetType(IRenameRewriterLanguageService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicRenameRewriterLanguageServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return VisualBasicRenameRewriterLanguageService.Instance End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass Partial Public Class ImplementAbstractClassTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicImplementAbstractClassCodeFixProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestSimpleCases() As Task Await TestInRegularAndScriptAsync( "Public MustInherit Class Goo Public MustOverride Sub Goo(i As Integer) Protected MustOverride Function Bar(s As String, ByRef d As Double) As Boolean End Class Public Class [|Bar|] Inherits Goo End Class", "Public MustInherit Class Goo Public MustOverride Sub Goo(i As Integer) Protected MustOverride Function Bar(s As String, ByRef d As Double) As Boolean End Class Public Class Bar Inherits Goo Public Overrides Sub Goo(i As Integer) Throw New System.NotImplementedException() End Sub Protected Overrides Function Bar(s As String, ByRef d As Double) As Boolean Throw New System.NotImplementedException() End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestMethodWithTupleNames() As Task Await TestInRegularAndScriptAsync( "Public MustInherit Class Base Protected MustOverride Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) End Class Public Class [|Derived|] Inherits Base End Class", "Public MustInherit Class Base Protected MustOverride Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) End Class Public Class Derived Inherits Base Protected Overrides Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) Throw New System.NotImplementedException() End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalTrueParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = True) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = True) End Class Class c Inherits b Public Overrides Sub g(Optional x As Boolean = True) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalFalseParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = False) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = False) End Class Class c Inherits b Public Overrides Sub g(Optional x As Boolean = False) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalStringParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As String = ""a"") End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As String = ""a"") End Class Class c Inherits b Public Overrides Sub g(Optional x As String = ""a"") Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalCharParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Char = ""c""c) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Char = ""c""c) End Class Class c Inherits b Public Overrides Sub g(Optional x As Char = ""c""c) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalLongParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Long = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Long = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Long = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalShortParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Short = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Short = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Short = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalUShortParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As UShort = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As UShort = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As UShort = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNegativeIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = -3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = -3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer = -3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalUIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As UInteger = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As UInteger = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As UInteger = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalULongParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As ULong = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As ULong = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As ULong = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalDecimalParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Decimal = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Decimal = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Decimal = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalDoubleParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Double = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Double = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Double = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalStructParameter() As Task Await TestInRegularAndScriptAsync( "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class", "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNullableStructParameter() As Task Await TestInRegularAndScriptAsync( "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S? = Nothing) End Class Class [|c|] Inherits b End Class", "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S? = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S? = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNullableIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalClassParameter() As Task Await TestInRegularAndScriptAsync( "Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class", "Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestClassStatementTerminators1() As Task Await TestInRegularAndScriptAsync( "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class [|C|] : Inherits D : End Class", "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class C : Inherits D Public Overrides Sub Goo() Throw New NotImplementedException() End Sub End Class") End Function <WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestClassStatementTerminators2() As Task Await TestInRegularAndScriptAsync( "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class [|C|] : Inherits D : Implements IDisposable : End Class", "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class C : Inherits D : Implements IDisposable Public Overrides Sub Goo() Throw New NotImplementedException() End Sub End Class") End Function <WorkItem(530737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530737")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestRenameTypeParameters() As Task Await TestInRegularAndScriptAsync( "MustInherit Class A(Of T) MustOverride Sub Goo(Of S As T)() End Class Class [|C(Of S)|] Inherits A(Of S) End Class", "MustInherit Class A(Of T) MustOverride Sub Goo(Of S As T)() End Class Class C(Of S) Inherits A(Of S) Public Overrides Sub Goo(Of S1 As S)() Throw New System.NotImplementedException() End Sub End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestFormattingInImplementAbstractClass() As Task Await TestInRegularAndScriptAsync( <Text>Imports System Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports System Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestImplementClassWithInaccessibleMembers() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Globalization Class [|x|] Inherits EastAsianLunisolarCalendar End Class", "Imports System Imports System.Globalization Class x Inherits EastAsianLunisolarCalendar Public Overrides ReadOnly Property Eras As Integer() Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MinCalendarYear As Integer Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MaxCalendarYear As Integer Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property CalEraInfo As EraInfo() Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MinDate As Date Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MaxDate As Date Get Throw New NotImplementedException() End Get End Property Public Overrides Function GetEra(time As Date) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetYearInfo(LunarYear As Integer, Index As Integer) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetYear(year As Integer, time As Date) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetGregorianYear(year As Integer, era As Integer) As Integer Throw New NotImplementedException() End Function End Class") End Function <WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")> <WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function TestAutoProperties() As Task Await TestInRegularAndScript1Async( "MustInherit Class AbstractClass MustOverride ReadOnly Property ReadOnlyProp As Integer MustOverride Property ReadWriteProp As Integer MustOverride WriteOnly Property WriteOnlyProp As Integer End Class Class [|C|] Inherits AbstractClass End Class", "MustInherit Class AbstractClass MustOverride ReadOnly Property ReadOnlyProp As Integer MustOverride Property ReadWriteProp As Integer MustOverride WriteOnly Property WriteOnlyProp As Integer End Class Class C Inherits AbstractClass Public Overrides ReadOnly Property ReadOnlyProp As Integer Public Overrides Property ReadWriteProp As Integer Public Overrides WriteOnly Property WriteOnlyProp As Integer Set(value As Integer) Throw New System.NotImplementedException() End Set End Property End Class", parameters:=New TestParameters(options:=[Option]( ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties))) 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass Partial Public Class ImplementAbstractClassTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicImplementAbstractClassCodeFixProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestSimpleCases() As Task Await TestInRegularAndScriptAsync( "Public MustInherit Class Goo Public MustOverride Sub Goo(i As Integer) Protected MustOverride Function Bar(s As String, ByRef d As Double) As Boolean End Class Public Class [|Bar|] Inherits Goo End Class", "Public MustInherit Class Goo Public MustOverride Sub Goo(i As Integer) Protected MustOverride Function Bar(s As String, ByRef d As Double) As Boolean End Class Public Class Bar Inherits Goo Public Overrides Sub Goo(i As Integer) Throw New System.NotImplementedException() End Sub Protected Overrides Function Bar(s As String, ByRef d As Double) As Boolean Throw New System.NotImplementedException() End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestMethodWithTupleNames() As Task Await TestInRegularAndScriptAsync( "Public MustInherit Class Base Protected MustOverride Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) End Class Public Class [|Derived|] Inherits Base End Class", "Public MustInherit Class Base Protected MustOverride Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) End Class Public Class Derived Inherits Base Protected Overrides Function Bar(x As (a As Integer, Integer)) As (c As Integer, Integer) Throw New System.NotImplementedException() End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalTrueParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = True) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = True) End Class Class c Inherits b Public Overrides Sub g(Optional x As Boolean = True) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalFalseParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = False) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Boolean = False) End Class Class c Inherits b Public Overrides Sub g(Optional x As Boolean = False) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalStringParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As String = ""a"") End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As String = ""a"") End Class Class c Inherits b Public Overrides Sub g(Optional x As String = ""a"") Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalCharParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Char = ""c""c) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Char = ""c""c) End Class Class c Inherits b Public Overrides Sub g(Optional x As Char = ""c""c) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalLongParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Long = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Long = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Long = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalShortParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Short = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Short = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Short = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalUShortParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As UShort = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As UShort = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As UShort = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNegativeIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = -3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer = -3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer = -3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalUIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As UInteger = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As UInteger = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As UInteger = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalULongParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As ULong = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As ULong = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As ULong = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalDecimalParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Decimal = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Decimal = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Decimal = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalDoubleParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Double = 3) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Double = 3) End Class Class c Inherits b Public Overrides Sub g(Optional x As Double = 3) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalStructParameter() As Task Await TestInRegularAndScriptAsync( "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class", "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNullableStructParameter() As Task Await TestInRegularAndScriptAsync( "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S? = Nothing) End Class Class [|c|] Inherits b End Class", "Structure S End Structure MustInherit Class b Public MustOverride Sub g(Optional x As S? = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S? = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalNullableIntParameter() As Task Await TestInRegularAndScriptAsync( "MustInherit Class b Public MustOverride Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) End Class Class [|c|] Inherits b End Class", "MustInherit Class b Public MustOverride Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) End Class Class c Inherits b Public Overrides Sub g(Optional x As Integer? = Nothing, Optional y As Integer? = 5) Throw New System.NotImplementedException() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestOptionalClassParameter() As Task Await TestInRegularAndScriptAsync( "Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class", "Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New System.NotImplementedException() End Sub End Class") End Function <WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestClassStatementTerminators1() As Task Await TestInRegularAndScriptAsync( "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class [|C|] : Inherits D : End Class", "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class C : Inherits D Public Overrides Sub Goo() Throw New NotImplementedException() End Sub End Class") End Function <WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestClassStatementTerminators2() As Task Await TestInRegularAndScriptAsync( "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class [|C|] : Inherits D : Implements IDisposable : End Class", "Imports System MustInherit Class D MustOverride Sub Goo() End Class Class C : Inherits D : Implements IDisposable Public Overrides Sub Goo() Throw New NotImplementedException() End Sub End Class") End Function <WorkItem(530737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530737")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestRenameTypeParameters() As Task Await TestInRegularAndScriptAsync( "MustInherit Class A(Of T) MustOverride Sub Goo(Of S As T)() End Class Class [|C(Of S)|] Inherits A(Of S) End Class", "MustInherit Class A(Of T) MustOverride Sub Goo(Of S As T)() End Class Class C(Of S) Inherits A(Of S) Public Overrides Sub Goo(Of S1 As S)() Throw New System.NotImplementedException() End Sub End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestFormattingInImplementAbstractClass() As Task Await TestInRegularAndScriptAsync( <Text>Imports System Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class [|c|] Inherits b End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports System Class S End Class MustInherit Class b Public MustOverride Sub g(Optional x As S = Nothing) End Class Class c Inherits b Public Overrides Sub g(Optional x As S = Nothing) Throw New NotImplementedException() End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> Public Async Function TestImplementClassWithInaccessibleMembers() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Globalization Class [|x|] Inherits EastAsianLunisolarCalendar End Class", "Imports System Imports System.Globalization Class x Inherits EastAsianLunisolarCalendar Public Overrides ReadOnly Property Eras As Integer() Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MinCalendarYear As Integer Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MaxCalendarYear As Integer Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property CalEraInfo As EraInfo() Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MinDate As Date Get Throw New NotImplementedException() End Get End Property Friend Overrides ReadOnly Property MaxDate As Date Get Throw New NotImplementedException() End Get End Property Public Overrides Function GetEra(time As Date) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetYearInfo(LunarYear As Integer, Index As Integer) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetYear(year As Integer, time As Date) As Integer Throw New NotImplementedException() End Function Friend Overrides Function GetGregorianYear(year As Integer, era As Integer) As Integer Throw New NotImplementedException() End Function End Class") End Function <WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")> <WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function TestAutoProperties() As Task Await TestInRegularAndScript1Async( "MustInherit Class AbstractClass MustOverride ReadOnly Property ReadOnlyProp As Integer MustOverride Property ReadWriteProp As Integer MustOverride WriteOnly Property WriteOnlyProp As Integer End Class Class [|C|] Inherits AbstractClass End Class", "MustInherit Class AbstractClass MustOverride ReadOnly Property ReadOnlyProp As Integer MustOverride Property ReadWriteProp As Integer MustOverride WriteOnly Property WriteOnlyProp As Integer End Class Class C Inherits AbstractClass Public Overrides ReadOnly Property ReadOnlyProp As Integer Public Overrides Property ReadWriteProp As Integer Public Overrides WriteOnly Property WriteOnlyProp As Integer Set(value As Integer) Throw New System.NotImplementedException() End Set End Property End Class", parameters:=New TestParameters(options:=[Option]( ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties))) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.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 Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/CallKeywordRecommender.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.Statements ''' <summary> ''' Recommends the "Call" statement. ''' </summary> Friend Class CallKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Call", VBFeaturesResources.Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Call" statement. ''' </summary> Friend Class CallKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Call", VBFeaturesResources.Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasicTest/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers Imports Microsoft.CodeAnalysis.PickMembers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateConstructorFromMembers Public Class GenerateEqualsAndGetHashCodeFromMembersTests Inherits AbstractVisualBasicCodeActionTest Private Const GenerateOperatorsId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId Private Const ImplementIEquatableId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider( DirectCast(parameters.fixProviderData, IPickMembersService)) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestEqualsOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function End Class") End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestBothOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructure() As Task Await TestInRegularAndScriptAsync( "Structure Z [|Private a As Integer|] End Structure", "Imports System Structure Z Implements IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyImplementsInterface1() As Task Await TestInRegularAndScriptAsync( "Structure Z Implements IEquatable(Of Z) [|Private a As Integer|] End Structure", "Structure Z Implements IEquatable(Of Z), System.IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements System.IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyImplementsInterface2() As Task Await TestInRegularAndScriptAsync( "Structure Z Implements System.IEquatable(Of Z) [|Private a As Integer|] End Structure", "Structure Z Implements System.IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean If Not (TypeOf obj Is Z) Then Return False End If Dim z = DirectCast(obj, Z) Return a = z.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyHasOperators() As Task Await TestInRegularAndScriptAsync( "Structure Z [|Private a As Integer|] Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure", "Imports System Structure Z Implements IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(545205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545205")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestTypeWithNumberInName() As Task Await TestInRegularAndScriptAsync( "Partial Class c1(Of V As {New}, U) [|Dim x As New V|] End Class", "Imports System.Collections.Generic Partial Class c1(Of V As {New}, U) Dim x As New V Public Overrides Function Equals(obj As Object) As Boolean Dim c = TryCast(obj, c1(Of V, U)) Return c IsNot Nothing AndAlso EqualityComparer(Of V).Default.Equals(x, c.x) End Function End Class") End Function <WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoBackingField() As Task Await TestWithPickMembersDialogAsync( " Class Program Public Property F() As Integer [||] End Class", " Class Program Public Property F() As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso F = program.F End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoParameterizedProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoIndexer() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoSetterOnlyProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogInheritedMembers() As Task Await TestWithPickMembersDialogAsync( " Class Base Public Property C As Integer End Class Class Middle Inherits Base Public Property B As Integer End Class Class Derived Inherits Middle Public Property A As Integer [||] End Class", " Class Base Public Property C As Integer End Class Class Middle Inherits Base Public Property B As Integer End Class Class Derived Inherits Middle Public Property A As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim derived = TryCast(obj, Derived) Return derived IsNot Nothing AndAlso C = derived.C AndAlso B = derived.B AndAlso A = derived.A End Function End Class", chosenSymbols:=Nothing) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return EqualityComparer(Of Program).Default.Equals(left, right) End Operator Public Shared Operator <>(left As Program, right As Program) As Boolean Return Not left = right End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators3() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] Public Shared Operator =(left As Program, right As Program) As Boolean Return True End Operator End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return True End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) Assert.Null(Options.FirstOrDefault(Function(o) o.Id = GenerateOperatorsId))) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators4() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Structure Program Public s As String [||] End Structure", " Imports System.Collections.Generic Structure Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean If Not (TypeOf obj Is Program) Then Return False End If Dim program = DirectCast(obj, Program) Return s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Program, right As Program) As Boolean Return Not left = right End Operator End Structure", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic structure Program Public s As String [||] End structure", " Imports System Imports System.Collections.Generic structure Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Program) AndAlso Equals(DirectCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return s = other.s End Function End structure", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable2() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System Imports System.Collections.Generic Class Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return Equals(TryCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return other IsNot Nothing AndAlso s = other.s End Function End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class Z [|Private a As Integer Private b As Integer|] End Class", "Option Strict On Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Return (a, b).GetHashCode() End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithoutOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Return -1757793268 + a.GetHashCode() End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithoutValueTuple() As Task Await TestInRegularAndScriptAsync(" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferencesWithoutValueTuple=""true""> <Document> Class Z [|Private a As Integer Private b As Integer|] End Class </Document> </Project> </Workspace>", " Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Dim hashCode = 2118541809 hashCode = hashCode * -1521134295 + a.GetHashCode() hashCode = hashCode * -1521134295 + b.GetHashCode() Return hashCode End Function End Class ", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleOneValue() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer|] Private b As Integer End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleTwoValues() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer Private b As Integer|] End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Return (a, b).GetHashCode() End Function End Class", index:=1) End Function <WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestPartialSelection() As Task Await TestMissingAsync( "Class Z Private [|a|] As Integer End Class") End Function <WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestAbstractBase() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Class HashCode End Class End Namespace MustInherit Class Base Public MustOverride Overrides Function Equals(obj As Object) As Boolean Public MustOverride Overrides Function GetHashCode() As Integer End Class Class Derived Inherits Base [|Public P As Integer|] End Class ", " Imports System Namespace System Public Class HashCode End Class End Namespace MustInherit Class Base Public MustOverride Overrides Function Equals(obj As Object) As Boolean Public MustOverride Overrides Function GetHashCode() As Integer End Class Class Derived Inherits Base Public P As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim derived = TryCast(obj, Derived) Return derived IsNot Nothing AndAlso P = derived.P End Function Public Overrides Function GetHashCode() As Integer Return HashCode.Combine(P) End Function End Class ", index:=1) 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers Imports Microsoft.CodeAnalysis.PickMembers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateConstructorFromMembers Public Class GenerateEqualsAndGetHashCodeFromMembersTests Inherits AbstractVisualBasicCodeActionTest Private Const GenerateOperatorsId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId Private Const ImplementIEquatableId = GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider( DirectCast(parameters.fixProviderData, IPickMembersService)) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestEqualsOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function End Class") End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestBothOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructure() As Task Await TestInRegularAndScriptAsync( "Structure Z [|Private a As Integer|] End Structure", "Imports System Structure Z Implements IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyImplementsInterface1() As Task Await TestInRegularAndScriptAsync( "Structure Z Implements IEquatable(Of Z) [|Private a As Integer|] End Structure", "Structure Z Implements IEquatable(Of Z), System.IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements System.IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyImplementsInterface2() As Task Await TestInRegularAndScriptAsync( "Structure Z Implements System.IEquatable(Of Z) [|Private a As Integer|] End Structure", "Structure Z Implements System.IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean If Not (TypeOf obj Is Z) Then Return False End If Dim z = DirectCast(obj, Z) Return a = z.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(30396, "https://github.com/dotnet/roslyn/issues/30396")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestStructureThatAlreadyHasOperators() As Task Await TestInRegularAndScriptAsync( "Structure Z [|Private a As Integer|] Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure", "Imports System Structure Z Implements IEquatable(Of Z) Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Z) AndAlso Equals(DirectCast(obj, Z)) End Function Public Function Equals(other As Z) As Boolean Implements IEquatable(Of Z).Equals Return a = other.a End Function Public Shared Operator =(left As Z, right As Z) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Z, right As Z) As Boolean Return Not left = right End Operator End Structure") End Function <WorkItem(545205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545205")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestTypeWithNumberInName() As Task Await TestInRegularAndScriptAsync( "Partial Class c1(Of V As {New}, U) [|Dim x As New V|] End Class", "Imports System.Collections.Generic Partial Class c1(Of V As {New}, U) Dim x As New V Public Overrides Function Equals(obj As Object) As Boolean Dim c = TryCast(obj, c1(Of V, U)) Return c IsNot Nothing AndAlso EqualityComparer(Of V).Default.Equals(x, c.x) End Function End Class") End Function <WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoBackingField() As Task Await TestWithPickMembersDialogAsync( " Class Program Public Property F() As Integer [||] End Class", " Class Program Public Property F() As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso F = program.F End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoParameterizedProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoIndexer() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoSetterOnlyProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogInheritedMembers() As Task Await TestWithPickMembersDialogAsync( " Class Base Public Property C As Integer End Class Class Middle Inherits Base Public Property B As Integer End Class Class Derived Inherits Middle Public Property A As Integer [||] End Class", " Class Base Public Property C As Integer End Class Class Middle Inherits Base Public Property B As Integer End Class Class Derived Inherits Middle Public Property A As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim derived = TryCast(obj, Derived) Return derived IsNot Nothing AndAlso C = derived.C AndAlso B = derived.B AndAlso A = derived.A End Function End Class", chosenSymbols:=Nothing) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return EqualityComparer(Of Program).Default.Equals(left, right) End Operator Public Shared Operator <>(left As Program, right As Program) As Boolean Return Not left = right End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators3() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] Public Shared Operator =(left As Program, right As Program) As Boolean Return True End Operator End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return True End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) Assert.Null(Options.FirstOrDefault(Function(o) o.Id = GenerateOperatorsId))) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators4() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Structure Program Public s As String [||] End Structure", " Imports System.Collections.Generic Structure Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean If Not (TypeOf obj Is Program) Then Return False End If Dim program = DirectCast(obj, Program) Return s = program.s End Function Public Shared Operator =(left As Program, right As Program) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As Program, right As Program) As Boolean Return Not left = right End Operator End Structure", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic structure Program Public s As String [||] End structure", " Imports System Imports System.Collections.Generic structure Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Program) AndAlso Equals(DirectCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return s = other.s End Function End structure", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable2() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System Imports System.Collections.Generic Class Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return Equals(TryCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return other IsNot Nothing AndAlso s = other.s End Function End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class Z [|Private a As Integer Private b As Integer|] End Class", "Option Strict On Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Return (a, b).GetHashCode() End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithoutOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Return -1757793268 + a.GetHashCode() End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithoutValueTuple() As Task Await TestInRegularAndScriptAsync(" <Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferencesWithoutValueTuple=""true""> <Document> Class Z [|Private a As Integer Private b As Integer|] End Class </Document> </Project> </Workspace>", " Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Dim hashCode = 2118541809 hashCode = hashCode * -1521134295 + a.GetHashCode() hashCode = hashCode * -1521134295 + b.GetHashCode() Return hashCode End Function End Class ", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleOneValue() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer|] Private b As Integer End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleTwoValues() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer Private b As Integer|] End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Return (a, b).GetHashCode() End Function End Class", index:=1) End Function <WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestPartialSelection() As Task Await TestMissingAsync( "Class Z Private [|a|] As Integer End Class") End Function <WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestAbstractBase() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Class HashCode End Class End Namespace MustInherit Class Base Public MustOverride Overrides Function Equals(obj As Object) As Boolean Public MustOverride Overrides Function GetHashCode() As Integer End Class Class Derived Inherits Base [|Public P As Integer|] End Class ", " Imports System Namespace System Public Class HashCode End Class End Namespace MustInherit Class Base Public MustOverride Overrides Function Equals(obj As Object) As Boolean Public MustOverride Overrides Function GetHashCode() As Integer End Class Class Derived Inherits Base Public P As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim derived = TryCast(obj, Derived) Return derived IsNot Nothing AndAlso P = derived.P End Function Public Overrides Function GetHashCode() As Integer Return HashCode.Combine(P) End Function End Class ", index:=1) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/CorTypes.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 CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.CorLibrary Public Class CorTypes Inherits BasicTestBase <Fact()> Public Sub MissingCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.SymbolsTests.CorLibrary.NoMsCorLibRef}) Dim noMsCorLibRef = assemblies(0) For i As Integer = 1 To SpecialType.Count Dim t = noMsCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Equal(TypeKind.Error, t.TypeKind) Assert.NotNull(t.ContainingAssembly) Assert.Equal("<Missing Core Assembly>", t.ContainingAssembly.Identity.Name) Next Dim p = noMsCorLibRef.GlobalNamespace.GetTypeMembers("I1").Single(). GetMembers("M1").OfType(Of MethodSymbol)().Single(). Parameters(0).Type Assert.Equal(TypeKind.Error, p.TypeKind) Assert.Equal(SpecialType.System_Int32, p.SpecialType) End Sub <Fact()> Public Sub PresentCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestMetadata.NetCoreApp.SystemRuntime}) Dim msCorLibRef As MetadataOrSourceAssemblySymbol = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) Dim knownMissingTypes As HashSet(Of Integer) = New HashSet(Of Integer) For i As Integer = 1 To SpecialType.Count Dim t = msCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Same(msCorLibRef, t.ContainingAssembly) If knownMissingTypes.Contains(i) Then ' not present on dotnet core 3.1 Assert.Equal(TypeKind.Error, t.TypeKind) Else Assert.NotEqual(TypeKind.Error, t.TypeKind) End If Next Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) assemblies = MetadataTestHelpers.GetSymbolsForReferences({MetadataReference.CreateFromImage(TestMetadata.ResourcesNetCoreApp.SystemRuntime)}) msCorLibRef = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim namespaces As New Queue(Of NamespaceSymbol)() namespaces.Enqueue(msCorLibRef.Modules(0).GlobalNamespace) Dim count As Integer = 0 While (namespaces.Count > 0) For Each m In namespaces.Dequeue().GetMembers() Dim ns = TryCast(m, NamespaceSymbol) If (ns IsNot Nothing) Then namespaces.Enqueue(ns) ElseIf (DirectCast(m, NamedTypeSymbol).SpecialType <> SpecialType.None) Then count += 1 End If If (count >= SpecialType.Count) Then Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) End If Next End While Assert.Equal(count + knownMissingTypes.Count, CType(SpecialType.Count, Integer)) Assert.Equal(knownMissingTypes.Any(), msCorLibRef.KeepLookingForDeclaredSpecialTypes) End Sub <Fact()> Public Sub FakeCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.SymbolsTests.CorLibrary.FakeMsCorLib.dll}) Dim msCorLibRef = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) For i As Integer = 1 To SpecialType.Count Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim t = msCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) If (t.SpecialType = SpecialType.System_Object) Then Assert.NotEqual(TypeKind.Error, t.TypeKind) Else Assert.Equal(TypeKind.Error, t.TypeKind) Assert.Same(msCorLibRef, t.ContainingAssembly) End If Assert.Same(msCorLibRef, t.ContainingAssembly) Next Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) End Sub <Fact()> Public Sub SourceCorLib() Dim source = <source> namespace System public class Object End Class ENd NAmespace </source> Dim c1 = VisualBasicCompilation.Create("CorLib", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source.Value)}) Assert.Same(c1.Assembly, c1.Assembly.CorLibrary) Dim msCorLibRef = DirectCast(c1.Assembly, MetadataOrSourceAssemblySymbol) For i As Integer = 1 To SpecialType.Count If (i <> SpecialType.System_Object) Then Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim t = c1.Assembly.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Equal(TypeKind.Error, t.TypeKind) Assert.Same(msCorLibRef, t.ContainingAssembly) End If Next Dim system_object = msCorLibRef.Modules(0).GlobalNamespace.GetMembers("System"). Select(Function(m) DirectCast(m, NamespaceSymbol)).Single().GetTypeMembers("Object").Single() Assert.Equal(SpecialType.System_Object, system_object.SpecialType) Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Assert.Same(system_object, c1.Assembly.GetSpecialType(SpecialType.System_Object)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() c1.GetSpecialType(SpecialType.None)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() c1.GetSpecialType(CType(SpecialType.Count + 1, SpecialType))) Assert.Throws(Of ArgumentOutOfRangeException)(Function() msCorLibRef.GetSpecialType(SpecialType.None)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() msCorLibRef.GetSpecialType(CType(SpecialType.Count + 1, SpecialType))) End Sub <Fact()> Public Sub TestGetTypeByNameAndArity() Dim source1 = <source> namespace System Public Class TestClass End Class public class TestClass(Of T) End Class End Namespace </source> Dim source2 = <source> namespace System Public Class TestClass End Class End Namespace </source> Dim c1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source1.Value)}, references:={TestMetadata.Net40.mscorlib}) Assert.Null(c1.GetTypeByMetadataName("DoesntExist")) Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1")) Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2")) Dim c1TestClass As NamedTypeSymbol = c1.GetTypeByMetadataName("System.TestClass") Assert.NotNull(c1TestClass) Dim c1TestClassT As NamedTypeSymbol = c1.GetTypeByMetadataName("System.TestClass`1") Assert.NotNull(c1TestClassT) Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2")) Dim c2 = VisualBasicCompilation.Create("Test2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source2.Value)}, references:={New VisualBasicCompilationReference(c1), TestMetadata.Net40.mscorlib}) Dim c2TestClass As NamedTypeSymbol = c2.GetTypeByMetadataName("System.TestClass") Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly) Dim c3 = VisualBasicCompilation.Create("Test3", references:={New VisualBasicCompilationReference(c2), TestMetadata.Net40.mscorlib}) Dim c3TestClass As NamedTypeSymbol = c3.GetTypeByMetadataName("System.TestClass") Assert.NotSame(c2TestClass, c3TestClass) Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly)) Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1")) Dim c4 = VisualBasicCompilation.Create("Test4", references:={New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2), TestMetadata.Net40.mscorlib}) Dim c4TestClass As NamedTypeSymbol = c4.GetTypeByMetadataName("System.TestClass") Assert.Null(c4TestClass) Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`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. Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.CorLibrary Public Class CorTypes Inherits BasicTestBase <Fact()> Public Sub MissingCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.SymbolsTests.CorLibrary.NoMsCorLibRef}) Dim noMsCorLibRef = assemblies(0) For i As Integer = 1 To SpecialType.Count Dim t = noMsCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Equal(TypeKind.Error, t.TypeKind) Assert.NotNull(t.ContainingAssembly) Assert.Equal("<Missing Core Assembly>", t.ContainingAssembly.Identity.Name) Next Dim p = noMsCorLibRef.GlobalNamespace.GetTypeMembers("I1").Single(). GetMembers("M1").OfType(Of MethodSymbol)().Single(). Parameters(0).Type Assert.Equal(TypeKind.Error, p.TypeKind) Assert.Equal(SpecialType.System_Int32, p.SpecialType) End Sub <Fact()> Public Sub PresentCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestMetadata.NetCoreApp.SystemRuntime}) Dim msCorLibRef As MetadataOrSourceAssemblySymbol = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) Dim knownMissingTypes As HashSet(Of Integer) = New HashSet(Of Integer) For i As Integer = 1 To SpecialType.Count Dim t = msCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Same(msCorLibRef, t.ContainingAssembly) If knownMissingTypes.Contains(i) Then ' not present on dotnet core 3.1 Assert.Equal(TypeKind.Error, t.TypeKind) Else Assert.NotEqual(TypeKind.Error, t.TypeKind) End If Next Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) assemblies = MetadataTestHelpers.GetSymbolsForReferences({MetadataReference.CreateFromImage(TestMetadata.ResourcesNetCoreApp.SystemRuntime)}) msCorLibRef = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim namespaces As New Queue(Of NamespaceSymbol)() namespaces.Enqueue(msCorLibRef.Modules(0).GlobalNamespace) Dim count As Integer = 0 While (namespaces.Count > 0) For Each m In namespaces.Dequeue().GetMembers() Dim ns = TryCast(m, NamespaceSymbol) If (ns IsNot Nothing) Then namespaces.Enqueue(ns) ElseIf (DirectCast(m, NamedTypeSymbol).SpecialType <> SpecialType.None) Then count += 1 End If If (count >= SpecialType.Count) Then Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) End If Next End While Assert.Equal(count + knownMissingTypes.Count, CType(SpecialType.Count, Integer)) Assert.Equal(knownMissingTypes.Any(), msCorLibRef.KeepLookingForDeclaredSpecialTypes) End Sub <Fact()> Public Sub FakeCorLib() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences({TestReferences.SymbolsTests.CorLibrary.FakeMsCorLib.dll}) Dim msCorLibRef = DirectCast(assemblies(0), MetadataOrSourceAssemblySymbol) For i As Integer = 1 To SpecialType.Count Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim t = msCorLibRef.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) If (t.SpecialType = SpecialType.System_Object) Then Assert.NotEqual(TypeKind.Error, t.TypeKind) Else Assert.Equal(TypeKind.Error, t.TypeKind) Assert.Same(msCorLibRef, t.ContainingAssembly) End If Assert.Same(msCorLibRef, t.ContainingAssembly) Next Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) End Sub <Fact()> Public Sub SourceCorLib() Dim source = <source> namespace System public class Object End Class ENd NAmespace </source> Dim c1 = VisualBasicCompilation.Create("CorLib", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source.Value)}) Assert.Same(c1.Assembly, c1.Assembly.CorLibrary) Dim msCorLibRef = DirectCast(c1.Assembly, MetadataOrSourceAssemblySymbol) For i As Integer = 1 To SpecialType.Count If (i <> SpecialType.System_Object) Then Assert.True(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Dim t = c1.Assembly.GetSpecialType(CType(i, SpecialType)) Assert.Equal(CType(i, SpecialType), t.SpecialType) Assert.Equal(TypeKind.Error, t.TypeKind) Assert.Same(msCorLibRef, t.ContainingAssembly) End If Next Dim system_object = msCorLibRef.Modules(0).GlobalNamespace.GetMembers("System"). Select(Function(m) DirectCast(m, NamespaceSymbol)).Single().GetTypeMembers("Object").Single() Assert.Equal(SpecialType.System_Object, system_object.SpecialType) Assert.False(msCorLibRef.KeepLookingForDeclaredSpecialTypes) Assert.Same(system_object, c1.Assembly.GetSpecialType(SpecialType.System_Object)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() c1.GetSpecialType(SpecialType.None)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() c1.GetSpecialType(CType(SpecialType.Count + 1, SpecialType))) Assert.Throws(Of ArgumentOutOfRangeException)(Function() msCorLibRef.GetSpecialType(SpecialType.None)) Assert.Throws(Of ArgumentOutOfRangeException)(Function() msCorLibRef.GetSpecialType(CType(SpecialType.Count + 1, SpecialType))) End Sub <Fact()> Public Sub TestGetTypeByNameAndArity() Dim source1 = <source> namespace System Public Class TestClass End Class public class TestClass(Of T) End Class End Namespace </source> Dim source2 = <source> namespace System Public Class TestClass End Class End Namespace </source> Dim c1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source1.Value)}, references:={TestMetadata.Net40.mscorlib}) Assert.Null(c1.GetTypeByMetadataName("DoesntExist")) Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1")) Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2")) Dim c1TestClass As NamedTypeSymbol = c1.GetTypeByMetadataName("System.TestClass") Assert.NotNull(c1TestClass) Dim c1TestClassT As NamedTypeSymbol = c1.GetTypeByMetadataName("System.TestClass`1") Assert.NotNull(c1TestClassT) Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2")) Dim c2 = VisualBasicCompilation.Create("Test2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(source2.Value)}, references:={New VisualBasicCompilationReference(c1), TestMetadata.Net40.mscorlib}) Dim c2TestClass As NamedTypeSymbol = c2.GetTypeByMetadataName("System.TestClass") Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly) Dim c3 = VisualBasicCompilation.Create("Test3", references:={New VisualBasicCompilationReference(c2), TestMetadata.Net40.mscorlib}) Dim c3TestClass As NamedTypeSymbol = c3.GetTypeByMetadataName("System.TestClass") Assert.NotSame(c2TestClass, c3TestClass) Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly)) Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1")) Dim c4 = VisualBasicCompilation.Create("Test4", references:={New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2), TestMetadata.Net40.mscorlib}) Dim c4TestClass As NamedTypeSymbol = c4.GetTypeByMetadataName("System.TestClass") Assert.Null(c4TestClass) Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1")) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Features/VisualBasic/Portable/SignatureHelp/CastExpressionSignatureHelpProvider.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.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("CastExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class CastExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of CastExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As CastExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Select Case node.Kind Case SyntaxKind.CTypeExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New CTypeCastExpressionDocumentation()}) Case SyntaxKind.DirectCastExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New DirectCastExpressionDocumentation()}) Case SyntaxKind.TryCastExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New TryCastExpressionDocumentation()}) End Select Return ValueTaskFactory.FromResult(SpecializedCollections.EmptyEnumerable(Of AbstractIntrinsicOperatorDocumentation)()) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of CastExpressionSyntax)(Function(ce) ce.OpenParenToken) OrElse token.IsChildToken(Of CastExpressionSyntax)(Function(ce) ce.CommaToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As CastExpressionSyntax, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso node.OpenParenToken.SpanStart <= token.SpanStart AndAlso token <> node.CloseParenToken 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.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("CastExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class CastExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of CastExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As CastExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Select Case node.Kind Case SyntaxKind.CTypeExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New CTypeCastExpressionDocumentation()}) Case SyntaxKind.DirectCastExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New DirectCastExpressionDocumentation()}) Case SyntaxKind.TryCastExpression Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New TryCastExpressionDocumentation()}) End Select Return ValueTaskFactory.FromResult(SpecializedCollections.EmptyEnumerable(Of AbstractIntrinsicOperatorDocumentation)()) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of CastExpressionSyntax)(Function(ce) ce.OpenParenToken) OrElse token.IsChildToken(Of CastExpressionSyntax)(Function(ce) ce.CommaToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As CastExpressionSyntax, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso node.OpenParenToken.SpanStart <= token.SpanStart AndAlso token <> node.CloseParenToken End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.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.Windows.Data Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class StyleViewModel Inherits AbstractOptionPreviewViewModel #Region "Preview Text" Private Const s_fieldDeclarationPreviewTrue As String = " Class C Private capacity As Integer Sub Method() '//[ Me.capacity = 0 '//] End Sub End Class " Private Const s_fieldDeclarationPreviewFalse As String = " Class C Private capacity As Integer Sub Method() '//[ capacity = 0 '//] End Sub End Class " Private Const s_propertyDeclarationPreviewTrue As String = " Class C Public Property Id As Integer Sub Method() '//[ Me.Id = 0 '//] End Sub End Class " Private Const s_propertyDeclarationPreviewFalse As String = " Class C Public Property Id As Integer Sub Method() '//[ Id = 0 '//] End Sub End Class " Private Const s_methodDeclarationPreviewTrue As String = " Class C Sub Display() '//[ Me.Display() '//] End Sub End Class " Private Const s_methodDeclarationPreviewFalse As String = " Class C Sub Display() '//[ Display() '//] End Sub End Class " Private Const s_eventDeclarationPreviewTrue As String = " Imports System Class C Public Event Elapsed As EventHandler Sub Handler(sender As Object, args As EventArgs) '//[ AddHandler Me.Elapsed, AddressOf Handler '//] End Sub End Class " Private Const s_eventDeclarationPreviewFalse As String = " Imports System Class C Public Event Elapsed As EventHandler Sub Handler(sender As Object, args As EventArgs) '//[ AddHandler Elapsed, AddressOf Handler '//] End Sub End Class " Private ReadOnly _intrinsicDeclarationPreviewTrue As String = <a><![CDATA[ Class Program '//[ Private _member As Integer Sub M(argument As Integer) Dim local As Integer = 0 End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicDeclarationPreviewFalse As String = <a><![CDATA[ Class Program '//[ Private _member As Int32 Sub M(argument As Int32) Dim local As Int32 = 0 End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicMemberAccessPreviewTrue As String = <a><![CDATA[ Imports System Class Program '//[ Sub M() Dim local = Integer.MaxValue End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicMemberAccessPreviewFalse As String = <a><![CDATA[ Imports System Class Program '//[ Sub M() Dim local = Int32.MaxValue End Sub '//] End Class ]]></a>.Value Private Shared ReadOnly s_preferObjectInitializer As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim c = New Customer() With {{ .Age = 21 }} //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim c = New Customer() c.Age = 21 //] End Sub End Class" Private Shared ReadOnly s_preferCollectionInitializer As String = $" Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim list = New List(Of Integer) From {{ 1, 2, 3 }} //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim list = New List(Of Integer)() list.Add(1) list.Add(2) list.Add(3) //] End Sub End Class" Private Shared ReadOnly s_preferSimplifiedConditionalExpressions As String = $" Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim x = A() AndAlso B() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim x = If(A() AndAlso B(), True, False) //] End Sub Function A() As Boolean Return True End Function Function B() As Boolean Return True End Function End Class" Private Shared ReadOnly s_preferExplicitTupleName As String = $" Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim customer As (name As String, age As Integer) Dim name = customer.name Dim age = customer.age //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim customer As (name As String, age As Integer) Dim name = customer.Item1 Dim age = customer.Item2 //] End Sub end class " Private Shared ReadOnly s_preferInferredTupleName As String = $" Class Customer Sub M1(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim tuple = (name, age) //] End Sub Sub M2(name as String, age As Integer) //[ ' {ServicesVSResources.Over_colon} Dim tuple = (name:=name, age:=age) //] End Sub end class " Private Shared ReadOnly s_preferInferredAnonymousTypeMemberName As String = $" Class Customer Sub M1(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim anon = New With {{ name, age }} //] End Sub Sub M2(name as String, age As Integer) //[ ' {ServicesVSResources.Over_colon} Dim anon = New With {{ .name = name, .age = age }} //] End Sub end class " Private Shared ReadOnly s_preferConditionalExpressionOverIfWithAssignments As String = $" Class Customer Public Sub New(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim s As String = If(expr, ""hello"", ""world"") ' {ServicesVSResources.Over_colon} Dim s As String If expr Then s = ""hello"" Else s = ""world"" End If //] End Sub end class " Private Shared ReadOnly s_preferConditionalExpressionOverIfWithReturns As String = $" Class Customer Public Sub New(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Return If(expr, ""hello"", ""world"") ' {ServicesVSResources.Over_colon} If expr Then Return ""hello"" Else Return ""world"" End If //] End Sub end class " Private Shared ReadOnly s_preferCoalesceExpression As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim v = If(x, y) //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim v = If(x Is Nothing, y, x) ' {ServicesVSResources.or} Dim v = If(x IsNot Nothing, x, y) //] End Sub End Class" Private Shared ReadOnly s_preferNullPropagation As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim v = o?.ToString() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim v = If(o Is Nothing, Nothing, o.ToString()) ' {ServicesVSResources.or} Dim v = If(o IsNot Nothing, o.ToString(), Nothing) //] End Sub End Class" Private Shared ReadOnly s_preferAutoProperties As String = $" Imports System Class Customer1 //[ ' {ServicesVSResources.Prefer_colon} Public ReadOnly Property Age As Integer //] End Class Class Customer2 //[ ' {ServicesVSResources.Over_colon} Private _age As Integer Public ReadOnly Property Age As Integer Get return _age End Get End Property //] End Class " Private Shared ReadOnly s_preferSystemHashCode As String = $" Imports System Class Customer1 Dim a, b, c As Integer //[ ' {ServicesVSResources.Prefer_colon} // {ServicesVSResources.Requires_System_HashCode_be_present_in_project} Public Overrides Function GetHashCodeAsInteger() Return System.HashCode.Combine(a, b, c) End Function //] End Class Class Customer2 Dim a, b, c As Integer //[ ' {ServicesVSResources.Over_colon} Public Overrides Function GetHashCodeAsInteger() Dim hashCode = 339610899 hashCode = hashCode * -1521134295 + a.GetHashCode() hashCode = hashCode * -1521134295 + b.GetHashCode() hashCode = hashCode * -1521134295 + c.GetHashCode() return hashCode End Function //] End Class " Private Shared ReadOnly s_preferIsNothingCheckOverReferenceEquals As String = $" Imports System Class Customer Sub M1(value as object) //[ ' {ServicesVSResources.Prefer_colon} If value Is Nothing Return End If //] End Sub Sub M2(value as object) //[ ' {ServicesVSResources.Over_colon} If Object.ReferenceEquals(value, Nothing) Return End If //] End Sub End Class" Private Shared ReadOnly s_preferCompoundAssignments As String = $" Imports System Class Customer Sub M1(value as integer) //[ ' {ServicesVSResources.Prefer_colon} value += 10 //] End Sub Sub M2(value as integer) //[ ' {ServicesVSResources.Over_colon} value = value + 10 //] End Sub End Class" Private Shared ReadOnly s_preferIsNotExpression As String = $" Imports System Class Customer Sub M1(value as object) //[ ' {ServicesVSResources.Prefer_colon} Dim isSomething = value IsNot Nothing //] End Sub Sub M2(value as object) //[ ' {ServicesVSResources.Over_colon} Dim isSomething = Not value Is Nothing //] End Sub End Class" Private Shared ReadOnly s_preferSimplifiedObjectCreation As String = $" Imports System Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim c As New Customer() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim c As Customer = New Customer() //] End Sub End Class" #Region "arithmetic binary parentheses" Private Shared ReadOnly s_arithmeticBinaryAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a + (b * c) ' {ServicesVSResources.Over_colon} Dim v = a + b * c //] end sub end class " Private Shared ReadOnly s_arithmeticBinaryNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a + b * c ' {ServicesVSResources.Over_colon} Dim v = a + (b * c) //] end sub end class " #End Region #Region "relational binary parentheses" Private Shared ReadOnly s_relationalBinaryAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Keep_all_parentheses_in_colon} Dim v = (a < b) = (c > d) //] end sub end class " Private Shared ReadOnly s_relationalBinaryNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a < b = c > d ' {ServicesVSResources.Over_colon} Dim v = (a < b) = (c > d) //] end sub end class " #End Region #Region "other binary parentheses" Private ReadOnly s_otherBinaryAlwaysForClarity As String = $" class C sub M() //[ // {ServicesVSResources.Prefer_colon} Dim v = a OrElse (b AndAlso c) // {ServicesVSResources.Over_colon} Dim v = a OrElse b AndAlso c //] end sub end class " Private ReadOnly s_otherBinaryNeverIfUnnecessary As String = $" class C sub M() //[ // {ServicesVSResources.Prefer_colon} Dim v = a OrElse b AndAlso c // {ServicesVSResources.Over_colon} Dim v = a OrElse (b AndAlso c) //] end sub end class " #End Region #Region "other parentheses" Private Shared ReadOnly s_otherParenthesesAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Keep_all_parentheses_in_colon} Dim v = (a.b).Length //] end sub end class " Private Shared ReadOnly s_otherParenthesesNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a.b.Length ' {ServicesVSResources.Over_colon} Dim v = (a.b).Length //] end sub end class " #End Region Private Shared ReadOnly s_preferReadonly As String = $" Class Customer1 //[ ' {ServicesVSResources.Prefer_colon} ' 'value' can only be assigned in constructor Private ReadOnly value As Integer = 0 //] End Class Class Customer2 //[ ' {ServicesVSResources.Over_colon} ' 'value' can be assigned anywhere Private value As Integer = 0 //] End Class" Private Shared ReadOnly s_allow_multiple_blank_lines_true As String = $" Class Customer2 Sub Method() //[ ' {ServicesVSResources.Allow_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_multiple_blank_lines_false As String = $" Class Customer1 Sub Method() //[ ' {ServicesVSResources.Require_colon} If True Then DoWork() End If Return //] End Sub End Class Class Customer2 Sub Method() //[ ' {ServicesVSResources.Over_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_statement_immediately_after_block_true As String = $" Class Customer2 Sub Method() //[ ' {ServicesVSResources.Allow_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_statement_immediately_after_block_false As String = $" Class Customer1 Sub Method() //[ ' {ServicesVSResources.Require_colon} If True Then DoWork() End If Return //] End Sub End Class Class Customer2 Sub Method() //[ ' {ServicesVSResources.Over_colon} If True Then DoWork() End If Return //] End Sub End Class" #Region "unused parameters" Private Shared ReadOnly s_avoidUnusedParametersNonPublicMethods As String = $" Public Class C1 //[ ' {ServicesVSResources.Prefer_colon} Private Sub M() End Sub //] End Class Public Class C2 //[ ' {ServicesVSResources.Over_colon} Private Sub M(param As Integer) End Sub //] End Class " Private Shared ReadOnly s_avoidUnusedParametersAllMethods As String = $" Public Class C1 //[ ' {ServicesVSResources.Prefer_colon} Public Sub M() End Sub //] End Class Public Class C2 //[ ' {ServicesVSResources.Over_colon} Public Sub M(param As Integer) End Sub //] End Class " #End Region #Region "unused values" Private Shared ReadOnly s_avoidUnusedValueAssignmentUnusedLocal As String = $" Class C1 Function M() As Integer //[ ' {ServicesVSResources.Prefer_colon} Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} Dim x = 1 //] Return x End Function End Class Class C2 Function M() As Integer //[ ' {ServicesVSResources.Over_colon} Dim x = Computation() ' {ServicesVSResources.Value_assigned_here_is_never_used} x = 1 //] Return x End Function End Class " Private Shared ReadOnly s_avoidUnusedValueExpressionStatementUnusedLocal As String = $" Class C1 Sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} //] End Sub End Class Class C2 Sub M() //[ ' {ServicesVSResources.Over_colon} Computation() ' {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] End Sub End Class " #End Region #End Region Public Sub New(optionStore As OptionStore, serviceProvider As IServiceProvider) MyBase.New(optionStore, serviceProvider, LanguageNames.VisualBasic) Dim collectionView = DirectCast(CollectionViewSource.GetDefaultView(CodeStyleItems), ListCollectionView) collectionView.GroupDescriptions.Add(New PropertyGroupDescription(NameOf(AbstractCodeStyleOptionViewModel.GroupName))) Dim qualifyGroupTitle = BasicVSResources.Me_preferences_colon Dim qualifyMemberAccessPreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(BasicVSResources.Prefer_Me, isChecked:=True), New CodeStylePreference(BasicVSResources.Do_not_prefer_Me, isChecked:=False) } Dim predefinedTypesGroupTitle = BasicVSResources.Predefined_type_preferences_colon Dim predefinedTypesPreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked:=True), New CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked:=False) } Dim codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon Dim expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon Dim nothingPreferencesGroupTitle = BasicVSResources.nothing_checking_colon Dim fieldPreferencesGroupTitle = ServicesVSResources.Modifier_preferences_colon Dim parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon Dim newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon ' qualify with Me. group Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, BasicVSResources.Qualify_field_access_with_Me, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, BasicVSResources.Qualify_property_access_with_Me, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, BasicVSResources.Qualify_method_access_with_Me, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, BasicVSResources.Qualify_event_access_with_Me, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) ' predefined or framework type group Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, _intrinsicDeclarationPreviewTrue, _intrinsicDeclarationPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, _intrinsicMemberAccessPreviewTrue, _intrinsicMemberAccessPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) AddParenthesesOptions(optionStore) ' Code block Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, Me, optionStore, codeBlockPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, Me, optionStore, codeBlockPreferencesGroupTitle)) ' expression preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpressions, s_preferSimplifiedConditionalExpressions, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(VisualBasicCodeStyleOptions.PreferIsNotExpression, BasicVSResources.Prefer_IsNot_expression, s_preferIsNotExpression, s_preferIsNotExpression, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, BasicVSResources.Prefer_simplified_object_creation, s_preferSimplifiedObjectCreation, s_preferSimplifiedObjectCreation, Me, optionStore, expressionPreferencesGroupTitle)) AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle) ' nothing preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, Me, optionStore, nothingPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, Me, optionStore, nothingPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, BasicVSResources.Prefer_Is_Nothing_for_reference_equality_checks, s_preferIsNothingCheckOverReferenceEquals, s_preferIsNothingCheckOverReferenceEquals, Me, optionStore, nothingPreferencesGroupTitle)) ' Field preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, Me, optionStore, fieldPreferencesGroupTitle)) ' Parameter preferences AddParameterOptions(optionStore, parameterPreferencesGroupTitle) ' New line preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, Me, optionStore, newLinePreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_true, Me, optionStore, newLinePreferencesGroupTitle)) End Sub Private Sub AddParenthesesOptions(optionStore As OptionStore) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, BasicVSResources.In_arithmetic_binary_operators, {s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherBinaryParentheses, BasicVSResources.In_other_binary_operators, {s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, BasicVSResources.In_relational_binary_operators, {s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, {s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary}, defaultAddForClarity:=False) End Sub Private Sub AddUnusedValueOptions(optionStore As OptionStore, expressionPreferencesGroupTitle As String) Dim unusedValuePreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(BasicVSResources.Unused_local, isChecked:=True) } Dim enumValues = { UnusedValuePreference.UnusedLocalVariable } Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)( VisualBasicCodeStyleOptions.UnusedValueAssignment, ServicesVSResources.Avoid_unused_value_assignments, enumValues, {s_avoidUnusedValueAssignmentUnusedLocal}, Me, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)) Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)( VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value, enumValues, {s_avoidUnusedValueExpressionStatementUnusedLocal}, Me, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)) End Sub Private Sub AddParameterOptions(optionStore As OptionStore, parameterPreferencesGroupTitle As String) Dim examples = { s_avoidUnusedParametersNonPublicMethods, s_avoidUnusedParametersAllMethods } AddUnusedParameterOption(LanguageNames.VisualBasic, optionStore, parameterPreferencesGroupTitle, examples) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Windows.Data Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class StyleViewModel Inherits AbstractOptionPreviewViewModel #Region "Preview Text" Private Const s_fieldDeclarationPreviewTrue As String = " Class C Private capacity As Integer Sub Method() '//[ Me.capacity = 0 '//] End Sub End Class " Private Const s_fieldDeclarationPreviewFalse As String = " Class C Private capacity As Integer Sub Method() '//[ capacity = 0 '//] End Sub End Class " Private Const s_propertyDeclarationPreviewTrue As String = " Class C Public Property Id As Integer Sub Method() '//[ Me.Id = 0 '//] End Sub End Class " Private Const s_propertyDeclarationPreviewFalse As String = " Class C Public Property Id As Integer Sub Method() '//[ Id = 0 '//] End Sub End Class " Private Const s_methodDeclarationPreviewTrue As String = " Class C Sub Display() '//[ Me.Display() '//] End Sub End Class " Private Const s_methodDeclarationPreviewFalse As String = " Class C Sub Display() '//[ Display() '//] End Sub End Class " Private Const s_eventDeclarationPreviewTrue As String = " Imports System Class C Public Event Elapsed As EventHandler Sub Handler(sender As Object, args As EventArgs) '//[ AddHandler Me.Elapsed, AddressOf Handler '//] End Sub End Class " Private Const s_eventDeclarationPreviewFalse As String = " Imports System Class C Public Event Elapsed As EventHandler Sub Handler(sender As Object, args As EventArgs) '//[ AddHandler Elapsed, AddressOf Handler '//] End Sub End Class " Private ReadOnly _intrinsicDeclarationPreviewTrue As String = <a><![CDATA[ Class Program '//[ Private _member As Integer Sub M(argument As Integer) Dim local As Integer = 0 End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicDeclarationPreviewFalse As String = <a><![CDATA[ Class Program '//[ Private _member As Int32 Sub M(argument As Int32) Dim local As Int32 = 0 End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicMemberAccessPreviewTrue As String = <a><![CDATA[ Imports System Class Program '//[ Sub M() Dim local = Integer.MaxValue End Sub '//] End Class ]]></a>.Value Private ReadOnly _intrinsicMemberAccessPreviewFalse As String = <a><![CDATA[ Imports System Class Program '//[ Sub M() Dim local = Int32.MaxValue End Sub '//] End Class ]]></a>.Value Private Shared ReadOnly s_preferObjectInitializer As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim c = New Customer() With {{ .Age = 21 }} //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim c = New Customer() c.Age = 21 //] End Sub End Class" Private Shared ReadOnly s_preferCollectionInitializer As String = $" Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim list = New List(Of Integer) From {{ 1, 2, 3 }} //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim list = New List(Of Integer)() list.Add(1) list.Add(2) list.Add(3) //] End Sub End Class" Private Shared ReadOnly s_preferSimplifiedConditionalExpressions As String = $" Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim x = A() AndAlso B() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim x = If(A() AndAlso B(), True, False) //] End Sub Function A() As Boolean Return True End Function Function B() As Boolean Return True End Function End Class" Private Shared ReadOnly s_preferExplicitTupleName As String = $" Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim customer As (name As String, age As Integer) Dim name = customer.name Dim age = customer.age //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim customer As (name As String, age As Integer) Dim name = customer.Item1 Dim age = customer.Item2 //] End Sub end class " Private Shared ReadOnly s_preferInferredTupleName As String = $" Class Customer Sub M1(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim tuple = (name, age) //] End Sub Sub M2(name as String, age As Integer) //[ ' {ServicesVSResources.Over_colon} Dim tuple = (name:=name, age:=age) //] End Sub end class " Private Shared ReadOnly s_preferInferredAnonymousTypeMemberName As String = $" Class Customer Sub M1(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim anon = New With {{ name, age }} //] End Sub Sub M2(name as String, age As Integer) //[ ' {ServicesVSResources.Over_colon} Dim anon = New With {{ .name = name, .age = age }} //] End Sub end class " Private Shared ReadOnly s_preferConditionalExpressionOverIfWithAssignments As String = $" Class Customer Public Sub New(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Dim s As String = If(expr, ""hello"", ""world"") ' {ServicesVSResources.Over_colon} Dim s As String If expr Then s = ""hello"" Else s = ""world"" End If //] End Sub end class " Private Shared ReadOnly s_preferConditionalExpressionOverIfWithReturns As String = $" Class Customer Public Sub New(name as String, age As Integer) //[ ' {ServicesVSResources.Prefer_colon} Return If(expr, ""hello"", ""world"") ' {ServicesVSResources.Over_colon} If expr Then Return ""hello"" Else Return ""world"" End If //] End Sub end class " Private Shared ReadOnly s_preferCoalesceExpression As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim v = If(x, y) //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim v = If(x Is Nothing, y, x) ' {ServicesVSResources.or} Dim v = If(x IsNot Nothing, x, y) //] End Sub End Class" Private Shared ReadOnly s_preferNullPropagation As String = $" Imports System Class Customer Private Age As Integer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim v = o?.ToString() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim v = If(o Is Nothing, Nothing, o.ToString()) ' {ServicesVSResources.or} Dim v = If(o IsNot Nothing, o.ToString(), Nothing) //] End Sub End Class" Private Shared ReadOnly s_preferAutoProperties As String = $" Imports System Class Customer1 //[ ' {ServicesVSResources.Prefer_colon} Public ReadOnly Property Age As Integer //] End Class Class Customer2 //[ ' {ServicesVSResources.Over_colon} Private _age As Integer Public ReadOnly Property Age As Integer Get return _age End Get End Property //] End Class " Private Shared ReadOnly s_preferSystemHashCode As String = $" Imports System Class Customer1 Dim a, b, c As Integer //[ ' {ServicesVSResources.Prefer_colon} // {ServicesVSResources.Requires_System_HashCode_be_present_in_project} Public Overrides Function GetHashCodeAsInteger() Return System.HashCode.Combine(a, b, c) End Function //] End Class Class Customer2 Dim a, b, c As Integer //[ ' {ServicesVSResources.Over_colon} Public Overrides Function GetHashCodeAsInteger() Dim hashCode = 339610899 hashCode = hashCode * -1521134295 + a.GetHashCode() hashCode = hashCode * -1521134295 + b.GetHashCode() hashCode = hashCode * -1521134295 + c.GetHashCode() return hashCode End Function //] End Class " Private Shared ReadOnly s_preferIsNothingCheckOverReferenceEquals As String = $" Imports System Class Customer Sub M1(value as object) //[ ' {ServicesVSResources.Prefer_colon} If value Is Nothing Return End If //] End Sub Sub M2(value as object) //[ ' {ServicesVSResources.Over_colon} If Object.ReferenceEquals(value, Nothing) Return End If //] End Sub End Class" Private Shared ReadOnly s_preferCompoundAssignments As String = $" Imports System Class Customer Sub M1(value as integer) //[ ' {ServicesVSResources.Prefer_colon} value += 10 //] End Sub Sub M2(value as integer) //[ ' {ServicesVSResources.Over_colon} value = value + 10 //] End Sub End Class" Private Shared ReadOnly s_preferIsNotExpression As String = $" Imports System Class Customer Sub M1(value as object) //[ ' {ServicesVSResources.Prefer_colon} Dim isSomething = value IsNot Nothing //] End Sub Sub M2(value as object) //[ ' {ServicesVSResources.Over_colon} Dim isSomething = Not value Is Nothing //] End Sub End Class" Private Shared ReadOnly s_preferSimplifiedObjectCreation As String = $" Imports System Class Customer Sub M1() //[ ' {ServicesVSResources.Prefer_colon} Dim c As New Customer() //] End Sub Sub M2() //[ ' {ServicesVSResources.Over_colon} Dim c As Customer = New Customer() //] End Sub End Class" #Region "arithmetic binary parentheses" Private Shared ReadOnly s_arithmeticBinaryAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a + (b * c) ' {ServicesVSResources.Over_colon} Dim v = a + b * c //] end sub end class " Private Shared ReadOnly s_arithmeticBinaryNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a + b * c ' {ServicesVSResources.Over_colon} Dim v = a + (b * c) //] end sub end class " #End Region #Region "relational binary parentheses" Private Shared ReadOnly s_relationalBinaryAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Keep_all_parentheses_in_colon} Dim v = (a < b) = (c > d) //] end sub end class " Private Shared ReadOnly s_relationalBinaryNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a < b = c > d ' {ServicesVSResources.Over_colon} Dim v = (a < b) = (c > d) //] end sub end class " #End Region #Region "other binary parentheses" Private ReadOnly s_otherBinaryAlwaysForClarity As String = $" class C sub M() //[ // {ServicesVSResources.Prefer_colon} Dim v = a OrElse (b AndAlso c) // {ServicesVSResources.Over_colon} Dim v = a OrElse b AndAlso c //] end sub end class " Private ReadOnly s_otherBinaryNeverIfUnnecessary As String = $" class C sub M() //[ // {ServicesVSResources.Prefer_colon} Dim v = a OrElse b AndAlso c // {ServicesVSResources.Over_colon} Dim v = a OrElse (b AndAlso c) //] end sub end class " #End Region #Region "other parentheses" Private Shared ReadOnly s_otherParenthesesAlwaysForClarity As String = $" class C sub M() //[ ' {ServicesVSResources.Keep_all_parentheses_in_colon} Dim v = (a.b).Length //] end sub end class " Private Shared ReadOnly s_otherParenthesesNeverIfUnnecessary As String = $" class C sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim v = a.b.Length ' {ServicesVSResources.Over_colon} Dim v = (a.b).Length //] end sub end class " #End Region Private Shared ReadOnly s_preferReadonly As String = $" Class Customer1 //[ ' {ServicesVSResources.Prefer_colon} ' 'value' can only be assigned in constructor Private ReadOnly value As Integer = 0 //] End Class Class Customer2 //[ ' {ServicesVSResources.Over_colon} ' 'value' can be assigned anywhere Private value As Integer = 0 //] End Class" Private Shared ReadOnly s_allow_multiple_blank_lines_true As String = $" Class Customer2 Sub Method() //[ ' {ServicesVSResources.Allow_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_multiple_blank_lines_false As String = $" Class Customer1 Sub Method() //[ ' {ServicesVSResources.Require_colon} If True Then DoWork() End If Return //] End Sub End Class Class Customer2 Sub Method() //[ ' {ServicesVSResources.Over_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_statement_immediately_after_block_true As String = $" Class Customer2 Sub Method() //[ ' {ServicesVSResources.Allow_colon} If True Then DoWork() End If Return //] End Sub End Class" Private Shared ReadOnly s_allow_statement_immediately_after_block_false As String = $" Class Customer1 Sub Method() //[ ' {ServicesVSResources.Require_colon} If True Then DoWork() End If Return //] End Sub End Class Class Customer2 Sub Method() //[ ' {ServicesVSResources.Over_colon} If True Then DoWork() End If Return //] End Sub End Class" #Region "unused parameters" Private Shared ReadOnly s_avoidUnusedParametersNonPublicMethods As String = $" Public Class C1 //[ ' {ServicesVSResources.Prefer_colon} Private Sub M() End Sub //] End Class Public Class C2 //[ ' {ServicesVSResources.Over_colon} Private Sub M(param As Integer) End Sub //] End Class " Private Shared ReadOnly s_avoidUnusedParametersAllMethods As String = $" Public Class C1 //[ ' {ServicesVSResources.Prefer_colon} Public Sub M() End Sub //] End Class Public Class C2 //[ ' {ServicesVSResources.Over_colon} Public Sub M(param As Integer) End Sub //] End Class " #End Region #Region "unused values" Private Shared ReadOnly s_avoidUnusedValueAssignmentUnusedLocal As String = $" Class C1 Function M() As Integer //[ ' {ServicesVSResources.Prefer_colon} Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} Dim x = 1 //] Return x End Function End Class Class C2 Function M() As Integer //[ ' {ServicesVSResources.Over_colon} Dim x = Computation() ' {ServicesVSResources.Value_assigned_here_is_never_used} x = 1 //] Return x End Function End Class " Private Shared ReadOnly s_avoidUnusedValueExpressionStatementUnusedLocal As String = $" Class C1 Sub M() //[ ' {ServicesVSResources.Prefer_colon} Dim unused = Computation() ' {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} //] End Sub End Class Class C2 Sub M() //[ ' {ServicesVSResources.Over_colon} Computation() ' {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] End Sub End Class " #End Region #End Region Public Sub New(optionStore As OptionStore, serviceProvider As IServiceProvider) MyBase.New(optionStore, serviceProvider, LanguageNames.VisualBasic) Dim collectionView = DirectCast(CollectionViewSource.GetDefaultView(CodeStyleItems), ListCollectionView) collectionView.GroupDescriptions.Add(New PropertyGroupDescription(NameOf(AbstractCodeStyleOptionViewModel.GroupName))) Dim qualifyGroupTitle = BasicVSResources.Me_preferences_colon Dim qualifyMemberAccessPreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(BasicVSResources.Prefer_Me, isChecked:=True), New CodeStylePreference(BasicVSResources.Do_not_prefer_Me, isChecked:=False) } Dim predefinedTypesGroupTitle = BasicVSResources.Predefined_type_preferences_colon Dim predefinedTypesPreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked:=True), New CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked:=False) } Dim codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon Dim expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon Dim nothingPreferencesGroupTitle = BasicVSResources.nothing_checking_colon Dim fieldPreferencesGroupTitle = ServicesVSResources.Modifier_preferences_colon Dim parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon Dim newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon ' qualify with Me. group Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, BasicVSResources.Qualify_field_access_with_Me, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, BasicVSResources.Qualify_property_access_with_Me, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, BasicVSResources.Qualify_method_access_with_Me, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, BasicVSResources.Qualify_event_access_with_Me, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) ' predefined or framework type group Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, _intrinsicDeclarationPreviewTrue, _intrinsicDeclarationPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, _intrinsicMemberAccessPreviewTrue, _intrinsicMemberAccessPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) AddParenthesesOptions(optionStore) ' Code block Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, Me, optionStore, codeBlockPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, Me, optionStore, codeBlockPreferencesGroupTitle)) ' expression preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpressions, s_preferSimplifiedConditionalExpressions, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(VisualBasicCodeStyleOptions.PreferIsNotExpression, BasicVSResources.Prefer_IsNot_expression, s_preferIsNotExpression, s_preferIsNotExpression, Me, optionStore, expressionPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, BasicVSResources.Prefer_simplified_object_creation, s_preferSimplifiedObjectCreation, s_preferSimplifiedObjectCreation, Me, optionStore, expressionPreferencesGroupTitle)) AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle) ' nothing preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, Me, optionStore, nothingPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, Me, optionStore, nothingPreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, BasicVSResources.Prefer_Is_Nothing_for_reference_equality_checks, s_preferIsNothingCheckOverReferenceEquals, s_preferIsNothingCheckOverReferenceEquals, Me, optionStore, nothingPreferencesGroupTitle)) ' Field preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, Me, optionStore, fieldPreferencesGroupTitle)) ' Parameter preferences AddParameterOptions(optionStore, parameterPreferencesGroupTitle) ' New line preferences Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, Me, optionStore, newLinePreferencesGroupTitle)) Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_true, Me, optionStore, newLinePreferencesGroupTitle)) End Sub Private Sub AddParenthesesOptions(optionStore As OptionStore) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, BasicVSResources.In_arithmetic_binary_operators, {s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherBinaryParentheses, BasicVSResources.In_other_binary_operators, {s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, BasicVSResources.In_relational_binary_operators, {s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, {s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary}, defaultAddForClarity:=False) End Sub Private Sub AddUnusedValueOptions(optionStore As OptionStore, expressionPreferencesGroupTitle As String) Dim unusedValuePreferences = New List(Of CodeStylePreference) From { New CodeStylePreference(BasicVSResources.Unused_local, isChecked:=True) } Dim enumValues = { UnusedValuePreference.UnusedLocalVariable } Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)( VisualBasicCodeStyleOptions.UnusedValueAssignment, ServicesVSResources.Avoid_unused_value_assignments, enumValues, {s_avoidUnusedValueAssignmentUnusedLocal}, Me, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)) Me.CodeStyleItems.Add(New EnumCodeStyleOptionViewModel(Of UnusedValuePreference)( VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value, enumValues, {s_avoidUnusedValueExpressionStatementUnusedLocal}, Me, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)) End Sub Private Sub AddParameterOptions(optionStore As OptionStore, parameterPreferencesGroupTitle As String) Dim examples = { s_avoidUnusedParametersNonPublicMethods, s_avoidUnusedParametersAllMethods } AddUnusedParameterOption(LanguageNames.VisualBasic, optionStore, parameterPreferencesGroupTitle, examples) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/TypeTests.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TypeTests Inherits BasicTestBase <Fact> Public Sub AlphaRenaming() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Class A(Of T) Public Class B(Of U) Public X As A(Of A(Of U)) End Class End Class Public Class A1 Inherits A(Of Integer) End Class Public Class A2 Inherits A(Of Integer) End Class </file> </compilation>) Dim aint1 = compilation.GlobalNamespace.GetTypeMembers("A1")(0).BaseType ' A<int> Dim aint2 = compilation.GlobalNamespace.GetTypeMembers("A2")(0).BaseType ' A<int> Dim b1 = aint1.GetTypeMembers("B", 1).Single() ' A<int>.B<U> Dim b2 = aint2.GetTypeMembers("B", 1).Single() ' A<int>.B<U> Assert.NotSame(b1.TypeParameters(0), b2.TypeParameters(0)) ' they've been alpha renamed independently Assert.Equal(b1.TypeParameters(0), b2.TypeParameters(0)) ' but happen to be the same type Dim xtype1 = DirectCast(b1.GetMembers("X")(0), FieldSymbol).Type ' Types using them are the same too Dim xtype2 = DirectCast(b2.GetMembers("X")(0), FieldSymbol).Type Assert.Equal(xtype1, xtype2) End Sub <Fact> Public Sub SourceTypeSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Friend Interface A End Interface Namespace n Partial Public MustInherit Class B End Class Structure I End Structure End Namespace </file> <file name="b.vb"> Namespace N Partial Public Class b End Class Friend Enum E A End Enum Friend Delegate Function B(Of T)() As String Module M End Module End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(2, globalNS.GetMembers().Length()) Dim membersNamedA = globalNS.GetMembers("a") Assert.Equal(1, membersNamedA.Length) Dim membersNamedN = globalNS.GetMembers("n") Assert.Equal(1, membersNamedN.Length) Dim ifaceA = DirectCast(membersNamedA(0), NamedTypeSymbol) Assert.Equal(globalNS, ifaceA.ContainingSymbol) Assert.Equal("A", ifaceA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, ifaceA.Kind) Assert.Equal(TypeKind.Interface, ifaceA.TypeKind) Assert.Equal(Accessibility.Friend, ifaceA.DeclaredAccessibility) Assert.False(ifaceA.IsNotInheritable) Assert.True(ifaceA.IsMustInherit) Assert.True(ifaceA.IsReferenceType) Assert.False(ifaceA.IsValueType) Assert.Equal(0, ifaceA.Arity) Assert.Null(ifaceA.BaseType) Dim nsN = DirectCast(membersNamedN(0), NamespaceSymbol) Dim membersOfN = nsN.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(5, membersOfN.Length) Dim classB = DirectCast(membersOfN(0), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("B", 0).First(), classB) Assert.Equal(nsN, classB.ContainingSymbol) Assert.Equal("B", classB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, classB.Kind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Equal(Accessibility.Public, classB.DeclaredAccessibility) Assert.False(classB.IsNotInheritable) Assert.True(classB.IsMustInherit) Assert.True(classB.IsReferenceType) Assert.False(classB.IsValueType) Assert.Equal(0, classB.Arity) Assert.Equal(0, classB.TypeParameters.Length) Assert.Equal(2, classB.Locations.Length()) Assert.Equal(1, classB.InstanceConstructors.Length()) Assert.Equal("System.Object", classB.BaseType.ToTestDisplayString()) Dim delegateB = DirectCast(membersOfN(1), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("B", 1).First(), delegateB) Assert.Equal(nsN, delegateB.ContainingSymbol) Assert.Equal("B", delegateB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, delegateB.Kind) Assert.Equal(TypeKind.Delegate, delegateB.TypeKind) Assert.Equal(Accessibility.Friend, delegateB.DeclaredAccessibility) Assert.True(delegateB.IsNotInheritable) Assert.False(delegateB.IsMustInherit) Assert.True(delegateB.IsReferenceType) Assert.False(delegateB.IsValueType) Assert.Equal(1, delegateB.Arity) Assert.Equal(1, delegateB.TypeParameters.Length) Assert.Equal(0, delegateB.TypeParameters(0).Ordinal) Assert.Same(delegateB, delegateB.TypeParameters(0).ContainingSymbol) Assert.Equal(1, delegateB.Locations.Length()) Assert.Equal("System.MulticastDelegate", delegateB.BaseType.ToTestDisplayString()) #If Not DISABLE_GOOD_HASH_TESTS Then Assert.NotEqual(IdentifierComparison.GetHashCode("A"), IdentifierComparison.GetHashCode("B")) #End If Dim enumE = DirectCast(membersOfN(2), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("E", 0).First(), enumE) Assert.Equal(nsN, enumE.ContainingSymbol) Assert.Equal("E", enumE.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, enumE.Kind) Assert.Equal(TypeKind.Enum, enumE.TypeKind) Assert.Equal(Accessibility.Friend, enumE.DeclaredAccessibility) Assert.True(enumE.IsNotInheritable) Assert.False(enumE.IsMustInherit) Assert.False(enumE.IsReferenceType) Assert.True(enumE.IsValueType) Assert.Equal(0, enumE.Arity) Assert.Equal(1, enumE.Locations.Length()) Assert.Equal("System.Enum", enumE.BaseType.ToTestDisplayString()) Dim structI = DirectCast(membersOfN(3), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("i", 0).First(), structI) Assert.Equal(nsN, structI.ContainingSymbol) Assert.Equal("I", structI.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, structI.Kind) Assert.Equal(TypeKind.Structure, structI.TypeKind) Assert.Equal(Accessibility.Friend, structI.DeclaredAccessibility) Assert.True(structI.IsNotInheritable) Assert.False(structI.IsMustInherit) Assert.False(structI.IsReferenceType) Assert.True(structI.IsValueType) Assert.Equal(0, structI.Arity) Assert.Equal(1, structI.Locations.Length()) Assert.Equal("System.ValueType", structI.BaseType.ToTestDisplayString()) Dim moduleM = DirectCast(membersOfN(4), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("m", 0).First(), moduleM) Assert.Equal(nsN, moduleM.ContainingSymbol) Assert.Equal("M", moduleM.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, moduleM.Kind) Assert.Equal(TypeKind.Module, moduleM.TypeKind) Assert.Equal(Accessibility.Friend, moduleM.DeclaredAccessibility) Assert.True(moduleM.IsNotInheritable) Assert.False(moduleM.IsMustInherit) Assert.True(moduleM.IsReferenceType) Assert.False(moduleM.IsValueType) Assert.Equal(0, moduleM.Arity) Assert.Equal(1, moduleM.Locations.Length()) Assert.Equal("System.Object", moduleM.BaseType.ToTestDisplayString()) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'n' does not match casing of namespace name 'N' in 'b.vb'. Namespace n ~ </expected>) End Sub <Fact> Public Sub NestedSourceTypeSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Partial Class Outer(Of K) Private Partial Class I1 Protected Partial Structure I2(Of T, U) End Structure End Class Private Partial Class I1 Protected Partial Structure I2(Of W) End Structure End Class Enum I4 X End Enum End Class Public Partial Class Outer(Of K) Protected Friend Interface I3 End Interface End Class </file> <file name="b.vb"> Public Class outer(Of K) Private Partial Class i1 Protected Partial Structure i2(Of T, U) End Structure End Class End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim outerClass = DirectCast(globalNSmembers(0), NamedTypeSymbol) Assert.Equal(globalNS, outerClass.ContainingSymbol) Assert.Equal("Outer", outerClass.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, outerClass.Kind) Assert.Equal(TypeKind.Class, outerClass.TypeKind) Assert.Equal(Accessibility.Public, outerClass.DeclaredAccessibility) Assert.Equal(1, outerClass.Arity) Assert.Equal(1, outerClass.TypeParameters.Length) Dim outerTypeParam = outerClass.TypeParameters(0) Assert.Equal(0, outerTypeParam.Ordinal) Assert.Same(outerClass, outerTypeParam.ContainingSymbol) Dim membersOfOuter = outerClass.GetTypeMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(3, membersOfOuter.Length) Dim i1Class = membersOfOuter(0) Assert.Equal(1, outerClass.GetTypeMembers("i1").Length()) Assert.Same(i1Class, outerClass.GetTypeMembers("i1").First()) Assert.Equal("I1", i1Class.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i1Class.Kind) Assert.Equal(TypeKind.Class, i1Class.TypeKind) Assert.Equal(Accessibility.Private, i1Class.DeclaredAccessibility) Assert.Equal(0, i1Class.Arity) Assert.Equal(3, i1Class.Locations.Length()) Dim i3Interface = membersOfOuter(1) Assert.Equal(1, outerClass.GetTypeMembers("i3").Length()) Assert.Same(i3Interface, outerClass.GetTypeMembers("i3").First()) Assert.Equal("I3", i3Interface.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i3Interface.Kind) Assert.Equal(TypeKind.Interface, i3Interface.TypeKind) Assert.Equal(Accessibility.ProtectedOrFriend, i3Interface.DeclaredAccessibility) Assert.Equal(0, i3Interface.Arity) Assert.Equal(1, i3Interface.Locations.Length()) Dim i4Enum = membersOfOuter(2) Assert.Equal(1, outerClass.GetTypeMembers("i4").Length()) Assert.Same(i4Enum, outerClass.GetTypeMembers("i4").First()) Assert.Equal("I4", i4Enum.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i4Enum.Kind) Assert.Equal(TypeKind.Enum, i4Enum.TypeKind) Assert.Equal(Accessibility.Public, i4Enum.DeclaredAccessibility) Assert.Equal(0, i4Enum.Arity) Assert.Equal(1, i4Enum.Locations.Length()) Dim membersOfI1 = i1Class.GetTypeMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(2, membersOfI1.Length) Assert.Equal(2, i1Class.GetTypeMembers("I2").Length()) Dim i2Arity1 = membersOfI1(0) Assert.Equal(1, i1Class.GetTypeMembers("i2", 1).Length()) Assert.Same(i2Arity1, i1Class.GetTypeMembers("i2", 1).First()) Assert.Equal("I2", i2Arity1.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i2Arity1.Kind) Assert.Equal(TypeKind.Structure, i2Arity1.TypeKind) Assert.Equal(Accessibility.Protected, i2Arity1.DeclaredAccessibility) Assert.Equal(1, i2Arity1.Arity) Assert.Equal(1, i2Arity1.TypeParameters.Length) Dim i2Arity1TypeParam = i2Arity1.TypeParameters(0) Assert.Equal(0, i2Arity1TypeParam.Ordinal) Assert.Same(i2Arity1, i2Arity1TypeParam.ContainingSymbol) Assert.Equal(1, i2Arity1.Locations.Length()) Dim i2Arity2 = membersOfI1(1) Assert.Equal(1, i1Class.GetTypeMembers("i2", 2).Length()) Assert.Same(i2Arity2, i1Class.GetTypeMembers("i2", 2).First()) Assert.Equal("I2", i2Arity2.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i2Arity2.Kind) Assert.Equal(TypeKind.Structure, i2Arity2.TypeKind) Assert.Equal(Accessibility.Protected, i2Arity2.DeclaredAccessibility) Assert.Equal(2, i2Arity2.Arity) Assert.Equal(2, i2Arity2.TypeParameters.Length) Dim i2Arity2TypeParam0 = i2Arity2.TypeParameters(0) Assert.Equal(0, i2Arity2TypeParam0.Ordinal) Assert.Same(i2Arity2, i2Arity2TypeParam0.ContainingSymbol) Dim i2Arity2TypeParam1 = i2Arity2.TypeParameters(1) Assert.Equal(1, i2Arity2TypeParam1.Ordinal) Assert.Same(i2Arity2, i2Arity2TypeParam1.ContainingSymbol) Assert.Equal(2, i2Arity2.Locations.Length()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(2200, "DevDiv_Projects/Roslyn")> <Fact> Public Sub ArrayTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public Shared AryField()(,) as Object Friend fAry01(9) as String Dim fAry02(9) as String Function M(ByVal ary1() As Byte, ByRef ary2()() as Single, ParamArray ary3(,) As Long) As String() Return Nothing End Function End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim members = classTest.GetMembers() Dim field1 = DirectCast(members(1), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) Dim sym1 = field1.Type ' Object Assert.Equal(SymbolKind.ArrayType, sym1.Kind) Assert.Equal(Accessibility.NotApplicable, sym1.DeclaredAccessibility) Assert.False(sym1.IsShared) Assert.Null(sym1.ContainingAssembly) ' bug 2200 field1 = DirectCast(members(2), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) field1 = DirectCast(members(3), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) Dim mem1 = DirectCast(members(4), MethodSymbol) Assert.Equal(3, mem1.Parameters.Length()) Dim sym2 = mem1.Parameters(0) Assert.Equal("ary1", sym2.Name) Assert.Equal(SymbolKind.ArrayType, sym2.Type.Kind) Assert.Equal("Array", sym2.Type.BaseType.Name) Dim sym3 = mem1.Parameters(1) Assert.Equal("ary2", sym3.Name) Assert.True(sym3.IsByRef) Assert.Equal(SymbolKind.ArrayType, sym3.Type.Kind) Dim sym4 = mem1.Parameters(2) Assert.Equal("ary3", sym4.Name) Assert.Equal(SymbolKind.ArrayType, sym4.Type.Kind) Assert.Equal(0, sym4.Type.GetTypeMembers().Length()) Assert.Equal(0, sym4.Type.GetTypeMembers(String.Empty).Length()) Assert.Equal(0, sym4.Type.GetTypeMembers(String.Empty, 0).Length()) Dim sym5 = mem1.ReturnType Assert.Equal(SymbolKind.ArrayType, sym5.Kind) Assert.Equal(0, sym5.GetAttributes().Length()) End Sub <WorkItem(537281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537281")> <WorkItem(537300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537300")> <WorkItem(932303, "DevDiv/Personal")> <Fact> Public Sub ArrayTypeInterfaces() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public AryField() As Object Shared AryField2()() As Integer Private AryField3(,,) As Byte Public Sub New() End Sub End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim sym1 = DirectCast(classTest.GetMembers().First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym1.Kind) ' IList(Of T) Assert.Equal(1, sym1.Interfaces.Length) Dim itype1 = sym1.Interfaces(0) Assert.Equal("System.Collections.Generic.IList(Of System.Object)", itype1.ToTestDisplayString()) ' Jagged array's rank is 1 Dim sym2 = DirectCast(classTest.GetMembers("AryField2").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym2.Kind) Assert.Equal(1, sym2.Interfaces.Length) Dim itype2 = sym2.Interfaces(0) Assert.Equal("System.Collections.Generic.IList(Of System.Int32())", itype2.ToTestDisplayString()) Dim sym3 = DirectCast(classTest.GetMembers("AryField3").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym3.Kind) Assert.Equal(0, sym3.Interfaces.Length) Assert.Throws(Of ArgumentNullException)(Sub() compilation.CreateArrayTypeSymbol(Nothing)) End Sub <WorkItem(537420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537420")> <WorkItem(537515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537515")> <Fact> Public Sub ArrayTypeGetFullNameAndHashCode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public Shared AryField1() As Integer Private AryField2(,,) As String Protected AryField3()(,) As Byte Shared AryField4 As ULong(,)() Friend AryField5(9) As Long Dim AryField6(2,4) As Object Public Abc(), Bbc(,,,), Cbc()() Public Sub New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim mems = classTest.GetMembers() Dim sym1 = DirectCast(classTest.GetMembers().First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym1.Kind) Assert.Equal("System.Int32()", sym1.ToTestDisplayString()) Dim v1 = sym1.GetHashCode() Dim v2 = sym1.GetHashCode() Assert.Equal(v1, v2) Dim sym21 = DirectCast(classTest.GetMembers("AryField2").First(), FieldSymbol) Assert.Equal(1, sym21.Locations.Length) Dim span = DirectCast(sym21.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(16, span.StartLinePosition.Character) Assert.Equal(25, span.EndLinePosition.Character) Assert.Equal("AryField2", sym21.Name) Assert.Equal("A.AryField2 As System.String(,,)", sym21.ToTestDisplayString()) Dim sym22 = sym21.Type Assert.Equal(SymbolKind.ArrayType, sym22.Kind) Assert.Equal("System.String(,,)", sym22.ToTestDisplayString()) v1 = sym22.GetHashCode() v2 = sym22.GetHashCode() Assert.Equal(v1, v2) Dim sym3 = DirectCast(classTest.GetMembers("AryField3").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym3.Kind) Assert.Equal("System.Byte()(,)", sym3.ToTestDisplayString()) v1 = sym3.GetHashCode() v2 = sym3.GetHashCode() Assert.Equal(v1, v2) Dim sym4 = DirectCast(mems(3), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym4.Kind) Assert.Equal("System.UInt64(,)()", sym4.ToTestDisplayString()) v1 = sym4.GetHashCode() v2 = sym4.GetHashCode() Assert.Equal(v1, v2) Dim sym5 = DirectCast(mems(4), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym5.Kind) Assert.Equal("System.Int64()", sym5.ToTestDisplayString()) v1 = sym5.GetHashCode() v2 = sym5.GetHashCode() Assert.Equal(v1, v2) Dim sym61 = DirectCast(mems(5), FieldSymbol) span = DirectCast(sym61.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(12, span.StartLinePosition.Character) Assert.Equal(21, span.EndLinePosition.Character) Dim sym62 = sym61.Type Assert.Equal(SymbolKind.ArrayType, sym62.Kind) Assert.Equal("System.Object(,)", sym62.ToTestDisplayString()) v1 = sym62.GetHashCode() v2 = sym62.GetHashCode() Assert.Equal(v1, v2) Dim sym71 = DirectCast(classTest.GetMembers("Abc").First(), FieldSymbol) Assert.Equal("system.object()", sym71.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym71.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(15, span.StartLinePosition.Character) Assert.Equal(18, span.EndLinePosition.Character) Dim sym72 = DirectCast(classTest.GetMembers("bBc").First(), FieldSymbol) Assert.Equal("system.object(,,,)", sym72.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym72.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(22, span.StartLinePosition.Character) Assert.Equal(25, span.EndLinePosition.Character) Dim sym73 = DirectCast(classTest.GetMembers("cbC").First(), FieldSymbol) Assert.Equal("system.object()()", sym73.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym73.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(32, span.StartLinePosition.Character) Assert.Equal(35, span.EndLinePosition.Character) Assert.Equal("A.Cbc As System.Object()()", sym73.ToTestDisplayString()) End Sub <Fact(), WorkItem(537187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537187"), WorkItem(529941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529941")> Public Sub EnumFields() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="EnumFields"> <file name="a.vb"> Public Enum E One Two = 2 Three End Enum </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(1, globalNS.GetMembers().Length()) Dim enumE = globalNS.GetTypeMembers("E", 0).First() Assert.Equal("E", enumE.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, enumE.Kind) Assert.Equal(TypeKind.Enum, enumE.TypeKind) Assert.Equal(Accessibility.Public, enumE.DeclaredAccessibility) Assert.True(enumE.IsNotInheritable) Assert.False(enumE.IsMustInherit) Assert.False(enumE.IsReferenceType) Assert.True(enumE.IsValueType) Assert.Equal(0, enumE.Arity) Assert.Equal("System.Enum", enumE.BaseType.ToTestDisplayString()) Dim enumMembers = enumE.GetMembers() Assert.Equal(5, enumMembers.Length) Dim ctor = enumMembers.Where(Function(s) s.Kind = SymbolKind.Method) Assert.Equal(1, ctor.Count) Assert.Equal(SymbolKind.Method, ctor(0).Kind) Dim _val = enumMembers.Where(Function(s) Not s.IsShared AndAlso s.Kind = SymbolKind.Field) Assert.Equal(1, _val.Count) Dim emem = enumMembers.Where(Function(s) s.IsShared) Assert.Equal(3, emem.Count) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> Public Sub SimpleGenericType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Generic"> <file name="g.vb"> Namespace NS Public Interface IGoo(Of T) End Interface Friend Class A(Of V) End Class Public Structure S(Of X, Y) End Structure End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim namespaceNS = globalNS.GetMembers("NS") Dim nsNS = DirectCast(namespaceNS(0), NamespaceSymbol) Dim membersOfNS = nsNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(3, membersOfNS.Length) Dim classA = DirectCast(membersOfNS(0), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("A").First(), classA) Assert.Equal(nsNS, classA.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, classA.Kind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(Accessibility.Friend, classA.DeclaredAccessibility) Assert.Equal(1, classA.TypeParameters.Length) Assert.Equal("V", classA.TypeParameters(0).Name) Assert.Equal(1, classA.TypeArguments.Length) Dim igoo = DirectCast(membersOfNS(1), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("IGoo").First(), igoo) Assert.Equal(nsNS, igoo.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, igoo.Kind) Assert.Equal(TypeKind.Interface, igoo.TypeKind) Assert.Equal(Accessibility.Public, igoo.DeclaredAccessibility) Assert.Equal(1, igoo.TypeParameters.Length) Assert.Equal("T", igoo.TypeParameters(0).Name) Assert.Equal(1, igoo.TypeArguments.Length) Dim structS = DirectCast(membersOfNS(2), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("S").First(), structS) Assert.Equal(nsNS, structS.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, structS.Kind) Assert.Equal(TypeKind.Structure, structS.TypeKind) Assert.Equal(Accessibility.Public, structS.DeclaredAccessibility) Assert.Equal(2, structS.TypeParameters.Length) Assert.Equal("X", structS.TypeParameters(0).Name) Assert.Equal("Y", structS.TypeParameters(1).Name) Assert.Equal(2, structS.TypeArguments.Length) End Sub ' Check that type parameters work correctly. <Fact> Public Sub TypeParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Interface Z(Of T, In U, Out V) End Interface </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim interfaceZ = DirectCast(globalNSmembers(0), NamedTypeSymbol) Dim typeParams = interfaceZ.TypeParameters Assert.Equal(3, typeParams.Length) Assert.Equal("T", typeParams(0).Name) Assert.Equal(VarianceKind.None, typeParams(0).Variance) Assert.Equal(0, typeParams(0).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(0).DeclaredAccessibility) Assert.Equal("U", typeParams(1).Name) Assert.Equal(VarianceKind.In, typeParams(1).Variance) Assert.Equal(1, typeParams(1).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(1).DeclaredAccessibility) Assert.Equal("V", typeParams(2).Name) Assert.Equal(VarianceKind.Out, typeParams(2).Variance) Assert.Equal(2, typeParams(2).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(2).DeclaredAccessibility) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(537199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537199")> <Fact> Public Sub UseTypeInNetModule() Dim mscorlibRef = TestMetadata.Net40.mscorlib Dim module1Ref = TestReferences.SymbolsTests.netModule.netModule1 Dim text = <literal> Class Test Dim a As Class1 = Nothing Public Sub New() End Sub End Class </literal>.Value Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.From(text), VisualBasicParseOptions.Default, "") Dim comp As VisualBasicCompilation = VisualBasicCompilation.Create("Test", {tree}, {mscorlibRef, module1Ref}) Dim globalNS = comp.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("Test").First(), NamedTypeSymbol) Dim members = classTest.GetMembers() ' has to have mscorlib Dim varA = DirectCast(members(0), FieldSymbol) Assert.Equal(SymbolKind.Field, varA.Kind) Assert.Equal(TypeKind.Class, varA.Type.TypeKind) Assert.Equal(SymbolKind.NamedType, varA.Type.Kind) End Sub ' Date: IEEE 64bits (8 bytes) values <Fact> Public Sub PredefinedType01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Generic"> <file name="pd.vb"> Namespace NS Friend Module MyMod Dim dateField As Date = #8/13/2002 12:14 PM# Function DateFunc() As Date() Dim Obj As Object = #10/10/2001# Return Obj End Function Sub DateSub(ByVal Ary(,,) As Date) #If compErrorTest Then 'COMPILEERROR: BC30414, "New Date() {}" Ary = New Date() {} #End If End Sub Shared Sub New() End Sub End Module End Namespace </file> </compilation>) Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol) Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol) Dim members = modOfNS.GetMembers() Assert.Equal(4, members.Length) ' 3 members + implicit shared constructor Dim mem1 = DirectCast(members(0), FieldSymbol) Assert.Equal(modOfNS, mem1.ContainingSymbol) Assert.Equal(Accessibility.Private, mem1.DeclaredAccessibility) Assert.Equal(SymbolKind.Field, mem1.Kind) Assert.Equal(TypeKind.Structure, mem1.Type.TypeKind) Assert.Equal("Date", mem1.Type.ToDisplayString()) Assert.Equal("System.DateTime", mem1.Type.ToTestDisplayString()) Dim mem2 = DirectCast(members(1), MethodSymbol) Assert.Equal(modOfNS, mem2.ContainingSymbol) Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility) Assert.Equal(SymbolKind.Method, mem2.Kind) Assert.Equal(TypeKind.Array, mem2.ReturnType.TypeKind) Dim ary = DirectCast(mem2.ReturnType, ArrayTypeSymbol) Assert.Equal(1, ary.Rank) Assert.Equal("Date", ary.ElementType.ToDisplayString()) Assert.Equal("System.DateTime", ary.ElementType.ToTestDisplayString()) Dim mem3 = DirectCast(modOfNS.GetMembers("DateSub").Single(), MethodSymbol) Assert.Equal(modOfNS, mem3.ContainingSymbol) Assert.Equal(Accessibility.Public, mem3.DeclaredAccessibility) Assert.Equal(SymbolKind.Method, mem3.Kind) Assert.True(mem3.IsSub) Dim param = DirectCast(mem3.Parameters(0), ParameterSymbol) Assert.Equal(TypeKind.Array, param.Type.TypeKind) ary = DirectCast(param.Type, ArrayTypeSymbol) Assert.Equal(3, ary.Rank) Assert.Equal("Date", ary.ElementType.ToDisplayString()) Assert.Equal("System.DateTime", ary.ElementType.ToTestDisplayString()) End Sub <WorkItem(537461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537461")> <Fact> Public Sub SourceTypeUndefinedBaseType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="SourceTypeUndefinedBaseType"> <file name="undefinedbasetype.vb"> Class Class1 : Inherits Goo End Class </file> </compilation>) Dim baseType = compilation.GlobalNamespace.GetTypeMembers("Class1").Single().BaseType Assert.Equal("Goo", baseType.ToTestDisplayString()) Assert.Equal(SymbolKind.ErrorType, baseType.Kind) End Sub <WorkItem(537467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537467")> <Fact> Public Sub TopLevelPrivateTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Option Strict Off Option Explicit Off Imports VB6 = Microsoft.VisualBasic Namespace InterfaceErr005 'COMPILEERROR: BC31089, "PrivateUDT" Private Structure PrivateUDT Public x As Short End Structure 'COMPILEERROR: BC31089, "PrivateIntf" Private Interface PrivateIntf Function goo() End Interface 'COMPILEERROR: BC31047 Protected Class ProtectedClass End Class End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("InterfaceErr005").First(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("PrivateUDT").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' type1 = DirectCast(ns.GetTypeMembers("PrivateIntf").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' type1 = DirectCast(ns.GetTypeMembers("ProtectedClass").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31089: Types declared 'Private' must be inside another type. Private Structure PrivateUDT ~~~~~~~~~~ BC31089: Types declared 'Private' must be inside another type. Private Interface PrivateIntf ~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Class ProtectedClass ~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527185")> <Fact> Public Sub InheritTypeFromMetadata01() Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="b.vb"> Public Module m1 Public Class C1_1 Public Class goo End Class End Class End Module </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="Test1"> <file name="a.vb"> Imports System Imports System.Collections.Generic Namespace ShadowsGen203 ' from mscorlib Public Class MyAttribute Inherits Attribute End Class ' from another module Public Module M1 Public Class C1_3 Inherits C1_1 Private Shadows Class goo End Class End Class End Module End Namespace </file> </compilation>, {compRef1}) ' VisualBasicCompilation.Create("Test", CompilationOptions.Default, {SyntaxTree.ParseCompilationUnit(text1)}, {compRef1}) Dim ns = DirectCast(comp.GlobalNamespace.GetMembers("ShadowsGen203").Single(), NamespaceSymbol) Dim mod1 = DirectCast(ns.GetMembers("m1").Single(), NamedTypeSymbol) Dim type1 = DirectCast(mod1.GetTypeMembers("C1_3").Single(), NamedTypeSymbol) Assert.Equal("C1_1", type1.BaseType.Name) Dim type2 = DirectCast(ns.GetTypeMembers("MyAttribute").Single(), NamedTypeSymbol) Assert.Equal("Attribute", type2.BaseType.Name) End Sub <WorkItem(537753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537753")> <Fact> Public Sub ImplementTypeCrossComps() Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="comp.vb"> Imports System.Collections.Generic Namespace MT Public Interface IGoo(Of T) Sub M(ByVal t As T) End Interface End Namespace </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="Test2"> <file name="comp2.vb"> Imports System.Collections.Generic Imports MT Namespace SS Public Class Goo Implements IGoo(Of String) Sub N(ByVal s As String) Implements IGoo(Of String).M End Sub End Class End Namespace </file> </compilation>, {compRef1}) Dim ns = DirectCast(comp.SourceModule.GlobalNamespace.GetMembers("SS").Single(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("Goo", 0).Single(), NamedTypeSymbol) ' Not impl ex Assert.Equal(1, type1.Interfaces.Length) Dim type2 = DirectCast(type1.Interfaces(0), NamedTypeSymbol) Assert.Equal(TypeKind.Interface, type2.TypeKind) Assert.Equal(1, type2.Arity) Assert.Equal(1, type2.TypeParameters.Length) Assert.Equal("MT.IGoo(Of System.String)", type2.ToTestDisplayString()) End Sub <WorkItem(537492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537492")> <Fact> Public Sub PartialClassImplInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Option Strict Off Option Explicit On Imports System.Collections.Generic Public Interface vbInt2(Of T) Sub Sub1(ByVal b1 As Byte, ByRef t2 As T) Function Fun1(Of Z)(ByVal p1 As T) As Z End Interface </file> <file name="b.vb"> Module Module1 Public Class vbPartialCls200a(Of P, Q) ' for test GenPartialCls200 Implements vbInt2(Of P) Public Function Fun1(Of X)(ByVal a As P) As X Implements vbInt2(Of P).Fun1 Return Nothing End Function End Class Partial Public Class vbPartialCls200a(Of P, Q) Implements vbInt2(Of P) Public Sub Sub1(ByVal p1 As Byte, ByRef p2 As P) Implements vbInt2(Of P).Sub1 End Sub End Class Sub Main() End Sub End Module </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim myMod = DirectCast(globalNS.GetMembers("Module1").First(), NamedTypeSymbol) Dim type1 = DirectCast(myMod.GetTypeMembers("vbPartialCls200a").Single(), NamedTypeSymbol) Assert.Equal(1, type1.Interfaces.Length) End Sub <Fact> Public Sub CyclesInStructureDeclarations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Module Module1 Structure stdUDT End Structure Structure nestedUDT Public xstdUDT As stdUDT Public xstdUDTarr() As stdUDT End Structure Public m_nx1var As nestedUDT Public m_nx2var As nestedUDT Sub Scen1() Dim x2var As stdUDT End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC42024: Unused local variable: 'x2var'. Dim x2var As stdUDT ~~~~~ </errors>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Module Module1 Structure OuterStruct Structure InnerStruct Public t As OuterStruct End Structure Public one As InnerStruct Public two As InnerStruct Sub Scen1() Dim three As OuterStruct End Sub End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'OuterStruct' cannot contain an instance of itself: 'Module1.OuterStruct' contains 'Module1.OuterStruct.InnerStruct' (variable 'one'). 'Module1.OuterStruct.InnerStruct' contains 'Module1.OuterStruct' (variable 't'). Public one As InnerStruct ~~~ BC42024: Unused local variable: 'three'. Dim three As OuterStruct ~~~~~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations2"> <file name="a.vb"> Structure st1(Of T) Dim x As T End Structure Structure st2 Dim x As st1(Of st2) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of st2)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations2_() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations2_"> <file name="a.vb"> Structure st2 Dim x As st1(Of st2) End Structure Structure st1(Of T) Dim x As T End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of st2)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations3"> <file name="a.vb"> Structure st1(Of T) Dim x As st2 End Structure Structure st2 Dim x As st1(Of st2) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st1' cannot contain an instance of itself: 'st1(Of T)' contains 'st2' (variable 'x'). 'st2' contains 'st1(Of st2)' (variable 'x'). Dim x As st2 ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations3_() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations3_"> <file name="a.vb"> Structure st2 Dim x As st1(Of st2) End Structure Structure st1(Of T) Dim x As st2 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of T)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations4"> <file name="a.vb"> Structure E End Structure Structure X(Of T) Public _t As T End Structure Structure Y Public xz As X(Of Z) End Structure Structure Z Public xe As X(Of E) Public xy As X(Of Y) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'Y' cannot contain an instance of itself: 'Y' contains 'X(Of Z)' (variable 'xz'). 'X(Of Z)' contains 'Z' (variable '_t'). 'Z' contains 'X(Of Y)' (variable 'xy'). 'X(Of Y)' contains 'Y' (variable '_t'). Public xz As X(Of Z) ~~ </errors>) End Sub <Fact> Public Sub PortedFromCSharp_StructLayoutCycle01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Module Module1 Structure A Public F As A ' BC30294 Public F_ As A ' no additional error End Structure Structure B Public F As C ' BC30294 Public G As C ' no additional error, cycle is reported for B.F End Structure Structure C Public G As B ' no additional error, cycle is reported for B.F End Structure Structure D(Of T) Public F As D(Of D(Of Object)) ' BC30294 End Structure Structure E Public F As F(Of E) ' no error End Structure Class F(Of T) Public G As E ' no error End Class Structure G Public F As H(Of G) ' BC30294 End Structure Structure H(Of T) Public G As G ' no additional error, cycle is reported for B.F End Structure Structure J Public Shared j As J ' no error End Structure Structure K Public Shared l As L ' no error End Structure Structure L Public l As K ' no error End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'A' cannot contain an instance of itself: 'Module1.A' contains 'Module1.A' (variable 'F'). Public F As A ' BC30294 ~ BC30294: Structure 'B' cannot contain an instance of itself: 'Module1.B' contains 'Module1.C' (variable 'F'). 'Module1.C' contains 'Module1.B' (variable 'G'). Public F As C ' BC30294 ~ BC30294: Structure 'D' cannot contain an instance of itself: 'Module1.D(Of T)' contains 'Module1.D(Of Module1.D(Of Object))' (variable 'F'). Public F As D(Of D(Of Object)) ' BC30294 ~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.H(Of Module1.G)' (variable 'F'). 'Module1.H(Of T)' contains 'Module1.G' (variable 'G'). Public F As H(Of G) ' BC30294 ~ </errors>) End Sub <Fact> Public Sub PortedFromCSharp_StructLayoutCycle02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Module Module1 Structure A Public Property P1 As A ' BC30294 Public Property P2 As A ' no additional error End Structure Structure B Public Property C1 As C ' BC30294 Public Property C2 As C ' no additional error End Structure Structure C Public Property B1 As B ' no error, cycle is already reported Public Property B2 As B ' no additional error End Structure Structure D(Of T) Public Property P1 As D(Of D(Of Object)) ' BC30294 Public Property P2 As D(Of D(Of Object)) ' no additional error End Structure Structure E Public Property F1 As F(Of E) ' no error Public Property F2 As F(Of E) ' no error End Structure Class F(Of T) Public Property P1 As E ' no error Public Property P2 As E ' no error End Class Structure G Public Property H1 As H(Of G) ' BC30294 Public Property H2 As H(Of G) ' no additional error Public Property G1 As G ' BC30294 End Structure Structure H(Of T) Public Property G1 As G ' no error Public Property G2 As G ' no error End Structure Structure J Public Shared Property j As J ' no error End Structure Structure K Public Shared Property l As L ' no error End Structure Structure L Public Property l As K ' no error End Structure Structure M Public Property N1 As N ' no error Public Property N2 As N ' no error End Structure Structure N Public Property M1 As M ' no error Get Return Nothing End Get Set(value As M) End Set End Property Public Property M2 As M ' no error Get Return Nothing End Get Set(value As M) End Set End Property End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'A' cannot contain an instance of itself: 'Module1.A' contains 'Module1.A' (variable '_P1'). Public Property P1 As A ' BC30294 ~~ BC30294: Structure 'B' cannot contain an instance of itself: 'Module1.B' contains 'Module1.C' (variable '_C1'). 'Module1.C' contains 'Module1.B' (variable '_B1'). Public Property C1 As C ' BC30294 ~~ BC30294: Structure 'D' cannot contain an instance of itself: 'Module1.D(Of T)' contains 'Module1.D(Of Module1.D(Of Object))' (variable '_P1'). Public Property P1 As D(Of D(Of Object)) ' BC30294 ~~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.H(Of Module1.G)' (variable '_H1'). 'Module1.H(Of T)' contains 'Module1.G' (variable '_G1'). Public Property H1 As H(Of G) ' BC30294 ~~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.G' (variable '_G1'). Public Property G1 As G ' BC30294 ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' ERROR Dim s2_ As S2 ' NO ERROR Dim s3 As S3 ' ERROR End Structure Structure S2 Dim s1 As S1 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' ERROR ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s3 As S3 ' ERROR ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' ERROR Dim s2_ As S2 ' NO ERROR Dim s3 As S3 ' NO ERROR End Structure Structure S2 Dim s1 As S1 End Structure Structure S3 Dim s2 As S2 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' ERROR ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' two errors Dim s2_ As S2 ' no errors End Structure Structure S2 Dim s1 As S1 Dim s3 As S3 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' two errors Dim s2_ As S2 ' no errors End Structure Structure S2 Dim s3 As S3 Dim s1 As S1 Dim s1_ As S1 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure05() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MultiplyCyclesInStructure05_I"> <file name="a.vb"> Public Structure SI_1 End Structure Public Structure SI_2 Public s1 As SI_1 End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation1) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="MultiplyCyclesInStructure05_II"> <file name="a.vb"> Public Structure SII_3 Public s2 As SI_2 End Structure Public Structure SII_4 Public s3 As SII_3 End Structure </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="MultiplyCyclesInStructure05_I"> <file name="a.vb"> Public Structure SI_1 Public s4 As SII_4 End Structure Public Structure SI_2 Public s1 As SI_1 End Structure </file> </compilation>, {New VisualBasicCompilationReference(compilation2)}) CompilationUtils.AssertTheseDiagnostics(compilation3, <errors> BC30294: Structure 'SI_1' cannot contain an instance of itself: 'SI_1' contains 'SII_4' (variable 's4'). 'SII_4' contains 'SII_3' (variable 's3'). 'SII_3' contains 'SI_2' (variable 's2'). 'SI_2' contains 'SI_1' (variable 's1'). Public s4 As SII_4 ~~ </errors>) End Sub <Fact> Public Sub SynthesizedConstructorLocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Goo End Class </file> </compilation>) Dim typeGoo = compilation.SourceModule.GlobalNamespace.GetTypeMembers("Goo").Single() Dim instanceConstructor = typeGoo.InstanceConstructors.Single() AssertEx.Equal(typeGoo.Locations, instanceConstructor.Locations) End Sub <Fact> Public Sub UsingProtectedInStructureMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingProtectedInStructureMethods"> <file name="a.vb"> Structure Goo Protected Overrides Sub Finalize() End Sub Protected Sub OtherMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Sub OtherMethod() ~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UsingMustOverrideInStructureMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UsingProtectedInStructureMethods"> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Structure S2 Public MustOverride Function Goo() As String End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30435: Members in a Structure cannot be declared 'MustOverride'. Public MustOverride Function Goo() As String ~~~~~~~~~~~~ BC30430: 'End Function' must be preceded by a matching 'Function'. End Function ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub Bug4135() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4135"> <file name="a.vb"> Interface I1 Protected Interface I2 End Interface Protected Friend Interface I3 End Interface Protected delegate Sub D1() Protected Friend delegate Sub D2() Protected Class C1 End Class Protected Friend Class C2 End Class Protected Structure S1 End Structure Protected Friend Structure S2 End Structure Protected Enum E1 val End Enum Protected Friend Enum E2 val End Enum 'Protected F1 As Integer 'Protected Friend F2 As Integer Protected Sub Sub1() Protected Friend Sub Sub2() End Interface Structure S3 Protected Interface I4 End Interface Protected Friend Interface I5 End Interface Protected delegate Sub D3() Protected Friend delegate Sub D4() Protected Class C3 End Class Protected Friend Class C4 End Class Protected Structure S4 End Structure Protected Friend Structure S5 End Structure Protected Enum E3 val End Enum Protected Friend Enum E4 val End Enum Protected F3 As Integer Protected Friend F4 As Integer Protected Sub Sub3() End Sub Protected Friend Sub Sub4() End Sub End Structure Module M1 Protected Interface I8 End Interface Protected Friend Interface I9 End Interface Protected delegate Sub D7() Protected Friend delegate Sub D8() Protected Class C7 End Class Protected Friend Class C8 End Class Protected Structure S8 End Structure Protected Friend Structure S9 End Structure Protected Enum E5 val End Enum Protected Friend Enum E6 val End Enum Protected F5 As Integer Protected Friend F6 As Integer Protected Sub Sub7() End Sub Protected Friend Sub Sub8() End Sub End Module Protected Interface I11 End Interface Protected Structure S11 End Structure Protected Class C11 End Class Protected Enum E11 val End Enum Protected Module M11 End Module Protected Friend Interface I12 End Interface Protected Friend Structure S12 End Structure Protected Friend Class C12 End Class Protected Friend Enum E12 val End Enum Protected Friend Module M12 End Module Protected delegate Sub D11() Protected Friend delegate Sub D12() Class C4 Protected Interface I6 End Interface Protected Friend Interface I7 End Interface Protected delegate Sub D5() Protected Friend delegate Sub D6() Protected Class C5 End Class Protected Friend Class C6 End Class Protected Structure S6 End Structure Protected Friend Structure S7 End Structure Protected Enum E7 val End Enum Protected Friend Enum E8 val End Enum Protected F7 As Integer Protected Friend F8 As Integer Protected Sub Sub5() End Sub Protected Friend Sub Sub6() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31209: Interface in an interface cannot be declared 'Protected'. Protected Interface I2 ~~~~~~~~~ BC31209: Interface in an interface cannot be declared 'Protected Friend'. Protected Friend Interface I3 ~~~~~~~~~~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Protected'. Protected delegate Sub D1() ~~~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Protected Friend'. Protected Friend delegate Sub D2() ~~~~~~~~~~~~~~~~ BC31070: Class in an interface cannot be declared 'Protected'. Protected Class C1 ~~~~~~~~~ BC31070: Class in an interface cannot be declared 'Protected Friend'. Protected Friend Class C2 ~~~~~~~~~~~~~~~~ BC31071: Structure in an interface cannot be declared 'Protected'. Protected Structure S1 ~~~~~~~~~ BC31071: Structure in an interface cannot be declared 'Protected Friend'. Protected Friend Structure S2 ~~~~~~~~~~~~~~~~ BC31069: Enum in an interface cannot be declared 'Protected'. Protected Enum E1 ~~~~~~~~~ BC31069: Enum in an interface cannot be declared 'Protected Friend'. Protected Friend Enum E2 ~~~~~~~~~~~~~~~~ BC30270: 'Protected' is not valid on an interface method declaration. Protected Sub Sub1() ~~~~~~~~~ BC30270: 'Protected Friend' is not valid on an interface method declaration. Protected Friend Sub Sub2() ~~~~~~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Interface I4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Interface I5 ~~ BC31047: Protected types can only be declared inside of a class. Protected delegate Sub D3() ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend delegate Sub D4() ~~ BC31047: Protected types can only be declared inside of a class. Protected Class C3 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Class C4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Structure S4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Structure S5 ~~ BC31047: Protected types can only be declared inside of a class. Protected Enum E3 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Enum E4 ~~ BC30435: Members in a Structure cannot be declared 'Protected'. Protected F3 As Integer ~~~~~~~~~ BC30435: Members in a Structure cannot be declared 'Protected Friend'. Protected Friend F4 As Integer ~~~~~~~~~~~~~~~~ BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Sub Sub3() ~~~~~~~~~ BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Friend Sub Sub4() ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Interface I8 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Interface I9 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected delegate Sub D7() ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend delegate Sub D8() ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Class C7 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Class C8 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Structure S8 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Structure S9 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Enum E5 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Enum E6 ~~~~~~~~~~~~~~~~ BC30593: Variables in Modules cannot be declared 'Protected'. Protected F5 As Integer ~~~~~~~~~ BC30593: Variables in Modules cannot be declared 'Protected Friend'. Protected Friend F6 As Integer ~~~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Protected'. Protected Sub Sub7() ~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Protected Friend'. Protected Friend Sub Sub8() ~~~~~~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Interface I11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Structure S11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Class C11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Enum E11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Module M11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Interface I12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Structure S12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Class C12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Enum E12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Module M12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected delegate Sub D11() ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend delegate Sub D12() ~~~ </expected>) End Sub <Fact> Public Sub Bug4136() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Private Interface I2 End Interface Private delegate Sub D1() Private Class C1 End Class Private Structure S1 End Structure Private Enum E1 val End Enum 'Private F1 As Integer Private Sub Sub1() End Interface Private Interface I11 End Interface Private Structure S11 End Structure Private Class C11 End Class Private Enum E11 val End Enum Private Module M11 End Module Private delegate Sub D11() Structure S3 Private Interface I4 End Interface Private delegate Sub D3() Private Class C3 End Class Private Structure S4 End Structure Private Enum E3 val End Enum Private F3 As Integer Private Sub Sub3() End Sub End Structure Module M1 Private Interface I8 End Interface Private delegate Sub D7() Private Class C7 End Class Private Structure S8 End Structure Private Enum E5 val End Enum Private F5 As Integer Private Sub Sub7() End Sub End Module Class C4 Private Interface I6 End Interface Private delegate Sub D5() Private Class C5 End Class Private Structure S6 End Structure Private Enum E7 val End Enum Private F7 As Integer Private Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31209: Interface in an interface cannot be declared 'Private'. Private Interface I2 ~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Private'. Private delegate Sub D1() ~~~~~~~ BC31070: Class in an interface cannot be declared 'Private'. Private Class C1 ~~~~~~~ BC31071: Structure in an interface cannot be declared 'Private'. Private Structure S1 ~~~~~~~ BC31069: Enum in an interface cannot be declared 'Private'. Private Enum E1 ~~~~~~~ BC30270: 'Private' is not valid on an interface method declaration. Private Sub Sub1() ~~~~~~~ BC31089: Types declared 'Private' must be inside another type. Private Interface I11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Structure S11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Class C11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Enum E11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Module M11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private delegate Sub D11() ~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Friend Interface I2 End Interface Friend delegate Sub D1() Friend Class C1 End Class Friend Structure S1 End Structure Friend Enum E1 val End Enum 'Friend F1 As Integer Friend Sub Sub1() End Interface Friend Interface I11 End Interface Friend Structure S11 End Structure Friend Class C11 End Class Friend Enum E11 val End Enum Friend Module M11 End Module Friend delegate Sub D11() Structure S3 Friend Interface I4 End Interface Friend delegate Sub D3() Friend Class C3 End Class Friend Structure S4 End Structure Friend Enum E3 val End Enum Friend F3 As Integer Friend Sub Sub3() End Sub End Structure Module M1 Friend Interface I8 End Interface Friend delegate Sub D7() Friend Class C7 End Class Friend Structure S8 End Structure Friend Enum E5 val End Enum Friend F5 As Integer Friend Sub Sub7() End Sub End Module Class C4 Friend Interface I6 End Interface Friend delegate Sub D5() Friend Class C5 End Class Friend Structure S6 End Structure Friend Enum E7 val End Enum Friend F7 As Integer Friend Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31068: Delegate in an interface cannot be declared 'Friend'. Friend delegate Sub D1() ~~~~~~ BC31070: Class in an interface cannot be declared 'Friend'. Friend Class C1 ~~~~~~ BC31071: Structure in an interface cannot be declared 'Friend'. Friend Structure S1 ~~~~~~ BC31069: Enum in an interface cannot be declared 'Friend'. Friend Enum E1 ~~~~~~ BC30270: 'Friend' is not valid on an interface method declaration. Friend Sub Sub1() ~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Public Interface I2 End Interface Public delegate Sub D1() Public Class C1 End Class Public Structure S1 End Structure Public Enum E1 val End Enum 'Public F1 As Integer Public Sub Sub1() End Interface Public Interface I11 End Interface Public Structure S11 End Structure Public Class C11 End Class Public Enum E11 val End Enum Public Module M11 End Module Public delegate Sub D11() Structure S3 Public Interface I4 End Interface Public delegate Sub D3() Public Class C3 End Class Public Structure S4 End Structure Public Enum E3 val End Enum Public F3 As Integer Public Sub Sub3() End Sub End Structure Module M1 Public Interface I8 End Interface Public delegate Sub D7() Public Class C7 End Class Public Structure S8 End Structure Public Enum E5 val End Enum Public F5 As Integer Public Sub Sub7() End Sub End Module Class C4 Public Interface I6 End Interface Public delegate Sub D5() Public Class C5 End Class Public Structure S6 End Structure Public Enum E7 val End Enum Public F7 As Integer Public Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31068: Delegate in an interface cannot be declared 'Public'. Public delegate Sub D1() ~~~~~~ BC31070: Class in an interface cannot be declared 'Public'. Public Class C1 ~~~~~~ BC31071: Structure in an interface cannot be declared 'Public'. Public Structure S1 ~~~~~~ BC31069: Enum in an interface cannot be declared 'Public'. Public Enum E1 ~~~~~~ BC30270: 'Public' is not valid on an interface method declaration. Public Sub Sub1() ~~~~~~ </expected>) End Sub ' Constructor initializers don't bind yet <WorkItem(7926, "DevDiv_Projects/Roslyn")> <WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")> <Fact> Public Sub StructDefaultConstructorInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StructDefaultConstructorInitializer"> <file name="StructDefaultConstructorInitializer.vb"> Structure S Public _x As Integer Public Sub New(x As Integer) Me.New() ' Note: not allowed in Dev10 End Sub End Structure </file> </compilation>) compilation.VerifyDiagnostics() Dim structType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("S") Dim constructors = structType.GetMembers(WellKnownMemberNames.InstanceConstructorName) Assert.Equal(2, constructors.Length) Dim sourceConstructor = CType(constructors.First(Function(c) Not c.IsImplicitlyDeclared), MethodSymbol) Dim synthesizedConstructor = CType(constructors.First(Function(c) c.IsImplicitlyDeclared), MethodSymbol) Assert.NotEqual(sourceConstructor, synthesizedConstructor) Assert.Equal(1, sourceConstructor.Parameters.Length) Assert.Equal(0, synthesizedConstructor.Parameters.Length) End Sub <Fact> Public Sub MetadataNameOfGenericTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MetadataName"> <file name="a.vb"> Class Gen1(Of T, U, V) End Class Class NonGen End Class </file> </compilation>) Dim globalNS = compilation.GlobalNamespace Dim gen1Class = DirectCast(globalNS.GetMembers("Gen1").First(), NamedTypeSymbol) Assert.Equal("Gen1", gen1Class.Name) Assert.Equal("Gen1`3", gen1Class.MetadataName) Dim nonGenClass = DirectCast(globalNS.GetMembers("NonGen").First(), NamedTypeSymbol) Assert.Equal("NonGen", nonGenClass.Name) Assert.Equal("NonGen", nonGenClass.MetadataName) Dim system = DirectCast(globalNS.GetMembers("System").First(), NamespaceSymbol) Dim equatable = DirectCast(system.GetMembers("IEquatable").First(), NamedTypeSymbol) Assert.Equal("IEquatable", equatable.Name) Assert.Equal("IEquatable`1", equatable.MetadataName) End Sub <Fact()> Public Sub TypeNameSpelling1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Class Aa End Class Public Partial Class AA End Class </file> <file name="b.vb"> Public Partial Class aa End Class </file> </compilation>) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("aa")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("Aa")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("AA")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("aA")(0).Name) End Sub <Fact()> Public Sub TypeNameSpelling2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="b.vb"> Public Partial Class aa End Class </file> <file name="a.vb"> Public Class Aa End Class Public Partial Class AA End Class </file> </compilation>) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("aa")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("Aa")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("AA")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("aA")(0).Name) End Sub <Fact()> Public Sub StructureInstanceConstructors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="b.vb"> Structure S1 Sub new () end sub End Structure Structure S2 Sub new (optional i as integer = 1) end sub End Structure </file> </compilation>) Dim s1 = compilation.GlobalNamespace.GetTypeMembers("s1")(0) Assert.Equal(1, s1.InstanceConstructors.Length) Dim s2 = compilation.GlobalNamespace.GetTypeMembers("s2")(0) Assert.Equal(2, s2.InstanceConstructors.Length) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NewInStruct, "new").WithLocation(2, 9) ) End Sub <Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")> Public Sub ErrorTypeTest01() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="Err"> <file name="b.vb"> Sub TopLevelMethod() End Sub </file> </compilation>) Dim symbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers().LastOrDefault(), NamedTypeSymbol) Assert.Equal("<invalid-global-code>", symbol.Name) Assert.False(symbol.IsErrorType(), "ErrorType") Assert.True(symbol.IsImplicitClass, "ImplicitClass") End Sub <Fact> Public Sub NameCollisionWithAddedModule_01() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ </expected>) CompileAndVerify(compilation) End Sub <Fact> Public Sub NameCollisionWithAddedModule_02() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Public Class C1 End Class Public Class c2 End Class End Namespace Namespace ns1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ BC37210: Type 'C3' conflicts with public type defined in added module 'module.netmodule'. Friend Class C3 ~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_03() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace ns2 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation) End Sub <Fact> Public Sub NameCollisionWithAddedModule_04() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Public Class c1 End Class End Namespace Namespace ns1 Public Class c2 End Class Public Class C3(Of T) End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_05() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace ns1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Friend Class C1 End Class Friend Class c2 End Class Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ BC37210: Type 'C3' conflicts with public type defined in added module 'module.netmodule'. Friend Class C3 ~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_06() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace NS1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Friend Class C1 End Class Friend Class c2 End Class Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_07() Dim ilSource = <![CDATA[ .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(ilSource.Value, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim source = <compilation> <file name="a.vb"> Interface ITest20 End Interface </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {moduleRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37211: Type 'ITest20(Of T)' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_08() Dim ilSource = <![CDATA[ .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(ilSource.Value, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim mod2 = <compilation name="mod_1_2"> <file name="a.vb"> namespace ns public interface c1 end interface public interface c3 end interface end namespace public interface c2 end interface public interface c4 end interface namespace ns1 public interface c5 end interface end namespace </file> </compilation> Dim source = <compilation> <file name="a.vb"> </file> </compilation> Dim moduleRef2 = CreateCompilationWithMscorlib40(mod2, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {moduleRef1, moduleRef2}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37212: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2(Of T)' exported from module 'mod_1_1.netmodule'. BC37212: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1(Of T)' exported from module 'mod_1_1.netmodule'. </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_09() Dim forwardedTypesSource = <compilation name=""> <file name="a.vb"> Public Class CF1 End Class namespace ns Public Class CF2 End Class End Namespace public class CF3(Of T) End Class </file> </compilation> forwardedTypesSource.@name = "ForwardedTypes1" Dim forwardedTypes1 = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseDll) Dim forwardedTypes1Ref = New VisualBasicCompilationReference(forwardedTypes1) forwardedTypesSource.@name = "ForwardedTypes2" Dim forwardedTypes2 = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseDll) Dim forwardedTypes2Ref = New VisualBasicCompilationReference(forwardedTypes2) forwardedTypesSource.@name = "forwardedTypesMod" Dim forwardedTypesModRef = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim modSource = <![CDATA[ .assembly extern <<TypesForWardedToAssembly>> { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF1 { .assembly extern <<TypesForWardedToAssembly>> } .class extern forwarder ns.CF2 { .assembly extern <<TypesForWardedToAssembly>> } .module <<ModuleName>>.netmodule // MVID: {987C2448-14BC-48E8-BE36-D24E14D49864} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D90000 ]]>.Value Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module1_FT1").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes1"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module1_FT1_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module2_FT1").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes1"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module2_FT1_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module3_FT2").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes2"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module3_FT2_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim module4_FT1_source = <![CDATA[ .assembly extern ForwardedTypes1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF3`1 { .assembly extern ForwardedTypes1 } .module module4_FT1.netmodule // MVID: {5C652C9E-35F2-4D1D-B2A4-68683237D8F1} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x01100000 ]]>.Value Using reference = IlasmUtilities.CreateTempAssembly(module4_FT1_source, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module4_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() forwardedTypesSource.@name = "consumer" Dim compilation = CreateCompilationWithMscorlib40AndReferences(forwardedTypesSource, { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37217: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. BC37217: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. </expected>) Dim emptySource = <compilation> <file name="a.vb"> </file> </compilation> compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37218: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. BC37218: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37218: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. BC37218: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) ' Exported types in .NET modules cause PEVerify to fail. CompileAndVerify(compilation, verify:=Verification.Fails).VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37219: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. BC37219: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. </expected>) End Sub <Fact> Public Sub PartialModules() Dim verifier = CompileAndVerify( <compilation name="PartialModules"> <file name="Program.vb"> Imports System.Console Module Program Sub Main() Write(Syntax.SyntaxFacts.IsExpressionKind(0)) Write(Syntax.SyntaxFacts.IsStatementKind(0)) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(GetType(MyTestAttribute1), False).Length) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(GetType(MyTestAttribute2), False).Length) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(False).Length) End Sub End Module Public Class MyTestAttribute1 Inherits System.Attribute End Class Public Class MyTestAttribute2 Inherits System.Attribute End Class </file> <file name="SyntaxFacts.vb"><![CDATA[ Namespace Syntax <MyTestAttribute1> Module SyntaxFacts Public Function IsExpressionKind(kind As Integer) As Boolean Return False End Function End Module End Namespace ]]></file> <file name="GeneratedSyntaxFacts.vb"><![CDATA[ Namespace Syntax <MyTestAttribute2> Partial Module SyntaxFacts Public Function IsStatementKind(kind As Integer) As Boolean Return True End Function End Module End Namespace ]]></file> </compilation>, expectedOutput:="FalseTrue113") End Sub <Fact> Public Sub PartialInterfaces() Dim verifier = CompileAndVerify( <compilation name="PartialModules"> <file name="Program.vb"> Imports System Imports System.Console Module Program Sub Main() Dim customer As ICustomer = New Customer() With { .Name = "Unnamed" } ValidateCustomer(customer) End Sub Sub ValidateCustomer(customer As ICustomer) Write(customer.Id = Guid.Empty) Write(customer.NameHash = customer.Name.GetHashCode()) Write(GetType(ICustomer).GetCustomAttributes(GetType(MyTestAttribute1), False).Length) Write(GetType(ICustomer).GetCustomAttributes(GetType(MyTestAttribute2), False).Length) Write(GetType(ICustomer).GetCustomAttributes(False).Length) End Sub End Module Public Class MyTestAttribute1 Inherits System.Attribute End Class Public Class MyTestAttribute2 Inherits System.Attribute End Class </file> <file name="ViewModels.vb"><![CDATA[ Imports System ' We only need this property for Silverlight. We omit this file when building for WPF. <MyTestAttribute1> Partial Interface ICustomer ReadOnly Property NameHash As Integer End Interface Partial Class Customer Private ReadOnly Property NameHash As Integer Implements ICustomer.NameHash Get Return Name.GetHashCode() End Get End Property End Class ]]></file> <file name="GeneratedViewModels.vb"><![CDATA[ Imports System <MyTestAttribute2> Partial Interface ICustomer ReadOnly Property Id As Guid Property Name As String End Interface Partial Class Customer Implements ICustomer Private ReadOnly _Id As Guid Public ReadOnly Property Id As Guid Implements ICustomer.Id Get return _Id End Get End Property Public Property Name As String Implements ICustomer.Name Public Sub New() Me.New(Guid.NewGuid()) End Sub Public Sub New(id As Guid) _Id = id End Sub End Class ]]></file> </compilation>, expectedOutput:="FalseTrue112") End Sub <Fact, WorkItem(8400, "https://github.com/dotnet/roslyn/issues/8400")> Public Sub WrongModifier() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"><![CDATA[ public class AAA : IBBB { public static AAA MMM(Stream xamlStream) { // Note: create custom module catalog ]]></file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30481: 'Class' statement must end with a matching 'End Class'. public class AAA : IBBB ~~~~~~~~~~~~~~~~ BC30188: Declaration expected. public class AAA : IBBB ~~~~ BC30035: Syntax error. { ~ BC30235: 'static' is not valid on a member variable declaration. public static AAA MMM(Stream xamlStream) ~~~~~~ BC30205: End of statement expected. public static AAA MMM(Stream xamlStream) ~~~ BC30035: Syntax error. { ~ BC30035: Syntax error. // Note: create custom module catalog ~ BC30188: Declaration expected. // Note: create custom module catalog ~~~~~~ BC31140: 'Custom' modifier can only be used immediately before an 'Event' declaration. // Note: create custom module catalog ~~~~~~ BC30617: 'Module' statements can occur only at file or namespace level. // Note: create custom module catalog ~~~~~~~~~~~~~~~~~~~~~ BC30625: 'Module' statement must end with a matching 'End Module'. // Note: create custom module catalog ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_01() Dim sources = <compilation> <file><![CDATA[ Imports System.Runtime.InteropServices <typeidentifier> Public Interface I1 End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") i1.GetAttributes() Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports System.Runtime.InteropServices <TypeIdentifierAttribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_03() Dim sources = <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifier <alias1> Public Interface I1 End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'System.Runtime.InteropServices.TypeIdentifier' 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 alias1 = System.Runtime.InteropServices.TypeIdentifier ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. <alias1> ~~~~~~ ]]></expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") i1.GetAttributes() Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifier <alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'System.Runtime.InteropServices.TypeIdentifier' 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 alias1 = System.Runtime.InteropServices.TypeIdentifier ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'alias1Attribute' is not defined. <alias1Attribute> ~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_05() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.typeIdentifierattribute <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_06() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_07() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_08() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attributeAttribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_09() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias2 = alias1 <alias2> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'alias1' 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 alias2 = alias1 ~~~~~~ BC30182: Type expected. <alias2> ~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <alias1> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias2 = I1 <alias1> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_12() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute Imports System.Runtime.CompilerServices <alias1> Public Partial Interface I1 End Interface <CompilerGenerated> Public Partial Interface I2 End Interface ]]></file> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.ComImportAttribute <alias1> Public Partial Interface I1 End Interface <alias1> Public Partial Interface I2 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Dim i2 = compilation.SourceAssembly.GetTypeByMetadataName("I2") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) Assert.False(i2.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_13() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.ComImportAttribute <alias1> Public Partial Interface I1 End Interface <alias1> Public Partial Interface I2 End Interface ]]></file> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute Imports System.Runtime.CompilerServices <alias1> Public Partial Interface I1 End Interface <CompilerGenerated> Public Partial Interface I2 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Dim i2 = compilation.SourceAssembly.GetTypeByMetadataName("I2") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) Assert.False(i2.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_14() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC30182: Type expected. <alias1> ~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_15() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <System.Runtime.InteropServices.TypeIdentifier> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_16() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <System.Runtime.InteropServices.TypeIdentifierAttribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_17() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_ContainingType_GenericNestedType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_ContainingType_GenericNestedType"> <file name="a.vb"> Public Class C(Of T) Public Interface I(Of U) End Interface End Class </file> </compilation>) AssertNoDeclarationDiagnostics(compilation) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim iDefinition = compilation.GetMember(Of NamedTypeSymbol)("C.I") Assert.Equal("C(Of T).I(Of U)", iDefinition.ToTestDisplayString()) Assert.True(iDefinition.IsDefinition) ' Construct from iDefinition with modified U from iDefinition Dim modifiedU = ImmutableArray.Create(New TypeWithModifiers(iDefinition.TypeParameters.Single(), modifiers)) Dim i1 = iDefinition.Construct(TypeSubstitution.Create(iDefinition, iDefinition.TypeParameters, modifiedU)) Assert.Equal("C(Of T).I(Of U modopt(System.Object))", i1.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i1) Dim cDefinition = iDefinition.ContainingType Assert.Equal("C(Of T)", cDefinition.ToTestDisplayString()) Assert.True(cDefinition.IsDefinition) ' Construct from cDefinition with modified T from cDefinition Dim modifiedT = ImmutableArray.Create(New TypeWithModifiers(cDefinition.TypeParameters.Single(), modifiers)) Dim c2 = cDefinition.Construct(TypeSubstitution.Create(cDefinition, cDefinition.TypeParameters, modifiedT)) Dim i2 = c2.GetTypeMember("I") Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i2.ToTestDisplayString()) Assert.Same(i2.OriginalDefinition, iDefinition) AssertHashCodesMatch(iDefinition, i2) ' Construct from i2 with U from iDefinition Dim i2a = i2.Construct(iDefinition.TypeParameters.Single()) Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i2a.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i2a) ' Construct from i2 (reconstructed) with modified U from iDefinition Dim i2b = iDefinition.Construct(TypeSubstitution.Create(iDefinition, ImmutableArray.Create(cDefinition.TypeParameters.Single(), iDefinition.TypeParameters.Single()), ImmutableArray.Create(modifiedT.Single(), modifiedU.Single()))) Assert.Equal("C(Of T modopt(System.Object)).I(Of U modopt(System.Object))", i2b.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i2b) ' Construct from cDefinition with modified T from cDefinition Dim c4 = cDefinition.Construct(TypeSubstitution.Create(cDefinition, cDefinition.TypeParameters, modifiedT)) Assert.Equal("C(Of T modopt(System.Object))", c4.ToTestDisplayString()) Assert.False(c4.IsDefinition) AssertHashCodesMatch(cDefinition, c4) Dim i4 = c4.GetTypeMember("I") Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i4.ToTestDisplayString()) Assert.Same(i4.OriginalDefinition, iDefinition) AssertHashCodesMatch(iDefinition, i4) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_ContainingType_GenericNestedType_Nested() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_ContainingType_GenericNestedType"> <file name="a.vb"> Public Class C(Of T) Public Class C2(Of U) Public Interface I(Of V) End Interface End Class End Class </file> </compilation>) AssertNoDeclarationDiagnostics(compilation) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim iDefinition = compilation.GetMember(Of NamedTypeSymbol)("C.C2.I") Assert.Equal("C(Of T).C2(Of U).I(Of V)", iDefinition.ToTestDisplayString()) Assert.True(iDefinition.IsDefinition) Dim c2Definition = iDefinition.ContainingType Dim cDefinition = c2Definition.ContainingType Dim modifiedT = New TypeWithModifiers(cDefinition.TypeParameters.Single(), modifiers) Dim modifiedU = New TypeWithModifiers(c2Definition.TypeParameters.Single(), modifiers) Dim modifiedV = New TypeWithModifiers(iDefinition.TypeParameters.Single(), modifiers) Dim i = iDefinition.Construct(TypeSubstitution.Create(iDefinition, ImmutableArray.Create(cDefinition.TypeParameters.Single(), c2Definition.TypeParameters.Single(), iDefinition.TypeParameters.Single()), ImmutableArray.Create(modifiedT, modifiedU, modifiedV))) Assert.Equal("C(Of T modopt(System.Object)).C2(Of U modopt(System.Object)).I(Of V modopt(System.Object))", i.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_SubstitutedErrorType() Dim missing = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class C(Of T) Public Class D(Of U) End Class End Class </file> </compilation>) AssertNoDeclarationDiagnostics(missing) Dim reference = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class Reference(Of T, U) Inherits C(Of T).D(Of U) End Class </file> </compilation>, references:={missing.EmitToImageReference()}) AssertNoDeclarationDiagnostics(reference) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class Program(Of V, W) Inherits Reference(Of V, W) End Class </file> </compilation>, references:={reference.EmitToImageReference()}) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'C(Of ).D(Of )' from assembly or module 'TypeSymbolGetHashCode_SubstitutedErrorType.dll' failed. Public Class Program(Of V, W) ~~~~~~~ BC31091: Import of type 'C(Of ).D(Of )' from assembly or module 'TypeSymbolGetHashCode_SubstitutedErrorType.dll' failed. Inherits Reference(Of V, W) ~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim programType = compilation.GlobalNamespace.GetTypeMember("Program") Dim errorType = programType.BaseType.BaseType Dim definition = errorType.OriginalDefinition Assert.Equal("Microsoft.CodeAnalysis.VisualBasic.Symbols.SubstitutedErrorType", errorType.GetType().ToString()) Assert.Equal("C(Of )[missing].D(Of )[missing]", definition.ToTestDisplayString()) Assert.True(definition.IsDefinition) ' Construct from definition with modified U from definition Dim modifiedU = ImmutableArray.Create(New TypeWithModifiers(definition.TypeParameters.Single(), modifiers)) Dim t1 = definition.Construct(TypeSubstitution.Create(definition, definition.TypeParameters, modifiedU)) Assert.Equal("C(Of )[missing].D(Of modopt(System.Object))[missing]", t1.ToTestDisplayString()) AssertHashCodesMatch(definition, t1) End Sub Private Shared Sub AssertHashCodesMatch(c As NamedTypeSymbol, c2 As NamedTypeSymbol) Assert.False(c.IsSameType(c2, TypeCompareKind.ConsiderEverything)) Assert.True(c.IsSameType(c2, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.False(c2.IsSameType(c, TypeCompareKind.ConsiderEverything)) Assert.True(c2.IsSameType(c, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.Equal(c2.GetHashCode(), c.GetHashCode()) If c.Arity <> 0 Then Dim ctp = c.TypeParameters(0) Dim ctp2 = c2.TypeParameters(0) If ctp IsNot ctp2 Then Assert.False(ctp.IsSameType(ctp2, TypeCompareKind.ConsiderEverything)) Assert.True(ctp.IsSameType(ctp2, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.False(ctp2.IsSameType(ctp, TypeCompareKind.ConsiderEverything)) Assert.True(ctp2.IsSameType(ctp, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.Equal(ctp2.GetHashCode(), ctp.GetHashCode()) End If End If 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class TypeTests Inherits BasicTestBase <Fact> Public Sub AlphaRenaming() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Class A(Of T) Public Class B(Of U) Public X As A(Of A(Of U)) End Class End Class Public Class A1 Inherits A(Of Integer) End Class Public Class A2 Inherits A(Of Integer) End Class </file> </compilation>) Dim aint1 = compilation.GlobalNamespace.GetTypeMembers("A1")(0).BaseType ' A<int> Dim aint2 = compilation.GlobalNamespace.GetTypeMembers("A2")(0).BaseType ' A<int> Dim b1 = aint1.GetTypeMembers("B", 1).Single() ' A<int>.B<U> Dim b2 = aint2.GetTypeMembers("B", 1).Single() ' A<int>.B<U> Assert.NotSame(b1.TypeParameters(0), b2.TypeParameters(0)) ' they've been alpha renamed independently Assert.Equal(b1.TypeParameters(0), b2.TypeParameters(0)) ' but happen to be the same type Dim xtype1 = DirectCast(b1.GetMembers("X")(0), FieldSymbol).Type ' Types using them are the same too Dim xtype2 = DirectCast(b2.GetMembers("X")(0), FieldSymbol).Type Assert.Equal(xtype1, xtype2) End Sub <Fact> Public Sub SourceTypeSymbols1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Friend Interface A End Interface Namespace n Partial Public MustInherit Class B End Class Structure I End Structure End Namespace </file> <file name="b.vb"> Namespace N Partial Public Class b End Class Friend Enum E A End Enum Friend Delegate Function B(Of T)() As String Module M End Module End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(2, globalNS.GetMembers().Length()) Dim membersNamedA = globalNS.GetMembers("a") Assert.Equal(1, membersNamedA.Length) Dim membersNamedN = globalNS.GetMembers("n") Assert.Equal(1, membersNamedN.Length) Dim ifaceA = DirectCast(membersNamedA(0), NamedTypeSymbol) Assert.Equal(globalNS, ifaceA.ContainingSymbol) Assert.Equal("A", ifaceA.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, ifaceA.Kind) Assert.Equal(TypeKind.Interface, ifaceA.TypeKind) Assert.Equal(Accessibility.Friend, ifaceA.DeclaredAccessibility) Assert.False(ifaceA.IsNotInheritable) Assert.True(ifaceA.IsMustInherit) Assert.True(ifaceA.IsReferenceType) Assert.False(ifaceA.IsValueType) Assert.Equal(0, ifaceA.Arity) Assert.Null(ifaceA.BaseType) Dim nsN = DirectCast(membersNamedN(0), NamespaceSymbol) Dim membersOfN = nsN.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(5, membersOfN.Length) Dim classB = DirectCast(membersOfN(0), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("B", 0).First(), classB) Assert.Equal(nsN, classB.ContainingSymbol) Assert.Equal("B", classB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, classB.Kind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Equal(Accessibility.Public, classB.DeclaredAccessibility) Assert.False(classB.IsNotInheritable) Assert.True(classB.IsMustInherit) Assert.True(classB.IsReferenceType) Assert.False(classB.IsValueType) Assert.Equal(0, classB.Arity) Assert.Equal(0, classB.TypeParameters.Length) Assert.Equal(2, classB.Locations.Length()) Assert.Equal(1, classB.InstanceConstructors.Length()) Assert.Equal("System.Object", classB.BaseType.ToTestDisplayString()) Dim delegateB = DirectCast(membersOfN(1), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("B", 1).First(), delegateB) Assert.Equal(nsN, delegateB.ContainingSymbol) Assert.Equal("B", delegateB.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, delegateB.Kind) Assert.Equal(TypeKind.Delegate, delegateB.TypeKind) Assert.Equal(Accessibility.Friend, delegateB.DeclaredAccessibility) Assert.True(delegateB.IsNotInheritable) Assert.False(delegateB.IsMustInherit) Assert.True(delegateB.IsReferenceType) Assert.False(delegateB.IsValueType) Assert.Equal(1, delegateB.Arity) Assert.Equal(1, delegateB.TypeParameters.Length) Assert.Equal(0, delegateB.TypeParameters(0).Ordinal) Assert.Same(delegateB, delegateB.TypeParameters(0).ContainingSymbol) Assert.Equal(1, delegateB.Locations.Length()) Assert.Equal("System.MulticastDelegate", delegateB.BaseType.ToTestDisplayString()) #If Not DISABLE_GOOD_HASH_TESTS Then Assert.NotEqual(IdentifierComparison.GetHashCode("A"), IdentifierComparison.GetHashCode("B")) #End If Dim enumE = DirectCast(membersOfN(2), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("E", 0).First(), enumE) Assert.Equal(nsN, enumE.ContainingSymbol) Assert.Equal("E", enumE.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, enumE.Kind) Assert.Equal(TypeKind.Enum, enumE.TypeKind) Assert.Equal(Accessibility.Friend, enumE.DeclaredAccessibility) Assert.True(enumE.IsNotInheritable) Assert.False(enumE.IsMustInherit) Assert.False(enumE.IsReferenceType) Assert.True(enumE.IsValueType) Assert.Equal(0, enumE.Arity) Assert.Equal(1, enumE.Locations.Length()) Assert.Equal("System.Enum", enumE.BaseType.ToTestDisplayString()) Dim structI = DirectCast(membersOfN(3), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("i", 0).First(), structI) Assert.Equal(nsN, structI.ContainingSymbol) Assert.Equal("I", structI.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, structI.Kind) Assert.Equal(TypeKind.Structure, structI.TypeKind) Assert.Equal(Accessibility.Friend, structI.DeclaredAccessibility) Assert.True(structI.IsNotInheritable) Assert.False(structI.IsMustInherit) Assert.False(structI.IsReferenceType) Assert.True(structI.IsValueType) Assert.Equal(0, structI.Arity) Assert.Equal(1, structI.Locations.Length()) Assert.Equal("System.ValueType", structI.BaseType.ToTestDisplayString()) Dim moduleM = DirectCast(membersOfN(4), NamedTypeSymbol) Assert.Equal(nsN.GetTypeMembers("m", 0).First(), moduleM) Assert.Equal(nsN, moduleM.ContainingSymbol) Assert.Equal("M", moduleM.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, moduleM.Kind) Assert.Equal(TypeKind.Module, moduleM.TypeKind) Assert.Equal(Accessibility.Friend, moduleM.DeclaredAccessibility) Assert.True(moduleM.IsNotInheritable) Assert.False(moduleM.IsMustInherit) Assert.True(moduleM.IsReferenceType) Assert.False(moduleM.IsValueType) Assert.Equal(0, moduleM.Arity) Assert.Equal(1, moduleM.Locations.Length()) Assert.Equal("System.Object", moduleM.BaseType.ToTestDisplayString()) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'n' does not match casing of namespace name 'N' in 'b.vb'. Namespace n ~ </expected>) End Sub <Fact> Public Sub NestedSourceTypeSymbols() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Partial Class Outer(Of K) Private Partial Class I1 Protected Partial Structure I2(Of T, U) End Structure End Class Private Partial Class I1 Protected Partial Structure I2(Of W) End Structure End Class Enum I4 X End Enum End Class Public Partial Class Outer(Of K) Protected Friend Interface I3 End Interface End Class </file> <file name="b.vb"> Public Class outer(Of K) Private Partial Class i1 Protected Partial Structure i2(Of T, U) End Structure End Class End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim outerClass = DirectCast(globalNSmembers(0), NamedTypeSymbol) Assert.Equal(globalNS, outerClass.ContainingSymbol) Assert.Equal("Outer", outerClass.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, outerClass.Kind) Assert.Equal(TypeKind.Class, outerClass.TypeKind) Assert.Equal(Accessibility.Public, outerClass.DeclaredAccessibility) Assert.Equal(1, outerClass.Arity) Assert.Equal(1, outerClass.TypeParameters.Length) Dim outerTypeParam = outerClass.TypeParameters(0) Assert.Equal(0, outerTypeParam.Ordinal) Assert.Same(outerClass, outerTypeParam.ContainingSymbol) Dim membersOfOuter = outerClass.GetTypeMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(3, membersOfOuter.Length) Dim i1Class = membersOfOuter(0) Assert.Equal(1, outerClass.GetTypeMembers("i1").Length()) Assert.Same(i1Class, outerClass.GetTypeMembers("i1").First()) Assert.Equal("I1", i1Class.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i1Class.Kind) Assert.Equal(TypeKind.Class, i1Class.TypeKind) Assert.Equal(Accessibility.Private, i1Class.DeclaredAccessibility) Assert.Equal(0, i1Class.Arity) Assert.Equal(3, i1Class.Locations.Length()) Dim i3Interface = membersOfOuter(1) Assert.Equal(1, outerClass.GetTypeMembers("i3").Length()) Assert.Same(i3Interface, outerClass.GetTypeMembers("i3").First()) Assert.Equal("I3", i3Interface.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i3Interface.Kind) Assert.Equal(TypeKind.Interface, i3Interface.TypeKind) Assert.Equal(Accessibility.ProtectedOrFriend, i3Interface.DeclaredAccessibility) Assert.Equal(0, i3Interface.Arity) Assert.Equal(1, i3Interface.Locations.Length()) Dim i4Enum = membersOfOuter(2) Assert.Equal(1, outerClass.GetTypeMembers("i4").Length()) Assert.Same(i4Enum, outerClass.GetTypeMembers("i4").First()) Assert.Equal("I4", i4Enum.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i4Enum.Kind) Assert.Equal(TypeKind.Enum, i4Enum.TypeKind) Assert.Equal(Accessibility.Public, i4Enum.DeclaredAccessibility) Assert.Equal(0, i4Enum.Arity) Assert.Equal(1, i4Enum.Locations.Length()) Dim membersOfI1 = i1Class.GetTypeMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(2, membersOfI1.Length) Assert.Equal(2, i1Class.GetTypeMembers("I2").Length()) Dim i2Arity1 = membersOfI1(0) Assert.Equal(1, i1Class.GetTypeMembers("i2", 1).Length()) Assert.Same(i2Arity1, i1Class.GetTypeMembers("i2", 1).First()) Assert.Equal("I2", i2Arity1.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i2Arity1.Kind) Assert.Equal(TypeKind.Structure, i2Arity1.TypeKind) Assert.Equal(Accessibility.Protected, i2Arity1.DeclaredAccessibility) Assert.Equal(1, i2Arity1.Arity) Assert.Equal(1, i2Arity1.TypeParameters.Length) Dim i2Arity1TypeParam = i2Arity1.TypeParameters(0) Assert.Equal(0, i2Arity1TypeParam.Ordinal) Assert.Same(i2Arity1, i2Arity1TypeParam.ContainingSymbol) Assert.Equal(1, i2Arity1.Locations.Length()) Dim i2Arity2 = membersOfI1(1) Assert.Equal(1, i1Class.GetTypeMembers("i2", 2).Length()) Assert.Same(i2Arity2, i1Class.GetTypeMembers("i2", 2).First()) Assert.Equal("I2", i2Arity2.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, i2Arity2.Kind) Assert.Equal(TypeKind.Structure, i2Arity2.TypeKind) Assert.Equal(Accessibility.Protected, i2Arity2.DeclaredAccessibility) Assert.Equal(2, i2Arity2.Arity) Assert.Equal(2, i2Arity2.TypeParameters.Length) Dim i2Arity2TypeParam0 = i2Arity2.TypeParameters(0) Assert.Equal(0, i2Arity2TypeParam0.Ordinal) Assert.Same(i2Arity2, i2Arity2TypeParam0.ContainingSymbol) Dim i2Arity2TypeParam1 = i2Arity2.TypeParameters(1) Assert.Equal(1, i2Arity2TypeParam1.Ordinal) Assert.Same(i2Arity2, i2Arity2TypeParam1.ContainingSymbol) Assert.Equal(2, i2Arity2.Locations.Length()) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(2200, "DevDiv_Projects/Roslyn")> <Fact> Public Sub ArrayTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public Shared AryField()(,) as Object Friend fAry01(9) as String Dim fAry02(9) as String Function M(ByVal ary1() As Byte, ByRef ary2()() as Single, ParamArray ary3(,) As Long) As String() Return Nothing End Function End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim members = classTest.GetMembers() Dim field1 = DirectCast(members(1), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) Dim sym1 = field1.Type ' Object Assert.Equal(SymbolKind.ArrayType, sym1.Kind) Assert.Equal(Accessibility.NotApplicable, sym1.DeclaredAccessibility) Assert.False(sym1.IsShared) Assert.Null(sym1.ContainingAssembly) ' bug 2200 field1 = DirectCast(members(2), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) field1 = DirectCast(members(3), FieldSymbol) Assert.Equal(SymbolKind.ArrayType, field1.Type.Kind) Dim mem1 = DirectCast(members(4), MethodSymbol) Assert.Equal(3, mem1.Parameters.Length()) Dim sym2 = mem1.Parameters(0) Assert.Equal("ary1", sym2.Name) Assert.Equal(SymbolKind.ArrayType, sym2.Type.Kind) Assert.Equal("Array", sym2.Type.BaseType.Name) Dim sym3 = mem1.Parameters(1) Assert.Equal("ary2", sym3.Name) Assert.True(sym3.IsByRef) Assert.Equal(SymbolKind.ArrayType, sym3.Type.Kind) Dim sym4 = mem1.Parameters(2) Assert.Equal("ary3", sym4.Name) Assert.Equal(SymbolKind.ArrayType, sym4.Type.Kind) Assert.Equal(0, sym4.Type.GetTypeMembers().Length()) Assert.Equal(0, sym4.Type.GetTypeMembers(String.Empty).Length()) Assert.Equal(0, sym4.Type.GetTypeMembers(String.Empty, 0).Length()) Dim sym5 = mem1.ReturnType Assert.Equal(SymbolKind.ArrayType, sym5.Kind) Assert.Equal(0, sym5.GetAttributes().Length()) End Sub <WorkItem(537281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537281")> <WorkItem(537300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537300")> <WorkItem(932303, "DevDiv/Personal")> <Fact> Public Sub ArrayTypeInterfaces() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public AryField() As Object Shared AryField2()() As Integer Private AryField3(,,) As Byte Public Sub New() End Sub End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim sym1 = DirectCast(classTest.GetMembers().First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym1.Kind) ' IList(Of T) Assert.Equal(1, sym1.Interfaces.Length) Dim itype1 = sym1.Interfaces(0) Assert.Equal("System.Collections.Generic.IList(Of System.Object)", itype1.ToTestDisplayString()) ' Jagged array's rank is 1 Dim sym2 = DirectCast(classTest.GetMembers("AryField2").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym2.Kind) Assert.Equal(1, sym2.Interfaces.Length) Dim itype2 = sym2.Interfaces(0) Assert.Equal("System.Collections.Generic.IList(Of System.Int32())", itype2.ToTestDisplayString()) Dim sym3 = DirectCast(classTest.GetMembers("AryField3").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym3.Kind) Assert.Equal(0, sym3.Interfaces.Length) Assert.Throws(Of ArgumentNullException)(Sub() compilation.CreateArrayTypeSymbol(Nothing)) End Sub <WorkItem(537420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537420")> <WorkItem(537515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537515")> <Fact> Public Sub ArrayTypeGetFullNameAndHashCode() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ArrayTypes"> <file name="a.vb"> Public Class A Public Shared AryField1() As Integer Private AryField2(,,) As String Protected AryField3()(,) As Byte Shared AryField4 As ULong(,)() Friend AryField5(9) As Long Dim AryField6(2,4) As Object Public Abc(), Bbc(,,,), Cbc()() Public Sub New() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("A").Single(), NamedTypeSymbol) Dim mems = classTest.GetMembers() Dim sym1 = DirectCast(classTest.GetMembers().First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym1.Kind) Assert.Equal("System.Int32()", sym1.ToTestDisplayString()) Dim v1 = sym1.GetHashCode() Dim v2 = sym1.GetHashCode() Assert.Equal(v1, v2) Dim sym21 = DirectCast(classTest.GetMembers("AryField2").First(), FieldSymbol) Assert.Equal(1, sym21.Locations.Length) Dim span = DirectCast(sym21.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(16, span.StartLinePosition.Character) Assert.Equal(25, span.EndLinePosition.Character) Assert.Equal("AryField2", sym21.Name) Assert.Equal("A.AryField2 As System.String(,,)", sym21.ToTestDisplayString()) Dim sym22 = sym21.Type Assert.Equal(SymbolKind.ArrayType, sym22.Kind) Assert.Equal("System.String(,,)", sym22.ToTestDisplayString()) v1 = sym22.GetHashCode() v2 = sym22.GetHashCode() Assert.Equal(v1, v2) Dim sym3 = DirectCast(classTest.GetMembers("AryField3").First(), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym3.Kind) Assert.Equal("System.Byte()(,)", sym3.ToTestDisplayString()) v1 = sym3.GetHashCode() v2 = sym3.GetHashCode() Assert.Equal(v1, v2) Dim sym4 = DirectCast(mems(3), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym4.Kind) Assert.Equal("System.UInt64(,)()", sym4.ToTestDisplayString()) v1 = sym4.GetHashCode() v2 = sym4.GetHashCode() Assert.Equal(v1, v2) Dim sym5 = DirectCast(mems(4), FieldSymbol).Type Assert.Equal(SymbolKind.ArrayType, sym5.Kind) Assert.Equal("System.Int64()", sym5.ToTestDisplayString()) v1 = sym5.GetHashCode() v2 = sym5.GetHashCode() Assert.Equal(v1, v2) Dim sym61 = DirectCast(mems(5), FieldSymbol) span = DirectCast(sym61.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(12, span.StartLinePosition.Character) Assert.Equal(21, span.EndLinePosition.Character) Dim sym62 = sym61.Type Assert.Equal(SymbolKind.ArrayType, sym62.Kind) Assert.Equal("System.Object(,)", sym62.ToTestDisplayString()) v1 = sym62.GetHashCode() v2 = sym62.GetHashCode() Assert.Equal(v1, v2) Dim sym71 = DirectCast(classTest.GetMembers("Abc").First(), FieldSymbol) Assert.Equal("system.object()", sym71.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym71.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(15, span.StartLinePosition.Character) Assert.Equal(18, span.EndLinePosition.Character) Dim sym72 = DirectCast(classTest.GetMembers("bBc").First(), FieldSymbol) Assert.Equal("system.object(,,,)", sym72.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym72.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(22, span.StartLinePosition.Character) Assert.Equal(25, span.EndLinePosition.Character) Dim sym73 = DirectCast(classTest.GetMembers("cbC").First(), FieldSymbol) Assert.Equal("system.object()()", sym73.Type.ToTestDisplayString().ToLower()) span = DirectCast(sym73.Locations(0), Location).GetLineSpan() Assert.Equal(span.StartLinePosition.Line, span.EndLinePosition.Line) Assert.Equal(32, span.StartLinePosition.Character) Assert.Equal(35, span.EndLinePosition.Character) Assert.Equal("A.Cbc As System.Object()()", sym73.ToTestDisplayString()) End Sub <Fact(), WorkItem(537187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537187"), WorkItem(529941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529941")> Public Sub EnumFields() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="EnumFields"> <file name="a.vb"> Public Enum E One Two = 2 Three End Enum </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Assert.Equal("", globalNS.Name) Assert.Equal(SymbolKind.Namespace, globalNS.Kind) Assert.Equal(1, globalNS.GetMembers().Length()) Dim enumE = globalNS.GetTypeMembers("E", 0).First() Assert.Equal("E", enumE.Name, IdentifierComparison.Comparer) Assert.Equal(SymbolKind.NamedType, enumE.Kind) Assert.Equal(TypeKind.Enum, enumE.TypeKind) Assert.Equal(Accessibility.Public, enumE.DeclaredAccessibility) Assert.True(enumE.IsNotInheritable) Assert.False(enumE.IsMustInherit) Assert.False(enumE.IsReferenceType) Assert.True(enumE.IsValueType) Assert.Equal(0, enumE.Arity) Assert.Equal("System.Enum", enumE.BaseType.ToTestDisplayString()) Dim enumMembers = enumE.GetMembers() Assert.Equal(5, enumMembers.Length) Dim ctor = enumMembers.Where(Function(s) s.Kind = SymbolKind.Method) Assert.Equal(1, ctor.Count) Assert.Equal(SymbolKind.Method, ctor(0).Kind) Dim _val = enumMembers.Where(Function(s) Not s.IsShared AndAlso s.Kind = SymbolKind.Field) Assert.Equal(1, _val.Count) Dim emem = enumMembers.Where(Function(s) s.IsShared) Assert.Equal(3, emem.Count) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> Public Sub SimpleGenericType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Generic"> <file name="g.vb"> Namespace NS Public Interface IGoo(Of T) End Interface Friend Class A(Of V) End Class Public Structure S(Of X, Y) End Structure End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim namespaceNS = globalNS.GetMembers("NS") Dim nsNS = DirectCast(namespaceNS(0), NamespaceSymbol) Dim membersOfNS = nsNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, NamedTypeSymbol).Arity).ToArray() Assert.Equal(3, membersOfNS.Length) Dim classA = DirectCast(membersOfNS(0), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("A").First(), classA) Assert.Equal(nsNS, classA.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, classA.Kind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(Accessibility.Friend, classA.DeclaredAccessibility) Assert.Equal(1, classA.TypeParameters.Length) Assert.Equal("V", classA.TypeParameters(0).Name) Assert.Equal(1, classA.TypeArguments.Length) Dim igoo = DirectCast(membersOfNS(1), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("IGoo").First(), igoo) Assert.Equal(nsNS, igoo.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, igoo.Kind) Assert.Equal(TypeKind.Interface, igoo.TypeKind) Assert.Equal(Accessibility.Public, igoo.DeclaredAccessibility) Assert.Equal(1, igoo.TypeParameters.Length) Assert.Equal("T", igoo.TypeParameters(0).Name) Assert.Equal(1, igoo.TypeArguments.Length) Dim structS = DirectCast(membersOfNS(2), NamedTypeSymbol) Assert.Equal(nsNS.GetTypeMembers("S").First(), structS) Assert.Equal(nsNS, structS.ContainingSymbol) Assert.Equal(SymbolKind.NamedType, structS.Kind) Assert.Equal(TypeKind.Structure, structS.TypeKind) Assert.Equal(Accessibility.Public, structS.DeclaredAccessibility) Assert.Equal(2, structS.TypeParameters.Length) Assert.Equal("X", structS.TypeParameters(0).Name) Assert.Equal("Y", structS.TypeParameters(1).Name) Assert.Equal(2, structS.TypeArguments.Length) End Sub ' Check that type parameters work correctly. <Fact> Public Sub TypeParameters() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Interface Z(Of T, In U, Out V) End Interface </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim interfaceZ = DirectCast(globalNSmembers(0), NamedTypeSymbol) Dim typeParams = interfaceZ.TypeParameters Assert.Equal(3, typeParams.Length) Assert.Equal("T", typeParams(0).Name) Assert.Equal(VarianceKind.None, typeParams(0).Variance) Assert.Equal(0, typeParams(0).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(0).DeclaredAccessibility) Assert.Equal("U", typeParams(1).Name) Assert.Equal(VarianceKind.In, typeParams(1).Variance) Assert.Equal(1, typeParams(1).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(1).DeclaredAccessibility) Assert.Equal("V", typeParams(2).Name) Assert.Equal(VarianceKind.Out, typeParams(2).Variance) Assert.Equal(2, typeParams(2).Ordinal) Assert.Equal(Accessibility.NotApplicable, typeParams(2).DeclaredAccessibility) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(537199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537199")> <Fact> Public Sub UseTypeInNetModule() Dim mscorlibRef = TestMetadata.Net40.mscorlib Dim module1Ref = TestReferences.SymbolsTests.netModule.netModule1 Dim text = <literal> Class Test Dim a As Class1 = Nothing Public Sub New() End Sub End Class </literal>.Value Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.From(text), VisualBasicParseOptions.Default, "") Dim comp As VisualBasicCompilation = VisualBasicCompilation.Create("Test", {tree}, {mscorlibRef, module1Ref}) Dim globalNS = comp.SourceModule.GlobalNamespace Dim classTest = DirectCast(globalNS.GetTypeMembers("Test").First(), NamedTypeSymbol) Dim members = classTest.GetMembers() ' has to have mscorlib Dim varA = DirectCast(members(0), FieldSymbol) Assert.Equal(SymbolKind.Field, varA.Kind) Assert.Equal(TypeKind.Class, varA.Type.TypeKind) Assert.Equal(SymbolKind.NamedType, varA.Type.Kind) End Sub ' Date: IEEE 64bits (8 bytes) values <Fact> Public Sub PredefinedType01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Generic"> <file name="pd.vb"> Namespace NS Friend Module MyMod Dim dateField As Date = #8/13/2002 12:14 PM# Function DateFunc() As Date() Dim Obj As Object = #10/10/2001# Return Obj End Function Sub DateSub(ByVal Ary(,,) As Date) #If compErrorTest Then 'COMPILEERROR: BC30414, "New Date() {}" Ary = New Date() {} #End If End Sub Shared Sub New() End Sub End Module End Namespace </file> </compilation>) Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol) Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol) Dim members = modOfNS.GetMembers() Assert.Equal(4, members.Length) ' 3 members + implicit shared constructor Dim mem1 = DirectCast(members(0), FieldSymbol) Assert.Equal(modOfNS, mem1.ContainingSymbol) Assert.Equal(Accessibility.Private, mem1.DeclaredAccessibility) Assert.Equal(SymbolKind.Field, mem1.Kind) Assert.Equal(TypeKind.Structure, mem1.Type.TypeKind) Assert.Equal("Date", mem1.Type.ToDisplayString()) Assert.Equal("System.DateTime", mem1.Type.ToTestDisplayString()) Dim mem2 = DirectCast(members(1), MethodSymbol) Assert.Equal(modOfNS, mem2.ContainingSymbol) Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility) Assert.Equal(SymbolKind.Method, mem2.Kind) Assert.Equal(TypeKind.Array, mem2.ReturnType.TypeKind) Dim ary = DirectCast(mem2.ReturnType, ArrayTypeSymbol) Assert.Equal(1, ary.Rank) Assert.Equal("Date", ary.ElementType.ToDisplayString()) Assert.Equal("System.DateTime", ary.ElementType.ToTestDisplayString()) Dim mem3 = DirectCast(modOfNS.GetMembers("DateSub").Single(), MethodSymbol) Assert.Equal(modOfNS, mem3.ContainingSymbol) Assert.Equal(Accessibility.Public, mem3.DeclaredAccessibility) Assert.Equal(SymbolKind.Method, mem3.Kind) Assert.True(mem3.IsSub) Dim param = DirectCast(mem3.Parameters(0), ParameterSymbol) Assert.Equal(TypeKind.Array, param.Type.TypeKind) ary = DirectCast(param.Type, ArrayTypeSymbol) Assert.Equal(3, ary.Rank) Assert.Equal("Date", ary.ElementType.ToDisplayString()) Assert.Equal("System.DateTime", ary.ElementType.ToTestDisplayString()) End Sub <WorkItem(537461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537461")> <Fact> Public Sub SourceTypeUndefinedBaseType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="SourceTypeUndefinedBaseType"> <file name="undefinedbasetype.vb"> Class Class1 : Inherits Goo End Class </file> </compilation>) Dim baseType = compilation.GlobalNamespace.GetTypeMembers("Class1").Single().BaseType Assert.Equal("Goo", baseType.ToTestDisplayString()) Assert.Equal(SymbolKind.ErrorType, baseType.Kind) End Sub <WorkItem(537467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537467")> <Fact> Public Sub TopLevelPrivateTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Option Strict Off Option Explicit Off Imports VB6 = Microsoft.VisualBasic Namespace InterfaceErr005 'COMPILEERROR: BC31089, "PrivateUDT" Private Structure PrivateUDT Public x As Short End Structure 'COMPILEERROR: BC31089, "PrivateIntf" Private Interface PrivateIntf Function goo() End Interface 'COMPILEERROR: BC31047 Protected Class ProtectedClass End Class End Namespace </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("InterfaceErr005").First(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("PrivateUDT").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' type1 = DirectCast(ns.GetTypeMembers("PrivateIntf").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' type1 = DirectCast(ns.GetTypeMembers("ProtectedClass").Single(), NamedTypeSymbol) Assert.Equal(Accessibility.Friend, type1.DeclaredAccessibility) ' NOTE: for erroneous symbols we return 'best guess' CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31089: Types declared 'Private' must be inside another type. Private Structure PrivateUDT ~~~~~~~~~~ BC31089: Types declared 'Private' must be inside another type. Private Interface PrivateIntf ~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Class ProtectedClass ~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(527185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527185")> <Fact> Public Sub InheritTypeFromMetadata01() Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="b.vb"> Public Module m1 Public Class C1_1 Public Class goo End Class End Class End Module </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="Test1"> <file name="a.vb"> Imports System Imports System.Collections.Generic Namespace ShadowsGen203 ' from mscorlib Public Class MyAttribute Inherits Attribute End Class ' from another module Public Module M1 Public Class C1_3 Inherits C1_1 Private Shadows Class goo End Class End Class End Module End Namespace </file> </compilation>, {compRef1}) ' VisualBasicCompilation.Create("Test", CompilationOptions.Default, {SyntaxTree.ParseCompilationUnit(text1)}, {compRef1}) Dim ns = DirectCast(comp.GlobalNamespace.GetMembers("ShadowsGen203").Single(), NamespaceSymbol) Dim mod1 = DirectCast(ns.GetMembers("m1").Single(), NamedTypeSymbol) Dim type1 = DirectCast(mod1.GetTypeMembers("C1_3").Single(), NamedTypeSymbol) Assert.Equal("C1_1", type1.BaseType.Name) Dim type2 = DirectCast(ns.GetTypeMembers("MyAttribute").Single(), NamedTypeSymbol) Assert.Equal("Attribute", type2.BaseType.Name) End Sub <WorkItem(537753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537753")> <Fact> Public Sub ImplementTypeCrossComps() Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Test2"> <file name="comp.vb"> Imports System.Collections.Generic Namespace MT Public Interface IGoo(Of T) Sub M(ByVal t As T) End Interface End Namespace </file> </compilation>) Dim compRef1 = New VisualBasicCompilationReference(comp1) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="Test2"> <file name="comp2.vb"> Imports System.Collections.Generic Imports MT Namespace SS Public Class Goo Implements IGoo(Of String) Sub N(ByVal s As String) Implements IGoo(Of String).M End Sub End Class End Namespace </file> </compilation>, {compRef1}) Dim ns = DirectCast(comp.SourceModule.GlobalNamespace.GetMembers("SS").Single(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("Goo", 0).Single(), NamedTypeSymbol) ' Not impl ex Assert.Equal(1, type1.Interfaces.Length) Dim type2 = DirectCast(type1.Interfaces(0), NamedTypeSymbol) Assert.Equal(TypeKind.Interface, type2.TypeKind) Assert.Equal(1, type2.Arity) Assert.Equal(1, type2.TypeParameters.Length) Assert.Equal("MT.IGoo(Of System.String)", type2.ToTestDisplayString()) End Sub <WorkItem(537492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537492")> <Fact> Public Sub PartialClassImplInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Option Strict Off Option Explicit On Imports System.Collections.Generic Public Interface vbInt2(Of T) Sub Sub1(ByVal b1 As Byte, ByRef t2 As T) Function Fun1(Of Z)(ByVal p1 As T) As Z End Interface </file> <file name="b.vb"> Module Module1 Public Class vbPartialCls200a(Of P, Q) ' for test GenPartialCls200 Implements vbInt2(Of P) Public Function Fun1(Of X)(ByVal a As P) As X Implements vbInt2(Of P).Fun1 Return Nothing End Function End Class Partial Public Class vbPartialCls200a(Of P, Q) Implements vbInt2(Of P) Public Sub Sub1(ByVal p1 As Byte, ByRef p2 As P) Implements vbInt2(Of P).Sub1 End Sub End Class Sub Main() End Sub End Module </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim myMod = DirectCast(globalNS.GetMembers("Module1").First(), NamedTypeSymbol) Dim type1 = DirectCast(myMod.GetTypeMembers("vbPartialCls200a").Single(), NamedTypeSymbol) Assert.Equal(1, type1.Interfaces.Length) End Sub <Fact> Public Sub CyclesInStructureDeclarations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Module Module1 Structure stdUDT End Structure Structure nestedUDT Public xstdUDT As stdUDT Public xstdUDTarr() As stdUDT End Structure Public m_nx1var As nestedUDT Public m_nx2var As nestedUDT Sub Scen1() Dim x2var As stdUDT End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC42024: Unused local variable: 'x2var'. Dim x2var As stdUDT ~~~~~ </errors>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"> Module Module1 Structure OuterStruct Structure InnerStruct Public t As OuterStruct End Structure Public one As InnerStruct Public two As InnerStruct Sub Scen1() Dim three As OuterStruct End Sub End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'OuterStruct' cannot contain an instance of itself: 'Module1.OuterStruct' contains 'Module1.OuterStruct.InnerStruct' (variable 'one'). 'Module1.OuterStruct.InnerStruct' contains 'Module1.OuterStruct' (variable 't'). Public one As InnerStruct ~~~ BC42024: Unused local variable: 'three'. Dim three As OuterStruct ~~~~~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations2"> <file name="a.vb"> Structure st1(Of T) Dim x As T End Structure Structure st2 Dim x As st1(Of st2) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of st2)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations2_() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations2_"> <file name="a.vb"> Structure st2 Dim x As st1(Of st2) End Structure Structure st1(Of T) Dim x As T End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of st2)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations3"> <file name="a.vb"> Structure st1(Of T) Dim x As st2 End Structure Structure st2 Dim x As st1(Of st2) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st1' cannot contain an instance of itself: 'st1(Of T)' contains 'st2' (variable 'x'). 'st2' contains 'st1(Of st2)' (variable 'x'). Dim x As st2 ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations3_() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations3_"> <file name="a.vb"> Structure st2 Dim x As st1(Of st2) End Structure Structure st1(Of T) Dim x As st2 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'st2' cannot contain an instance of itself: 'st2' contains 'st1(Of st2)' (variable 'x'). 'st1(Of T)' contains 'st2' (variable 'x'). Dim x As st1(Of st2) ~ </errors>) End Sub <Fact> Public Sub CyclesInStructureDeclarations4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="CyclesInStructureDeclarations4"> <file name="a.vb"> Structure E End Structure Structure X(Of T) Public _t As T End Structure Structure Y Public xz As X(Of Z) End Structure Structure Z Public xe As X(Of E) Public xy As X(Of Y) End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'Y' cannot contain an instance of itself: 'Y' contains 'X(Of Z)' (variable 'xz'). 'X(Of Z)' contains 'Z' (variable '_t'). 'Z' contains 'X(Of Y)' (variable 'xy'). 'X(Of Y)' contains 'Y' (variable '_t'). Public xz As X(Of Z) ~~ </errors>) End Sub <Fact> Public Sub PortedFromCSharp_StructLayoutCycle01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Module Module1 Structure A Public F As A ' BC30294 Public F_ As A ' no additional error End Structure Structure B Public F As C ' BC30294 Public G As C ' no additional error, cycle is reported for B.F End Structure Structure C Public G As B ' no additional error, cycle is reported for B.F End Structure Structure D(Of T) Public F As D(Of D(Of Object)) ' BC30294 End Structure Structure E Public F As F(Of E) ' no error End Structure Class F(Of T) Public G As E ' no error End Class Structure G Public F As H(Of G) ' BC30294 End Structure Structure H(Of T) Public G As G ' no additional error, cycle is reported for B.F End Structure Structure J Public Shared j As J ' no error End Structure Structure K Public Shared l As L ' no error End Structure Structure L Public l As K ' no error End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'A' cannot contain an instance of itself: 'Module1.A' contains 'Module1.A' (variable 'F'). Public F As A ' BC30294 ~ BC30294: Structure 'B' cannot contain an instance of itself: 'Module1.B' contains 'Module1.C' (variable 'F'). 'Module1.C' contains 'Module1.B' (variable 'G'). Public F As C ' BC30294 ~ BC30294: Structure 'D' cannot contain an instance of itself: 'Module1.D(Of T)' contains 'Module1.D(Of Module1.D(Of Object))' (variable 'F'). Public F As D(Of D(Of Object)) ' BC30294 ~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.H(Of Module1.G)' (variable 'F'). 'Module1.H(Of T)' contains 'Module1.G' (variable 'G'). Public F As H(Of G) ' BC30294 ~ </errors>) End Sub <Fact> Public Sub PortedFromCSharp_StructLayoutCycle02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Module Module1 Structure A Public Property P1 As A ' BC30294 Public Property P2 As A ' no additional error End Structure Structure B Public Property C1 As C ' BC30294 Public Property C2 As C ' no additional error End Structure Structure C Public Property B1 As B ' no error, cycle is already reported Public Property B2 As B ' no additional error End Structure Structure D(Of T) Public Property P1 As D(Of D(Of Object)) ' BC30294 Public Property P2 As D(Of D(Of Object)) ' no additional error End Structure Structure E Public Property F1 As F(Of E) ' no error Public Property F2 As F(Of E) ' no error End Structure Class F(Of T) Public Property P1 As E ' no error Public Property P2 As E ' no error End Class Structure G Public Property H1 As H(Of G) ' BC30294 Public Property H2 As H(Of G) ' no additional error Public Property G1 As G ' BC30294 End Structure Structure H(Of T) Public Property G1 As G ' no error Public Property G2 As G ' no error End Structure Structure J Public Shared Property j As J ' no error End Structure Structure K Public Shared Property l As L ' no error End Structure Structure L Public Property l As K ' no error End Structure Structure M Public Property N1 As N ' no error Public Property N2 As N ' no error End Structure Structure N Public Property M1 As M ' no error Get Return Nothing End Get Set(value As M) End Set End Property Public Property M2 As M ' no error Get Return Nothing End Get Set(value As M) End Set End Property End Structure End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'A' cannot contain an instance of itself: 'Module1.A' contains 'Module1.A' (variable '_P1'). Public Property P1 As A ' BC30294 ~~ BC30294: Structure 'B' cannot contain an instance of itself: 'Module1.B' contains 'Module1.C' (variable '_C1'). 'Module1.C' contains 'Module1.B' (variable '_B1'). Public Property C1 As C ' BC30294 ~~ BC30294: Structure 'D' cannot contain an instance of itself: 'Module1.D(Of T)' contains 'Module1.D(Of Module1.D(Of Object))' (variable '_P1'). Public Property P1 As D(Of D(Of Object)) ' BC30294 ~~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.H(Of Module1.G)' (variable '_H1'). 'Module1.H(Of T)' contains 'Module1.G' (variable '_G1'). Public Property H1 As H(Of G) ' BC30294 ~~ BC30294: Structure 'G' cannot contain an instance of itself: 'Module1.G' contains 'Module1.G' (variable '_G1'). Public Property G1 As G ' BC30294 ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' ERROR Dim s2_ As S2 ' NO ERROR Dim s3 As S3 ' ERROR End Structure Structure S2 Dim s1 As S1 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' ERROR ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s3 As S3 ' ERROR ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' ERROR Dim s2_ As S2 ' NO ERROR Dim s3 As S3 ' NO ERROR End Structure Structure S2 Dim s1 As S1 End Structure Structure S3 Dim s2 As S2 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' ERROR ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' two errors Dim s2_ As S2 ' no errors End Structure Structure S2 Dim s1 As S1 Dim s3 As S3 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="PortedFromCSharp_StructLayoutCycle01"> <file name="a.vb"> Structure S1 Dim s2 As S2 ' two errors Dim s2_ As S2 ' no errors End Structure Structure S2 Dim s3 As S3 Dim s1 As S1 Dim s1_ As S1 End Structure Structure S3 Dim s1 As S1 End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ BC30294: Structure 'S1' cannot contain an instance of itself: 'S1' contains 'S2' (variable 's2'). 'S2' contains 'S3' (variable 's3'). 'S3' contains 'S1' (variable 's1'). Dim s2 As S2 ' two errors ~~ </errors>) End Sub <Fact> Public Sub MultiplyCyclesInStructure05() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MultiplyCyclesInStructure05_I"> <file name="a.vb"> Public Structure SI_1 End Structure Public Structure SI_2 Public s1 As SI_1 End Structure </file> </compilation>) CompilationUtils.AssertNoErrors(compilation1) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="MultiplyCyclesInStructure05_II"> <file name="a.vb"> Public Structure SII_3 Public s2 As SI_2 End Structure Public Structure SII_4 Public s3 As SII_3 End Structure </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="MultiplyCyclesInStructure05_I"> <file name="a.vb"> Public Structure SI_1 Public s4 As SII_4 End Structure Public Structure SI_2 Public s1 As SI_1 End Structure </file> </compilation>, {New VisualBasicCompilationReference(compilation2)}) CompilationUtils.AssertTheseDiagnostics(compilation3, <errors> BC30294: Structure 'SI_1' cannot contain an instance of itself: 'SI_1' contains 'SII_4' (variable 's4'). 'SII_4' contains 'SII_3' (variable 's3'). 'SII_3' contains 'SI_2' (variable 's2'). 'SI_2' contains 'SI_1' (variable 's1'). Public s4 As SII_4 ~~ </errors>) End Sub <Fact> Public Sub SynthesizedConstructorLocation() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Class Goo End Class </file> </compilation>) Dim typeGoo = compilation.SourceModule.GlobalNamespace.GetTypeMembers("Goo").Single() Dim instanceConstructor = typeGoo.InstanceConstructors.Single() AssertEx.Equal(typeGoo.Locations, instanceConstructor.Locations) End Sub <Fact> Public Sub UsingProtectedInStructureMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="UsingProtectedInStructureMethods"> <file name="a.vb"> Structure Goo Protected Overrides Sub Finalize() End Sub Protected Sub OtherMethod() End Sub End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Sub OtherMethod() ~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UsingMustOverrideInStructureMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UsingProtectedInStructureMethods"> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Structure S2 Public MustOverride Function Goo() As String End Function End Structure </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30435: Members in a Structure cannot be declared 'MustOverride'. Public MustOverride Function Goo() As String ~~~~~~~~~~~~ BC30430: 'End Function' must be preceded by a matching 'Function'. End Function ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub Bug4135() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4135"> <file name="a.vb"> Interface I1 Protected Interface I2 End Interface Protected Friend Interface I3 End Interface Protected delegate Sub D1() Protected Friend delegate Sub D2() Protected Class C1 End Class Protected Friend Class C2 End Class Protected Structure S1 End Structure Protected Friend Structure S2 End Structure Protected Enum E1 val End Enum Protected Friend Enum E2 val End Enum 'Protected F1 As Integer 'Protected Friend F2 As Integer Protected Sub Sub1() Protected Friend Sub Sub2() End Interface Structure S3 Protected Interface I4 End Interface Protected Friend Interface I5 End Interface Protected delegate Sub D3() Protected Friend delegate Sub D4() Protected Class C3 End Class Protected Friend Class C4 End Class Protected Structure S4 End Structure Protected Friend Structure S5 End Structure Protected Enum E3 val End Enum Protected Friend Enum E4 val End Enum Protected F3 As Integer Protected Friend F4 As Integer Protected Sub Sub3() End Sub Protected Friend Sub Sub4() End Sub End Structure Module M1 Protected Interface I8 End Interface Protected Friend Interface I9 End Interface Protected delegate Sub D7() Protected Friend delegate Sub D8() Protected Class C7 End Class Protected Friend Class C8 End Class Protected Structure S8 End Structure Protected Friend Structure S9 End Structure Protected Enum E5 val End Enum Protected Friend Enum E6 val End Enum Protected F5 As Integer Protected Friend F6 As Integer Protected Sub Sub7() End Sub Protected Friend Sub Sub8() End Sub End Module Protected Interface I11 End Interface Protected Structure S11 End Structure Protected Class C11 End Class Protected Enum E11 val End Enum Protected Module M11 End Module Protected Friend Interface I12 End Interface Protected Friend Structure S12 End Structure Protected Friend Class C12 End Class Protected Friend Enum E12 val End Enum Protected Friend Module M12 End Module Protected delegate Sub D11() Protected Friend delegate Sub D12() Class C4 Protected Interface I6 End Interface Protected Friend Interface I7 End Interface Protected delegate Sub D5() Protected Friend delegate Sub D6() Protected Class C5 End Class Protected Friend Class C6 End Class Protected Structure S6 End Structure Protected Friend Structure S7 End Structure Protected Enum E7 val End Enum Protected Friend Enum E8 val End Enum Protected F7 As Integer Protected Friend F8 As Integer Protected Sub Sub5() End Sub Protected Friend Sub Sub6() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31209: Interface in an interface cannot be declared 'Protected'. Protected Interface I2 ~~~~~~~~~ BC31209: Interface in an interface cannot be declared 'Protected Friend'. Protected Friend Interface I3 ~~~~~~~~~~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Protected'. Protected delegate Sub D1() ~~~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Protected Friend'. Protected Friend delegate Sub D2() ~~~~~~~~~~~~~~~~ BC31070: Class in an interface cannot be declared 'Protected'. Protected Class C1 ~~~~~~~~~ BC31070: Class in an interface cannot be declared 'Protected Friend'. Protected Friend Class C2 ~~~~~~~~~~~~~~~~ BC31071: Structure in an interface cannot be declared 'Protected'. Protected Structure S1 ~~~~~~~~~ BC31071: Structure in an interface cannot be declared 'Protected Friend'. Protected Friend Structure S2 ~~~~~~~~~~~~~~~~ BC31069: Enum in an interface cannot be declared 'Protected'. Protected Enum E1 ~~~~~~~~~ BC31069: Enum in an interface cannot be declared 'Protected Friend'. Protected Friend Enum E2 ~~~~~~~~~~~~~~~~ BC30270: 'Protected' is not valid on an interface method declaration. Protected Sub Sub1() ~~~~~~~~~ BC30270: 'Protected Friend' is not valid on an interface method declaration. Protected Friend Sub Sub2() ~~~~~~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Interface I4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Interface I5 ~~ BC31047: Protected types can only be declared inside of a class. Protected delegate Sub D3() ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend delegate Sub D4() ~~ BC31047: Protected types can only be declared inside of a class. Protected Class C3 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Class C4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Structure S4 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Structure S5 ~~ BC31047: Protected types can only be declared inside of a class. Protected Enum E3 ~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Enum E4 ~~ BC30435: Members in a Structure cannot be declared 'Protected'. Protected F3 As Integer ~~~~~~~~~ BC30435: Members in a Structure cannot be declared 'Protected Friend'. Protected Friend F4 As Integer ~~~~~~~~~~~~~~~~ BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Sub Sub3() ~~~~~~~~~ BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'. Protected Friend Sub Sub4() ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Interface I8 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Interface I9 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected delegate Sub D7() ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend delegate Sub D8() ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Class C7 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Class C8 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Structure S8 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Structure S9 ~~~~~~~~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected'. Protected Enum E5 ~~~~~~~~~ BC30735: Type in a Module cannot be declared 'Protected Friend'. Protected Friend Enum E6 ~~~~~~~~~~~~~~~~ BC30593: Variables in Modules cannot be declared 'Protected'. Protected F5 As Integer ~~~~~~~~~ BC30593: Variables in Modules cannot be declared 'Protected Friend'. Protected Friend F6 As Integer ~~~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Protected'. Protected Sub Sub7() ~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Protected Friend'. Protected Friend Sub Sub8() ~~~~~~~~~~~~~~~~ BC31047: Protected types can only be declared inside of a class. Protected Interface I11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Structure S11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Class C11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Enum E11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Module M11 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Interface I12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Structure S12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Class C12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Enum E12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend Module M12 ~~~ BC31047: Protected types can only be declared inside of a class. Protected delegate Sub D11() ~~~ BC31047: Protected types can only be declared inside of a class. Protected Friend delegate Sub D12() ~~~ </expected>) End Sub <Fact> Public Sub Bug4136() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Private Interface I2 End Interface Private delegate Sub D1() Private Class C1 End Class Private Structure S1 End Structure Private Enum E1 val End Enum 'Private F1 As Integer Private Sub Sub1() End Interface Private Interface I11 End Interface Private Structure S11 End Structure Private Class C11 End Class Private Enum E11 val End Enum Private Module M11 End Module Private delegate Sub D11() Structure S3 Private Interface I4 End Interface Private delegate Sub D3() Private Class C3 End Class Private Structure S4 End Structure Private Enum E3 val End Enum Private F3 As Integer Private Sub Sub3() End Sub End Structure Module M1 Private Interface I8 End Interface Private delegate Sub D7() Private Class C7 End Class Private Structure S8 End Structure Private Enum E5 val End Enum Private F5 As Integer Private Sub Sub7() End Sub End Module Class C4 Private Interface I6 End Interface Private delegate Sub D5() Private Class C5 End Class Private Structure S6 End Structure Private Enum E7 val End Enum Private F7 As Integer Private Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31209: Interface in an interface cannot be declared 'Private'. Private Interface I2 ~~~~~~~ BC31068: Delegate in an interface cannot be declared 'Private'. Private delegate Sub D1() ~~~~~~~ BC31070: Class in an interface cannot be declared 'Private'. Private Class C1 ~~~~~~~ BC31071: Structure in an interface cannot be declared 'Private'. Private Structure S1 ~~~~~~~ BC31069: Enum in an interface cannot be declared 'Private'. Private Enum E1 ~~~~~~~ BC30270: 'Private' is not valid on an interface method declaration. Private Sub Sub1() ~~~~~~~ BC31089: Types declared 'Private' must be inside another type. Private Interface I11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Structure S11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Class C11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Enum E11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private Module M11 ~~~ BC31089: Types declared 'Private' must be inside another type. Private delegate Sub D11() ~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Friend Interface I2 End Interface Friend delegate Sub D1() Friend Class C1 End Class Friend Structure S1 End Structure Friend Enum E1 val End Enum 'Friend F1 As Integer Friend Sub Sub1() End Interface Friend Interface I11 End Interface Friend Structure S11 End Structure Friend Class C11 End Class Friend Enum E11 val End Enum Friend Module M11 End Module Friend delegate Sub D11() Structure S3 Friend Interface I4 End Interface Friend delegate Sub D3() Friend Class C3 End Class Friend Structure S4 End Structure Friend Enum E3 val End Enum Friend F3 As Integer Friend Sub Sub3() End Sub End Structure Module M1 Friend Interface I8 End Interface Friend delegate Sub D7() Friend Class C7 End Class Friend Structure S8 End Structure Friend Enum E5 val End Enum Friend F5 As Integer Friend Sub Sub7() End Sub End Module Class C4 Friend Interface I6 End Interface Friend delegate Sub D5() Friend Class C5 End Class Friend Structure S6 End Structure Friend Enum E7 val End Enum Friend F7 As Integer Friend Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31068: Delegate in an interface cannot be declared 'Friend'. Friend delegate Sub D1() ~~~~~~ BC31070: Class in an interface cannot be declared 'Friend'. Friend Class C1 ~~~~~~ BC31071: Structure in an interface cannot be declared 'Friend'. Friend Structure S1 ~~~~~~ BC31069: Enum in an interface cannot be declared 'Friend'. Friend Enum E1 ~~~~~~ BC30270: 'Friend' is not valid on an interface method declaration. Friend Sub Sub1() ~~~~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4136"> <file name="a.vb"> Interface I1 Public Interface I2 End Interface Public delegate Sub D1() Public Class C1 End Class Public Structure S1 End Structure Public Enum E1 val End Enum 'Public F1 As Integer Public Sub Sub1() End Interface Public Interface I11 End Interface Public Structure S11 End Structure Public Class C11 End Class Public Enum E11 val End Enum Public Module M11 End Module Public delegate Sub D11() Structure S3 Public Interface I4 End Interface Public delegate Sub D3() Public Class C3 End Class Public Structure S4 End Structure Public Enum E3 val End Enum Public F3 As Integer Public Sub Sub3() End Sub End Structure Module M1 Public Interface I8 End Interface Public delegate Sub D7() Public Class C7 End Class Public Structure S8 End Structure Public Enum E5 val End Enum Public F5 As Integer Public Sub Sub7() End Sub End Module Class C4 Public Interface I6 End Interface Public delegate Sub D5() Public Class C5 End Class Public Structure S6 End Structure Public Enum E7 val End Enum Public F7 As Integer Public Sub Sub5() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31068: Delegate in an interface cannot be declared 'Public'. Public delegate Sub D1() ~~~~~~ BC31070: Class in an interface cannot be declared 'Public'. Public Class C1 ~~~~~~ BC31071: Structure in an interface cannot be declared 'Public'. Public Structure S1 ~~~~~~ BC31069: Enum in an interface cannot be declared 'Public'. Public Enum E1 ~~~~~~ BC30270: 'Public' is not valid on an interface method declaration. Public Sub Sub1() ~~~~~~ </expected>) End Sub ' Constructor initializers don't bind yet <WorkItem(7926, "DevDiv_Projects/Roslyn")> <WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")> <Fact> Public Sub StructDefaultConstructorInitializer() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="StructDefaultConstructorInitializer"> <file name="StructDefaultConstructorInitializer.vb"> Structure S Public _x As Integer Public Sub New(x As Integer) Me.New() ' Note: not allowed in Dev10 End Sub End Structure </file> </compilation>) compilation.VerifyDiagnostics() Dim structType = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("S") Dim constructors = structType.GetMembers(WellKnownMemberNames.InstanceConstructorName) Assert.Equal(2, constructors.Length) Dim sourceConstructor = CType(constructors.First(Function(c) Not c.IsImplicitlyDeclared), MethodSymbol) Dim synthesizedConstructor = CType(constructors.First(Function(c) c.IsImplicitlyDeclared), MethodSymbol) Assert.NotEqual(sourceConstructor, synthesizedConstructor) Assert.Equal(1, sourceConstructor.Parameters.Length) Assert.Equal(0, synthesizedConstructor.Parameters.Length) End Sub <Fact> Public Sub MetadataNameOfGenericTypes() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="MetadataName"> <file name="a.vb"> Class Gen1(Of T, U, V) End Class Class NonGen End Class </file> </compilation>) Dim globalNS = compilation.GlobalNamespace Dim gen1Class = DirectCast(globalNS.GetMembers("Gen1").First(), NamedTypeSymbol) Assert.Equal("Gen1", gen1Class.Name) Assert.Equal("Gen1`3", gen1Class.MetadataName) Dim nonGenClass = DirectCast(globalNS.GetMembers("NonGen").First(), NamedTypeSymbol) Assert.Equal("NonGen", nonGenClass.Name) Assert.Equal("NonGen", nonGenClass.MetadataName) Dim system = DirectCast(globalNS.GetMembers("System").First(), NamespaceSymbol) Dim equatable = DirectCast(system.GetMembers("IEquatable").First(), NamedTypeSymbol) Assert.Equal("IEquatable", equatable.Name) Assert.Equal("IEquatable`1", equatable.MetadataName) End Sub <Fact()> Public Sub TypeNameSpelling1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Class Aa End Class Public Partial Class AA End Class </file> <file name="b.vb"> Public Partial Class aa End Class </file> </compilation>) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("aa")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("Aa")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("AA")(0).Name) Assert.Equal("Aa", compilation.GlobalNamespace.GetTypeMembers("aA")(0).Name) End Sub <Fact()> Public Sub TypeNameSpelling2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="b.vb"> Public Partial Class aa End Class </file> <file name="a.vb"> Public Class Aa End Class Public Partial Class AA End Class </file> </compilation>) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("aa")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("Aa")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("AA")(0).Name) Assert.Equal("aa", compilation.GlobalNamespace.GetTypeMembers("aA")(0).Name) End Sub <Fact()> Public Sub StructureInstanceConstructors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="b.vb"> Structure S1 Sub new () end sub End Structure Structure S2 Sub new (optional i as integer = 1) end sub End Structure </file> </compilation>) Dim s1 = compilation.GlobalNamespace.GetTypeMembers("s1")(0) Assert.Equal(1, s1.InstanceConstructors.Length) Dim s2 = compilation.GlobalNamespace.GetTypeMembers("s2")(0) Assert.Equal(2, s2.InstanceConstructors.Length) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_NewInStruct, "new").WithLocation(2, 9) ) End Sub <Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")> Public Sub ErrorTypeTest01() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="Err"> <file name="b.vb"> Sub TopLevelMethod() End Sub </file> </compilation>) Dim symbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers().LastOrDefault(), NamedTypeSymbol) Assert.Equal("<invalid-global-code>", symbol.Name) Assert.False(symbol.IsErrorType(), "ErrorType") Assert.True(symbol.IsImplicitClass, "ImplicitClass") End Sub <Fact> Public Sub NameCollisionWithAddedModule_01() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ </expected>) CompileAndVerify(compilation) End Sub <Fact> Public Sub NameCollisionWithAddedModule_02() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Public Class C1 End Class Public Class c2 End Class End Namespace Namespace ns1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ BC37210: Type 'C3' conflicts with public type defined in added module 'module.netmodule'. Friend Class C3 ~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_03() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace ns2 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation) End Sub <Fact> Public Sub NameCollisionWithAddedModule_04() Dim source1 = <compilation name="module"> <file name="a.vb"> Namespace NS1 Public Class c1 End Class End Namespace Namespace ns1 Public Class c2 End Class Public Class C3(Of T) End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference(expectedWarnings:= { Diagnostic(ERRID.WRN_NamespaceCaseMismatch3, "ns1").WithArguments("ns1", "NS1", "a.vb") }) Dim source2 = <compilation> <file name="a.vb"> Namespace NS1 Friend Class C1 End Class Friend Class c2 End Class End Namespace Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'a.vb'. Namespace ns1 ~~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_05() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace ns1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Friend Class C1 End Class Friend Class c2 End Class Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ BC37210: Type 'C3' conflicts with public type defined in added module 'module.netmodule'. Friend Class C3 ~~ BC37210: Type 'c4' conflicts with public type defined in added module 'module.netmodule'. Friend Class c4 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_06() Dim source1 = <compilation name="module"> <file name="a.vb"> Public Class C1 End Class Public Class c2 End Class Namespace NS1 Public Class C3 End Class Public Class c4 End Class End Namespace </file> </compilation> Dim modComp = CreateCompilationWithMscorlib40(source1, OutputKind.NetModule) Dim modRef = modComp.EmitToImageReference() Dim source2 = <compilation> <file name="a.vb"> Friend Class C1 End Class Friend Class c2 End Class Namespace ns1 Friend Class C3 End Class Friend Class c4 End Class End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source2, {modRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected> BC37210: Type 'C1' conflicts with public type defined in added module 'module.netmodule'. Friend Class C1 ~~ BC37210: Type 'c2' conflicts with public type defined in added module 'module.netmodule'. Friend Class c2 ~~ </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_07() Dim ilSource = <![CDATA[ .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(ilSource.Value, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim source = <compilation> <file name="a.vb"> Interface ITest20 End Interface </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {moduleRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37211: Type 'ITest20(Of T)' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_08() Dim ilSource = <![CDATA[ .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } ]]> Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(ilSource.Value, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim mod2 = <compilation name="mod_1_2"> <file name="a.vb"> namespace ns public interface c1 end interface public interface c3 end interface end namespace public interface c2 end interface public interface c4 end interface namespace ns1 public interface c5 end interface end namespace </file> </compilation> Dim source = <compilation> <file name="a.vb"> </file> </compilation> Dim moduleRef2 = CreateCompilationWithMscorlib40(mod2, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {moduleRef1, moduleRef2}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37212: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2(Of T)' exported from module 'mod_1_1.netmodule'. BC37212: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1(Of T)' exported from module 'mod_1_1.netmodule'. </expected>) End Sub <Fact> Public Sub NameCollisionWithAddedModule_09() Dim forwardedTypesSource = <compilation name=""> <file name="a.vb"> Public Class CF1 End Class namespace ns Public Class CF2 End Class End Namespace public class CF3(Of T) End Class </file> </compilation> forwardedTypesSource.@name = "ForwardedTypes1" Dim forwardedTypes1 = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseDll) Dim forwardedTypes1Ref = New VisualBasicCompilationReference(forwardedTypes1) forwardedTypesSource.@name = "ForwardedTypes2" Dim forwardedTypes2 = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseDll) Dim forwardedTypes2Ref = New VisualBasicCompilationReference(forwardedTypes2) forwardedTypesSource.@name = "forwardedTypesMod" Dim forwardedTypesModRef = CreateCompilationWithMscorlib40(forwardedTypesSource, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim modSource = <![CDATA[ .assembly extern <<TypesForWardedToAssembly>> { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF1 { .assembly extern <<TypesForWardedToAssembly>> } .class extern forwarder ns.CF2 { .assembly extern <<TypesForWardedToAssembly>> } .module <<ModuleName>>.netmodule // MVID: {987C2448-14BC-48E8-BE36-D24E14D49864} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D90000 ]]>.Value Dim ilBytes As ImmutableArray(Of Byte) = Nothing Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module1_FT1").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes1"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module1_FT1_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module2_FT1").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes1"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module2_FT1_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Using reference = IlasmUtilities.CreateTempAssembly(modSource.Replace("<<ModuleName>>", "module3_FT2").Replace("<<TypesForWardedToAssembly>>", "ForwardedTypes2"), prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module3_FT2_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() Dim module4_FT1_source = <![CDATA[ .assembly extern ForwardedTypes1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class extern forwarder CF3`1 { .assembly extern ForwardedTypes1 } .module module4_FT1.netmodule // MVID: {5C652C9E-35F2-4D1D-B2A4-68683237D8F1} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x01100000 ]]>.Value Using reference = IlasmUtilities.CreateTempAssembly(module4_FT1_source, prependDefaultHeader:=False) ilBytes = ReadFromFile(reference.Path) End Using Dim module4_Ref = ModuleMetadata.CreateFromImage(ilBytes).GetReference() forwardedTypesSource.@name = "consumer" Dim compilation = CreateCompilationWithMscorlib40AndReferences(forwardedTypesSource, { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37217: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. BC37217: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. </expected>) Dim emptySource = <compilation> <file name="a.vb"> </file> </compilation> compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37218: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. BC37218: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37218: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. BC37218: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll) ' Exported types in .NET modules cause PEVerify to fail. CompileAndVerify(compilation, verify:=Verification.Fails).VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences(emptySource, { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37219: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. BC37219: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. </expected>) End Sub <Fact> Public Sub PartialModules() Dim verifier = CompileAndVerify( <compilation name="PartialModules"> <file name="Program.vb"> Imports System.Console Module Program Sub Main() Write(Syntax.SyntaxFacts.IsExpressionKind(0)) Write(Syntax.SyntaxFacts.IsStatementKind(0)) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(GetType(MyTestAttribute1), False).Length) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(GetType(MyTestAttribute2), False).Length) Write(GetType(Syntax.SyntaxFacts).GetCustomAttributes(False).Length) End Sub End Module Public Class MyTestAttribute1 Inherits System.Attribute End Class Public Class MyTestAttribute2 Inherits System.Attribute End Class </file> <file name="SyntaxFacts.vb"><![CDATA[ Namespace Syntax <MyTestAttribute1> Module SyntaxFacts Public Function IsExpressionKind(kind As Integer) As Boolean Return False End Function End Module End Namespace ]]></file> <file name="GeneratedSyntaxFacts.vb"><![CDATA[ Namespace Syntax <MyTestAttribute2> Partial Module SyntaxFacts Public Function IsStatementKind(kind As Integer) As Boolean Return True End Function End Module End Namespace ]]></file> </compilation>, expectedOutput:="FalseTrue113") End Sub <Fact> Public Sub PartialInterfaces() Dim verifier = CompileAndVerify( <compilation name="PartialModules"> <file name="Program.vb"> Imports System Imports System.Console Module Program Sub Main() Dim customer As ICustomer = New Customer() With { .Name = "Unnamed" } ValidateCustomer(customer) End Sub Sub ValidateCustomer(customer As ICustomer) Write(customer.Id = Guid.Empty) Write(customer.NameHash = customer.Name.GetHashCode()) Write(GetType(ICustomer).GetCustomAttributes(GetType(MyTestAttribute1), False).Length) Write(GetType(ICustomer).GetCustomAttributes(GetType(MyTestAttribute2), False).Length) Write(GetType(ICustomer).GetCustomAttributes(False).Length) End Sub End Module Public Class MyTestAttribute1 Inherits System.Attribute End Class Public Class MyTestAttribute2 Inherits System.Attribute End Class </file> <file name="ViewModels.vb"><![CDATA[ Imports System ' We only need this property for Silverlight. We omit this file when building for WPF. <MyTestAttribute1> Partial Interface ICustomer ReadOnly Property NameHash As Integer End Interface Partial Class Customer Private ReadOnly Property NameHash As Integer Implements ICustomer.NameHash Get Return Name.GetHashCode() End Get End Property End Class ]]></file> <file name="GeneratedViewModels.vb"><![CDATA[ Imports System <MyTestAttribute2> Partial Interface ICustomer ReadOnly Property Id As Guid Property Name As String End Interface Partial Class Customer Implements ICustomer Private ReadOnly _Id As Guid Public ReadOnly Property Id As Guid Implements ICustomer.Id Get return _Id End Get End Property Public Property Name As String Implements ICustomer.Name Public Sub New() Me.New(Guid.NewGuid()) End Sub Public Sub New(id As Guid) _Id = id End Sub End Class ]]></file> </compilation>, expectedOutput:="FalseTrue112") End Sub <Fact, WorkItem(8400, "https://github.com/dotnet/roslyn/issues/8400")> Public Sub WrongModifier() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C"> <file name="a.vb"><![CDATA[ public class AAA : IBBB { public static AAA MMM(Stream xamlStream) { // Note: create custom module catalog ]]></file> </compilation>) compilation.AssertTheseDiagnostics( <expected> BC30481: 'Class' statement must end with a matching 'End Class'. public class AAA : IBBB ~~~~~~~~~~~~~~~~ BC30188: Declaration expected. public class AAA : IBBB ~~~~ BC30035: Syntax error. { ~ BC30235: 'static' is not valid on a member variable declaration. public static AAA MMM(Stream xamlStream) ~~~~~~ BC30205: End of statement expected. public static AAA MMM(Stream xamlStream) ~~~ BC30035: Syntax error. { ~ BC30035: Syntax error. // Note: create custom module catalog ~ BC30188: Declaration expected. // Note: create custom module catalog ~~~~~~ BC31140: 'Custom' modifier can only be used immediately before an 'Event' declaration. // Note: create custom module catalog ~~~~~~ BC30617: 'Module' statements can occur only at file or namespace level. // Note: create custom module catalog ~~~~~~~~~~~~~~~~~~~~~ BC30625: 'Module' statement must end with a matching 'End Module'. // Note: create custom module catalog ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_01() Dim sources = <compilation> <file><![CDATA[ Imports System.Runtime.InteropServices <typeidentifier> Public Interface I1 End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") i1.GetAttributes() Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports System.Runtime.InteropServices <TypeIdentifierAttribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_03() Dim sources = <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifier <alias1> Public Interface I1 End Interface ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'System.Runtime.InteropServices.TypeIdentifier' 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 alias1 = System.Runtime.InteropServices.TypeIdentifier ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. <alias1> ~~~~~~ ]]></expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40(sources) i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") i1.GetAttributes() Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifier <alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'System.Runtime.InteropServices.TypeIdentifier' 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 alias1 = System.Runtime.InteropServices.TypeIdentifier ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'alias1Attribute' is not defined. <alias1Attribute> ~~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_05() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.typeIdentifierattribute <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_06() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_07() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_08() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1attributeAttribute = System.Runtime.InteropServices.typeIdentifierattribute <Alias1Attribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_09() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias2 = alias1 <alias2> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC40056: Namespace or type specified in the Imports 'alias1' 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 alias2 = alias1 ~~~~~~ BC30182: Type expected. <alias2> ~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <alias1> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias2 = I1 <alias1> Public Interface I1 End Interface ]]></file> </compilation>, options:=TestOptions.DebugDll.WithGlobalImports(GlobalImport.Parse("alias1=System.Runtime.InteropServices.typeIdentifierattribute"))) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_12() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute Imports System.Runtime.CompilerServices <alias1> Public Partial Interface I1 End Interface <CompilerGenerated> Public Partial Interface I2 End Interface ]]></file> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.ComImportAttribute <alias1> Public Partial Interface I1 End Interface <alias1> Public Partial Interface I2 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Dim i2 = compilation.SourceAssembly.GetTypeByMetadataName("I2") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) Assert.False(i2.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_13() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.ComImportAttribute <alias1> Public Partial Interface I1 End Interface <alias1> Public Partial Interface I2 End Interface ]]></file> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute Imports System.Runtime.CompilerServices <alias1> Public Partial Interface I1 End Interface <CompilerGenerated> Public Partial Interface I2 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Dim i2 = compilation.SourceAssembly.GetTypeByMetadataName("I2") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) Assert.False(i2.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_14() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.False(i1.IsExplicitDefinitionOfNoPiaLocalType) compilation.AssertTheseDeclarationDiagnostics( <expected><![CDATA[ BC30182: Type expected. <alias1> ~~~~~~ ]]></expected>) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_15() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <System.Runtime.InteropServices.TypeIdentifier> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_16() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ <System.Runtime.InteropServices.TypeIdentifierAttribute> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <Fact> Public Sub IsExplicitDefinitionOfNoPiaLocalType_17() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file><![CDATA[ Imports alias1 = System.Runtime.InteropServices.TypeIdentifierAttribute <alias1> Public Interface I1 End Interface ]]></file> </compilation>) Dim i1 = compilation.SourceAssembly.GetTypeByMetadataName("I1") Assert.True(i1.IsExplicitDefinitionOfNoPiaLocalType) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_ContainingType_GenericNestedType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_ContainingType_GenericNestedType"> <file name="a.vb"> Public Class C(Of T) Public Interface I(Of U) End Interface End Class </file> </compilation>) AssertNoDeclarationDiagnostics(compilation) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim iDefinition = compilation.GetMember(Of NamedTypeSymbol)("C.I") Assert.Equal("C(Of T).I(Of U)", iDefinition.ToTestDisplayString()) Assert.True(iDefinition.IsDefinition) ' Construct from iDefinition with modified U from iDefinition Dim modifiedU = ImmutableArray.Create(New TypeWithModifiers(iDefinition.TypeParameters.Single(), modifiers)) Dim i1 = iDefinition.Construct(TypeSubstitution.Create(iDefinition, iDefinition.TypeParameters, modifiedU)) Assert.Equal("C(Of T).I(Of U modopt(System.Object))", i1.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i1) Dim cDefinition = iDefinition.ContainingType Assert.Equal("C(Of T)", cDefinition.ToTestDisplayString()) Assert.True(cDefinition.IsDefinition) ' Construct from cDefinition with modified T from cDefinition Dim modifiedT = ImmutableArray.Create(New TypeWithModifiers(cDefinition.TypeParameters.Single(), modifiers)) Dim c2 = cDefinition.Construct(TypeSubstitution.Create(cDefinition, cDefinition.TypeParameters, modifiedT)) Dim i2 = c2.GetTypeMember("I") Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i2.ToTestDisplayString()) Assert.Same(i2.OriginalDefinition, iDefinition) AssertHashCodesMatch(iDefinition, i2) ' Construct from i2 with U from iDefinition Dim i2a = i2.Construct(iDefinition.TypeParameters.Single()) Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i2a.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i2a) ' Construct from i2 (reconstructed) with modified U from iDefinition Dim i2b = iDefinition.Construct(TypeSubstitution.Create(iDefinition, ImmutableArray.Create(cDefinition.TypeParameters.Single(), iDefinition.TypeParameters.Single()), ImmutableArray.Create(modifiedT.Single(), modifiedU.Single()))) Assert.Equal("C(Of T modopt(System.Object)).I(Of U modopt(System.Object))", i2b.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i2b) ' Construct from cDefinition with modified T from cDefinition Dim c4 = cDefinition.Construct(TypeSubstitution.Create(cDefinition, cDefinition.TypeParameters, modifiedT)) Assert.Equal("C(Of T modopt(System.Object))", c4.ToTestDisplayString()) Assert.False(c4.IsDefinition) AssertHashCodesMatch(cDefinition, c4) Dim i4 = c4.GetTypeMember("I") Assert.Equal("C(Of T modopt(System.Object)).I(Of U)", i4.ToTestDisplayString()) Assert.Same(i4.OriginalDefinition, iDefinition) AssertHashCodesMatch(iDefinition, i4) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_ContainingType_GenericNestedType_Nested() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_ContainingType_GenericNestedType"> <file name="a.vb"> Public Class C(Of T) Public Class C2(Of U) Public Interface I(Of V) End Interface End Class End Class </file> </compilation>) AssertNoDeclarationDiagnostics(compilation) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim iDefinition = compilation.GetMember(Of NamedTypeSymbol)("C.C2.I") Assert.Equal("C(Of T).C2(Of U).I(Of V)", iDefinition.ToTestDisplayString()) Assert.True(iDefinition.IsDefinition) Dim c2Definition = iDefinition.ContainingType Dim cDefinition = c2Definition.ContainingType Dim modifiedT = New TypeWithModifiers(cDefinition.TypeParameters.Single(), modifiers) Dim modifiedU = New TypeWithModifiers(c2Definition.TypeParameters.Single(), modifiers) Dim modifiedV = New TypeWithModifiers(iDefinition.TypeParameters.Single(), modifiers) Dim i = iDefinition.Construct(TypeSubstitution.Create(iDefinition, ImmutableArray.Create(cDefinition.TypeParameters.Single(), c2Definition.TypeParameters.Single(), iDefinition.TypeParameters.Single()), ImmutableArray.Create(modifiedT, modifiedU, modifiedV))) Assert.Equal("C(Of T modopt(System.Object)).C2(Of U modopt(System.Object)).I(Of V modopt(System.Object))", i.ToTestDisplayString()) AssertHashCodesMatch(iDefinition, i) End Sub <WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")> <Fact> Public Sub TypeSymbolGetHashCode_SubstitutedErrorType() Dim missing = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class C(Of T) Public Class D(Of U) End Class End Class </file> </compilation>) AssertNoDeclarationDiagnostics(missing) Dim reference = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class Reference(Of T, U) Inherits C(Of T).D(Of U) End Class </file> </compilation>, references:={missing.EmitToImageReference()}) AssertNoDeclarationDiagnostics(reference) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TypeSymbolGetHashCode_SubstitutedErrorType"> <file name="a.vb"> Public Class Program(Of V, W) Inherits Reference(Of V, W) End Class </file> </compilation>, references:={reference.EmitToImageReference()}) compilation.AssertTheseDiagnostics(<errors><![CDATA[ BC31091: Import of type 'C(Of ).D(Of )' from assembly or module 'TypeSymbolGetHashCode_SubstitutedErrorType.dll' failed. Public Class Program(Of V, W) ~~~~~~~ BC31091: Import of type 'C(Of ).D(Of )' from assembly or module 'TypeSymbolGetHashCode_SubstitutedErrorType.dll' failed. Inherits Reference(Of V, W) ~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim modifiers = ImmutableArray.Create(VisualBasicCustomModifier.CreateOptional(compilation.GetSpecialType(SpecialType.System_Object))) Dim programType = compilation.GlobalNamespace.GetTypeMember("Program") Dim errorType = programType.BaseType.BaseType Dim definition = errorType.OriginalDefinition Assert.Equal("Microsoft.CodeAnalysis.VisualBasic.Symbols.SubstitutedErrorType", errorType.GetType().ToString()) Assert.Equal("C(Of )[missing].D(Of )[missing]", definition.ToTestDisplayString()) Assert.True(definition.IsDefinition) ' Construct from definition with modified U from definition Dim modifiedU = ImmutableArray.Create(New TypeWithModifiers(definition.TypeParameters.Single(), modifiers)) Dim t1 = definition.Construct(TypeSubstitution.Create(definition, definition.TypeParameters, modifiedU)) Assert.Equal("C(Of )[missing].D(Of modopt(System.Object))[missing]", t1.ToTestDisplayString()) AssertHashCodesMatch(definition, t1) End Sub Private Shared Sub AssertHashCodesMatch(c As NamedTypeSymbol, c2 As NamedTypeSymbol) Assert.False(c.IsSameType(c2, TypeCompareKind.ConsiderEverything)) Assert.True(c.IsSameType(c2, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.False(c2.IsSameType(c, TypeCompareKind.ConsiderEverything)) Assert.True(c2.IsSameType(c, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.Equal(c2.GetHashCode(), c.GetHashCode()) If c.Arity <> 0 Then Dim ctp = c.TypeParameters(0) Dim ctp2 = c2.TypeParameters(0) If ctp IsNot ctp2 Then Assert.False(ctp.IsSameType(ctp2, TypeCompareKind.ConsiderEverything)) Assert.True(ctp.IsSameType(ctp2, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.False(ctp2.IsSameType(ctp, TypeCompareKind.ConsiderEverything)) Assert.True(ctp2.IsSameType(ctp, (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds Or TypeCompareKind.IgnoreTupleNames))) Assert.Equal(ctp2.GetHashCode(), ctp.GetHashCode()) End If End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./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 '{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
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/BoundTree/BoundUserDefinedShortCircuitingOperator.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 Partial Friend Class BoundUserDefinedShortCircuitingOperator #If DEBUG Then Private Sub Validate() Debug.Assert(LeftTest Is Nothing OrElse LeftTest.Type.IsBooleanType()) Debug.Assert((LeftOperand Is Nothing) = (LeftOperandPlaceholder Is Nothing)) Debug.Assert(LeftOperand IsNot Nothing OrElse HasErrors) If LeftTest IsNot Nothing Then Debug.Assert(LeftTest.Kind = BoundKind.UserDefinedUnaryOperator OrElse (LeftTest.Kind = BoundKind.NullableIsTrueOperator AndAlso DirectCast(LeftTest, BoundNullableIsTrueOperator).Operand.Kind = BoundKind.UserDefinedUnaryOperator)) End If End Sub #End If 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 Partial Friend Class BoundUserDefinedShortCircuitingOperator #If DEBUG Then Private Sub Validate() Debug.Assert(LeftTest Is Nothing OrElse LeftTest.Type.IsBooleanType()) Debug.Assert((LeftOperand Is Nothing) = (LeftOperandPlaceholder Is Nothing)) Debug.Assert(LeftOperand IsNot Nothing OrElse HasErrors) If LeftTest IsNot Nothing Then Debug.Assert(LeftTest.Kind = BoundKind.UserDefinedUnaryOperator OrElse (LeftTest.Kind = BoundKind.NullableIsTrueOperator AndAlso DirectCast(LeftTest, BoundNullableIsTrueOperator).Operand.Kind = BoundKind.UserDefinedUnaryOperator)) End If End Sub #End If End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Semantics/TypeInference/TypeArgumentInference.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.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The only public entry point is the Infer method. ''' </summary> Friend MustInherit Class TypeArgumentInference Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, Optional inferTheseTypeParameters As BitVector = Nothing ) As Boolean Debug.Assert(candidate Is candidate.ConstructedFrom) Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons, inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch, useSiteInfo, diagnostic, inferTheseTypeParameters) End Function ' No-one should create instances of this class. Private Sub New() End Sub Public Enum InferenceLevel As Byte None = 0 ' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate ' or no delegate in the overload resolution hence both have value 0 such that overload resolution ' will not prefer a non inferred method over an inferred one. Whidbey = 0 Orcas = 1 ' Keep invalid the biggest number Invalid = 2 End Enum ' MatchGenericArgumentParameter: ' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T). ' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm). ' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg). ' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical. ' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T). Public Enum MatchGenericArgumentToParameter MatchBaseOfGenericArgumentToParameter MatchArgumentToBaseOfGenericParameter MatchGenericArgumentToParameterExactly End Enum Private Enum InferenceNodeType As Byte ArgumentNode TypeParameterNode End Enum Private MustInherit Class InferenceNode Inherits GraphNode(Of InferenceNode) Public ReadOnly NodeType As InferenceNodeType Public InferenceComplete As Boolean Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType) MyBase.New(graph) Me.NodeType = nodeType End Sub Public Shadows ReadOnly Property Graph As InferenceGraph Get Return DirectCast(MyBase.Graph, InferenceGraph) End Get End Property ''' <summary> ''' Returns True if the inference algorithm should be restarted. ''' </summary> Public MustOverride Function InferTypeAndPropagateHints() As Boolean <Conditional("DEBUG")> Public Sub VerifyIncomingInferenceComplete( ByVal nodeType As InferenceNodeType ) If Not Graph.SomeInferenceHasFailed() Then For Each current As InferenceNode In IncomingEdges Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.") Debug.Assert(current.InferenceComplete, "Should have inferred type already") Next End If End Sub End Class Private Class DominantTypeDataTypeInference Inherits DominantTypeData ' Fields needed for error reporting Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention? Public Parameter As ParameterSymbol Public InferredFromObject As Boolean Public TypeParameter As TypeParameterSymbol Public ArgumentLocation As SyntaxNode End Class Private Class TypeParameterNode Inherits InferenceNode Public ReadOnly DeclaredTypeParam As TypeParameterSymbol Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference) Private _inferredType As TypeSymbol Private _inferredFromLocation As SyntaxNodeOrToken Private _inferredTypeByAssumption As Boolean ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' This one, cannot be changed once set. We need to clean this up later. Private _candidateInferredType As TypeSymbol Private _parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol) MyBase.New(graph, InferenceNodeType.TypeParameterNode) DeclaredTypeParam = typeParameter InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)() End Sub Public ReadOnly Property InferredType As TypeSymbol Get Return _inferredType End Get End Property Public ReadOnly Property CandidateInferredType As TypeSymbol Get Return _candidateInferredType End Get End Property Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken Get Return _inferredFromLocation End Get End Property Public ReadOnly Property InferredTypeByAssumption As Boolean Get Return _inferredTypeByAssumption End Get End Property Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean) ' Make sure ArrayLiteralTypeSymbol does not leak out Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol) If arrayLiteralType IsNot Nothing Then Dim arrayLiteral = arrayLiteralType.ArrayLiteral Dim arrayType = arrayLiteral.InferredType If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso arrayType.ElementType.SpecialType = SpecialType.System_Object Then ' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error ' when option strict is on and the array type is object() and there wasn't a dominant type. However, ' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type ' to suppress the error. inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly) Else inferredType = arrayLiteral.InferredType End If End If Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol)) _inferredType = inferredType _inferredFromLocation = inferredFromLocation _inferredTypeByAssumption = inferredTypeByAssumption ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' We need to clean this up. If _candidateInferredType Is Nothing Then _candidateInferredType = inferredType End If End Sub Public ReadOnly Property Parameter As ParameterSymbol Get Return _parameter End Get End Property Public Sub SetParameter(parameter As ParameterSymbol) Debug.Assert(_parameter Is Nothing) _parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean Dim numberOfIncomingEdges As Integer = IncomingEdges.Count Dim restartAlgorithm As Boolean = False Dim argumentLocation As SyntaxNode Dim numberOfIncomingWithNothing As Integer = 0 If numberOfIncomingEdges > 0 Then argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax Else argumentLocation = Nothing End If Dim numberOfAssertions As Integer = 0 Dim incomingFromObject As Boolean = False Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.") Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode) If currentNamedNode.Expression.Type IsNot Nothing AndAlso currentNamedNode.Expression.Type.IsObjectType() Then incomingFromObject = True End If If Not currentNamedNode.InferenceComplete Then Graph.RemoveEdge(currentNamedNode, Me) restartAlgorithm = True numberOfAssertions += 1 Else ' We should not infer from a Nothing literal. If currentNamedNode.Expression.IsStrictNothingLiteral() Then numberOfIncomingWithNothing += 1 End If End If Next If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then ' !! Inference has failed: All incoming type hints, were based on 'Nothing' Graph.MarkInferenceFailure() Graph.ReportNotFailedInferenceDueToObject() End If Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count() If numberOfTypeHints = 0 Then If numberOfAssertions = numberOfIncomingEdges Then Graph.MarkInferenceLevel(InferenceLevel.Orcas) Else ' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict. RegisterInferredType(Nothing, Nothing, False) Graph.MarkInferenceFailure() If Not incomingFromObject Then Graph.ReportNotFailedInferenceDueToObject() End If End If ElseIf numberOfTypeHints = 1 Then Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0) If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then argumentLocation = typeData.ArgumentLocation End If RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption) Else ' Run the whidbey algorithm to see if we are smarter now. Dim firstInferredType As TypeSymbol = Nothing Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList() For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData If firstInferredType Is Nothing Then firstInferredType = currentTypeInfo.ResultType ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then ' Whidbey failed hard here, in Orcas we added dominant type information. Graph.MarkInferenceLevel(InferenceLevel.Orcas) End If Next Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance() Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo) If dominantTypeDataList.Count = 1 Then ' //consider: scottwis ' // This seems dangerous to me, that we ' // remove error reasons here. ' // Instead of clearing these, what we should be doing is ' // asserting that they are not set. ' // If for some reason they get set, but ' // we enter this path, then we have a bug. ' // This code is just masking any such bugs. errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest)) Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0) RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption) ' // Also update the location of the argument for constraint error reporting later on. Else If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then ' !! Inference has failed. Dominant type algorithm found ambiguous types. Graph.ReportAmbiguousInferenceError(dominantTypeDataList) Else ' //consider: scottwis ' // This code appears to be operating under the assumption that if the error reason is not due to an ' // ambiguity then it must be because there was no best match. ' // We should be asserting here to verify that assertion. ' !! Inference has failed. Dominant type algorithm could not find a dominant type. Graph.ReportIncompatibleInferenceError(allTypeData) End If RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False) Graph.MarkInferenceFailure() End If Graph.RegisterErrorReasons(errorReasons) dominantTypeDataList.Free() End If InferenceComplete = True Return restartAlgorithm End Function Public Sub AddTypeHint( type As TypeSymbol, typeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal") ' Don't add error types to the type argument inference collection. If type.IsErrorType Then Return End If Dim foundInList As Boolean = False ' Do not merge array literals with other expressions If TypeOf type IsNot ArrayLiteralTypeSymbol Then For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList() ' Do not merge array literals with other expressions If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type) competitor.InferenceRestrictions = Conversions.CombineConversionRequirements( competitor.InferenceRestrictions, inferenceRestrictions) competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.") foundInList = True ' TODO: Should we simply exit the loop for RELEASE build? End If Next End If If Not foundInList Then Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference() typeData.ResultType = type typeData.ByAssumption = typeByAssumption typeData.InferenceRestrictions = inferenceRestrictions typeData.ArgumentLocation = argumentLocation typeData.Parameter = parameter typeData.InferredFromObject = inferredFromObject typeData.TypeParameter = DeclaredTypeParam InferenceTypeCollection.GetTypeDataList().Add(typeData) End If End Sub End Class Private Class ArgumentNode Inherits InferenceNode Public ReadOnly ParameterType As TypeSymbol Public ReadOnly Expression As BoundExpression Public ReadOnly Parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol) MyBase.New(graph, InferenceNodeType.ArgumentNode) Me.Expression = expression Me.ParameterType = parameterType Me.Parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean #If DEBUG Then VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode) #End If ' Check if all incoming are ok, otherwise skip inference. For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.") Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode) If currentTypedNode.InferredType Is Nothing Then Dim skipThisNode As Boolean = True If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then ' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able ' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam ' of the method we are inferring that is not yet inferred. ' Now find the invoke method of the delegate Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol) Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then Dim unboundLambda = DirectCast(Expression, UnboundLambda) Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1 Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol) Dim delegateParam As ParameterSymbol = delegateParameters(i) If lambdaParameter.Type Is Nothing AndAlso delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then If Graph.Diagnostic Is Nothing Then Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies) End If ' If this was an argument to the unbound Lambda, infer Object. If Graph.ObjectType Is Nothing Then Debug.Assert(Graph.Diagnostic IsNot Nothing) Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic) End If currentTypedNode.RegisterInferredType(Graph.ObjectType, lambdaParameter.TypeSyntax, currentTypedNode.InferredTypeByAssumption) ' ' Port SP1 CL 2941063 to VS10 ' Bug 153317 ' Report an error if Option Strict On or a warning if Option Strict Off ' because we have no hints about the lambda parameter ' and we are assuming that it is an object. ' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)" ' needs to put the squiggly on the first "z". Debug.Assert(Graph.Diagnostic IsNot Nothing) unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic) skipThisNode = False Exit For End If Next End If End If If skipThisNode Then InferenceComplete = True Return False ' DOn't restart the algorithm. End If End If Next Dim argumentType As TypeSymbol = Nothing Dim inferenceOk As Boolean = False Select Case Expression.Kind Case BoundKind.AddressOfOperator inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument( Expression, ParameterType, Parameter) Case BoundKind.LateAddressOfOperator ' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. Graph.ReportNotFailedInferenceDueToObject() inferenceOk = True Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda ' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available. ' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType ' will be set and not be Void. In this case the lambda argument should be treated as a regular ' argument so fall through in this case. Debug.Assert(Expression.Type Is Nothing) ' TODO: We are setting inference level before ' even trying to infer something from the lambda. It is possible ' that we won't infer anything, should consider changing the ' inference level after. Graph.MarkInferenceLevel(InferenceLevel.Orcas) inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument( Expression, ParameterType, Parameter) Case Else HandleAsAGeneralExpression: ' We should not infer from a Nothing literal. If Expression.IsStrictNothingLiteral() Then InferenceComplete = True ' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark ' the inference as failed. Return False End If Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any If Parameter IsNot Nothing AndAlso Parameter.IsByRef AndAlso (Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then ' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into ' that argument. Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef") inferenceRestrictions = Conversions.CombineConversionRequirements( inferenceRestrictions, Conversions.InvertConversionRequirement(inferenceRestrictions)) Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion") End If Dim arrayLiteral As BoundArrayLiteral = Nothing Dim argumentTypeByAssumption As Boolean = False Dim expressionType As TypeSymbol If Expression.Kind = BoundKind.ArrayLiteral Then arrayLiteral = DirectCast(Expression, BoundArrayLiteral) argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1 expressionType = New ArrayLiteralTypeSymbol(arrayLiteral) ElseIf Expression.Kind = BoundKind.TupleLiteral Then expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType Else expressionType = Expression.Type End If ' Need to create an ArrayLiteralTypeSymbol inferenceOk = Graph.InferTypeArgumentsFromArgument( Expression.Syntax, expressionType, argumentTypeByAssumption, ParameterType, Parameter, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions) End Select If Not inferenceOk Then ' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints. Graph.MarkInferenceFailure() If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then Graph.ReportNotFailedInferenceDueToObject() End If End If InferenceComplete = True Return False ' // Don't restart the algorithm; End Function End Class Private Class InferenceGraph Inherits Graph(Of InferenceNode) Public Diagnostic As BindingDiagnosticBag Public ObjectType As NamedTypeSymbol Public ReadOnly Candidate As MethodSymbol Public ReadOnly Arguments As ImmutableArray(Of BoundExpression) Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer) Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer) Public ReadOnly DelegateReturnType As TypeSymbol Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) Private _someInferenceFailed As Boolean Private _inferenceErrorReasons As InferenceErrorReasons Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise. Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode) Private ReadOnly _verifyingAssertions As Boolean Private Sub New( diagnostic As BindingDiagnosticBag, candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing) Me.Diagnostic = diagnostic Me.Candidate = candidate Me.Arguments = arguments Me.ParameterToArgumentMap = parameterToArgumentMap Me.ParamArrayItems = paramArrayItems Me.DelegateReturnType = delegateReturnType Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch Me.UseSiteInfo = useSiteInfo ' Allocate the array of TypeParameter nodes. Dim arity As Integer = candidate.Arity Dim typeParameterNodes(arity - 1) As TypeParameterNode For i As Integer = 0 To arity - 1 Step 1 typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i)) Next _typeParameterNodes = typeParameterNodes.AsImmutableOrNull() End Sub Public ReadOnly Property SomeInferenceHasFailed As Boolean Get Return _someInferenceFailed End Get End Property Public Sub MarkInferenceFailure() _someInferenceFailed = True End Sub Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean Get Return _allFailedInferenceIsDueToObject End Get End Property Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons Get Return _inferenceErrorReasons End Get End Property Public Sub ReportNotFailedInferenceDueToObject() _allFailedInferenceIsDueToObject = False End Sub Public ReadOnly Property TypeInferenceLevel As InferenceLevel Get Return _typeInferenceLevel End Get End Property Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel) If _typeInferenceLevel < typeInferenceLevel Then _typeInferenceLevel = typeInferenceLevel End If End Sub Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, inferTheseTypeParameters As BitVector ) As Boolean Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch, useSiteInfo) ' Build a graph describing the flow of type inference data. ' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments. ' In the rest of this function that graph is then processed (see below for more details). Essentially, for each ' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant ' type algorithm is then performed over the list of hints associated with each node. ' ' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed ' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type ' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type ' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)), ' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for ' Array co-variance. graph.PopulateGraph() Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance() ' This is the restart point of the algorithm Do Dim restartAlgorithm As Boolean = False Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) = graph.BuildStronglyConnectedComponents() topoSortedGraph.Clear() stronglyConnectedComponents.TopoSort(topoSortedGraph) ' We now iterate over the topologically-sorted strongly connected components of the graph, and generate ' type hints as appropriate. ' ' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer ' types for all type parameters referenced by that argument and then propagate those types as hints ' to the referenced type parameters. If there are incoming edges into the argument node, they correspond ' to parameters of lambda arguments that get their value from the delegate type that contains type ' parameters that would have been inferred during a previous iteration of the loop. Those types are ' flowed into the lambda argument. ' ' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run ' the dominant type algorithm over all of it's hints and use the resulting type as the value for the ' referenced type parameter. ' ' If we find a strongly connected component with more than one node, it means we ' have a cycle and cannot simply run the inference algorithm. When this happens, ' we look through the nodes in the cycle for a type parameter node with at least ' one type hint. If we find one, we remove all incoming edges to that node, ' infer the type using its hints, and then restart the whole algorithm from the ' beginning (recompute the strongly connected components, resort them, and then ' iterate over the graph again). The source nodes of the incoming edges we ' removed are added to an "assertion list". After graph traversal is done we ' then run inference on any "assertion nodes" we may have created. For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes ' Small optimization if one node If childNodes.Count = 1 Then If childNodes(0).InferTypeAndPropagateHints() Then ' consider: scottwis ' We should be asserting here, because this code is unreachable.. ' There are two implementations of InferTypeAndPropagateHints, ' one for "named nodes" (nodes corresponding to arguments) and another ' for "type nodes" (nodes corresponding to types). ' The implementation for "named nodes" always returns false, which means ' "don't restart the algorithm". The implementation for "type nodes" only returns true ' if a node has incoming edges that have not been visited previously. In order for that ' to happen the node must be inside a strongly connected component with more than one node ' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in ' topological order, which means all incoming edges should have already been visited. ' That means that if we reach this code, there is probably a bug in the traversal process. We ' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error. ' ' An argument could be made that it is good to have this because ' InferTypeAndPropagateHints is virtual, and should some new node type be ' added it's implementation may return true, and so this would follow that ' path. That argument does make some tiny amount of sense, and so we ' should keep this code here to make it easier to make any such ' modifications in the future. However, we still need an assert to guard ' against graph traversal bugs, and in the event that such changes are ' made, leave it to the modifier to remove the assert if necessary. Throw ExceptionUtilities.Unreachable End If Else Dim madeInferenceProgress As Boolean = False For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then If child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If madeInferenceProgress = True End If Next If Not madeInferenceProgress Then ' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now, ' will infer object if no type hints. For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If Next End If If restartAlgorithm Then Exit For ' For Each sccNode End If End If Next If restartAlgorithm Then Continue Do End If Exit Do Loop 'The commented code below is from Dev10, but it looks like 'it doesn't do anything useful because topoSortedGraph contains 'StronglyConnectedComponents, which have NodeType=None. ' 'graph.m_VerifyingAssertions = True 'GraphNodeListIterator assertionIter(&topoSortedGraph); ' While (assertionIter.MoveNext()) '{ ' GraphNode* currentNode = assertionIter.Current(); ' if (currentNode->m_NodeType == TypedNodeType) ' { ' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode; ' currentTypeNode->VerifyTypeAssertions(); ' } '} 'graph.m_VerifyingAssertions = False topoSortedGraph.Free() Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed someInferenceFailed = graph.SomeInferenceHasFailed allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject inferenceErrorReasons = graph.InferenceErrorReasons ' Make sure that allFailedInferenceIsDueToObject only stays set, ' if there was an actual inference failure. If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then allFailedInferenceIsDueToObject = False End If Dim arity As Integer = candidate.Arity Dim inferredTypes(arity - 1) As TypeSymbol Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken For i As Integer = 0 To arity - 1 Step 1 ' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter, ' it might not be cleaned in case of a failure. Will use the former for now. Dim typeParameterNode = graph._typeParameterNodes(i) Dim inferredType As TypeSymbol = typeParameterNode.InferredType If inferredType Is Nothing AndAlso (inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then succeeded = False End If If typeParameterNode.InferredTypeByAssumption Then If inferredTypeByAssumption.IsNull Then inferredTypeByAssumption = BitVector.Create(arity) End If inferredTypeByAssumption(i) = True End If inferredTypes(i) = inferredType inferredFromLocation(i) = typeParameterNode.InferredFromLocation Next typeArguments = inferredTypes.AsImmutableOrNull() typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull() inferenceLevel = graph._typeInferenceLevel Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic) diagnostic = graph.Diagnostic asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch useSiteInfo = graph.UseSiteInfo Return succeeded End Function Private Sub PopulateGraph() Dim candidate As MethodSymbol = Me.Candidate Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing) Dim argIndex As Integer For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then Continue For End If If Not isExpandedParamArrayForm Then argIndex = parameterToArgumentMap(paramIndex) Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex)) Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. '!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!! If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then Continue For End If RegisterArgument(paramArrayArgument, targetType, param) Else Debug.Assert(isExpandedParamArrayForm) '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form. ' Note, that explicitly converted NOTHING is treated the same way by Dev10. If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then Continue For End If ' Otherwise, for a ParamArray parameter, all the matching arguments are passed ' ByVal as instances of the element type of the ParamArray. ' Perform the conversions to the element type of the ParamArray here. Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then Continue For End If targetType = arrayType.ElementType If targetType.Kind = SymbolKind.ErrorType Then Continue For End If For j As Integer = 0 To paramArrayItems.Count - 1 Step 1 If arguments(paramArrayItems(j)).HasErrors Then Continue For End If RegisterArgument(arguments(paramArrayItems(j)), targetType, param) Next End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) Dim argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then Continue For End If RegisterArgument(argument, targetType, param) Next AddDelegateReturnTypeToGraph() End Sub Private Sub AddDelegateReturnTypeToGraph() If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax, Me.DelegateReturnType) Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing) ' Add the edges from all the current generic parameters to this named node. For Each current As InferenceNode In Vertices If current.NodeType = InferenceNodeType.TypeParameterNode Then AddEdge(current, returnNode) End If Next ' Add the edges from the resultType outgoing to the generic parameters. AddTypeToGraph(returnNode, isOutgoingEdge:=True) End If End Sub Private Sub RegisterArgument( argument As BoundExpression, targetType As TypeSymbol, param As ParameterSymbol ) ' Dig through parenthesized. If Not argument.IsNothingLiteral Then argument = argument.GetMostEnclosedParenthesizedExpression() End If Dim argNode As New ArgumentNode(Me, argument, targetType, param) Select Case argument.Kind Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda AddLambdaToGraph(argNode, argument.GetBinderFromLambda()) Case BoundKind.AddressOfOperator AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder) Case BoundKind.TupleLiteral AddTupleLiteralToGraph(argNode) Case Else AddTypeToGraph(argNode, isOutgoingEdge:=True) End Select End Sub Private Sub AddTypeToGraph( node As ArgumentNode, isOutgoingEdge As Boolean ) AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length)) End Sub Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode Dim ordinal As Integer = typeParameter.Ordinal If ordinal < _typeParameterNodes.Length AndAlso _typeParameterNodes(ordinal) IsNot Nothing AndAlso typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then Return _typeParameterNodes(ordinal) End If Return Nothing End Function Private Sub AddTypeToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, isOutgoingEdge As Boolean, ByRef haveSeenTypeParameters As BitVector ) Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter) If typeParameterNode IsNot Nothing AndAlso Not haveSeenTypeParameters(typeParameter.Ordinal) Then If typeParameterNode.Parameter Is Nothing Then typeParameterNode.SetParameter(argNode.Parameter) End If If (isOutgoingEdge) Then AddEdge(argNode, typeParameterNode) Else AddEdge(typeParameterNode, argNode) End If haveSeenTypeParameters(typeParameter.Ordinal) = True End If Case SymbolKind.ArrayType AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters) Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select End Sub Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode) AddTupleLiteralToGraph(argNode.ParameterType, argNode) End Sub Private Sub AddTupleLiteralToGraph( parameterType As TypeSymbol, argNode As ArgumentNode ) Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral) Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral) Dim tupleArguments = tupleLiteral.Arguments If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible For i As Integer = 0 To tupleArguments.Length - 1 RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter) Next Return End If AddTypeToGraph(argNode, isOutgoingEdge:=True) End Sub Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder) AddAddressOfToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddAddressOfToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator) If parameterType.IsTypeParameter() Then AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge haveSeenTypeParameters.Clear() For Each delegateParameter As ParameterSymbol In invoke.Parameters AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge Next End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder) AddLambdaToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddLambdaToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) If parameterType.IsTypeParameter() Then ' Lambda is bound to a generic typeParam, just infer anonymous delegate AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) Select Case argNode.Expression.Kind Case BoundKind.QueryLambda lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind) End Select Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1 If lambdaParameters(i).Type IsNot Nothing Then ' Prepopulate the hint from the lambda's parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. ' TODO: Consider using location for the type declaration. InferTypeArgumentsFromArgument( argNode.Expression.Syntax, lambdaParameters(i).Type, argumentTypeByAssumption:=False, parameterType:=delegateParameters(i).Type, param:=delegateParameters(i), digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) Next haveSeenTypeParameters.Clear() AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean Dim argumentType As TypeSymbol = argument.Type Dim isArrayLiteral As Boolean = False If argumentType Is Nothing Then If argument.Kind = BoundKind.ArrayLiteral Then isArrayLiteral = True argumentType = DirectCast(argument, BoundArrayLiteral).InferredType Else Return False End If End If While paramType.IsArrayType() If Not argumentType.IsArrayType() Then Return False End If Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol) ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If argumentArray.Rank <> paramArrayType.Rank OrElse (Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then Return False End If isArrayLiteral = False argumentType = argumentArray.ElementType paramType = paramArrayType.ElementType End While Return True End Function Public Sub RegisterTypeParameterHint( genericParameter As TypeParameterSymbol, inferredType As TypeSymbol, inferredTypeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter) If typeNode IsNot Nothing Then typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions) End If End Sub Private Function RefersToGenericParameterToInferArgumentFor( parameterType As TypeSymbol ) As Boolean Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter) ' TODO: It looks like this check can give us a false positive. For example, ' if we are resolving a recursive call we might already bind a type ' parameter to itself (to the same type parameter of the containing method). ' So, the fact that we ran into this type parameter doesn't necessary mean ' that there is anything to infer. I am not sure if this can lead to some ' negative effect. Dev10 appears to have the same behavior, from what I see ' in the code. If typeNode IsNot Nothing Then Return True End If Case SymbolKind.ArrayType Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes If RefersToGenericParameterToInferArgumentFor(elementType) Then Return True End If Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If RefersToGenericParameterToInferArgumentFor(typeArgument) Then Return True End If Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select Return False End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' If a generic method is parameterized by T, an argument of type A matches a parameter of type ' P, this function tries to infer type for T by using these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T Private Function InferTypeArgumentsFromArgumentDirectly( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If argumentType Is Nothing OrElse argumentType.IsVoidType() Then ' We should never be able to infer a value from something that doesn't provide a value, e.g: ' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar()) Return False End If ' If a generic method is parameterized by T, an argument of type A matching a parameter of type ' P can be used to infer a type for T by these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T ' -- If P is (T, T) and A is (X, X), then infer X for T If parameterType.IsTypeParameter() Then RegisterTypeParameterHint( DirectCast(parameterType, TypeParameterSymbol), argumentType, argumentTypeByAssumption, argumentLocation, param, False, inferenceRestrictions) Return True End If Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType). TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then If parameterElementTypes.Length <> argumentElementTypes.Length Then Return False End If For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1 Dim parameterElementType = parameterElementTypes(typeArgumentIndex) Dim argumentElementType = argumentElementTypes(typeArgumentIndex) ' propagate restrictions to the elements If Not InferTypeArgumentsFromArgument( argumentLocation, argumentElementType, argumentTypeByAssumption, parameterElementType, param, digThroughToBasesAndImplements, inferenceRestrictions ) Then Return False End If Next Return True ElseIf parameterType.Kind = SymbolKind.NamedType Then ' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T) Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol) If parameterTypeAsNamedType.IsGenericType Then Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing) If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then Do For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1 ' The following code is subtle. Let's recap what's going on... ' We've so far encountered some context, e.g. "_" or "ICovariant(_)" ' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions. ' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)" ' and we have to apply extra restrictions to each of those subcontexts. ' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint. ' For variant parameters it's more subtle. First, we have to strengthen the ' restrictions to require reference conversion (rather than just VB conversion or ' whatever it was). Second, if it was an In parameter, then we have to invert ' the sense. ' ' Processing of generics is tricky in the case that we've already encountered ' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction ' "AnyConversionAndReverse", so that the argument could be copied into the parameter ' and back again. But now consider if we find a generic inside that ByRef, e.g. ' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case ' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)". ' What's needed for any candidate for T is that G(Of Hint) be convertible to ' G(Of Candidate), and vice versa for the copyback. ' ' But then what should we write down for the hints? The problem is that hints inhere ' to the generic parameter T, not to the function parameter G(Of T). So we opt for a ' safe approximation: we just require CLR identity between a candidate and the hint. ' This is safe but is a little overly-strict. For example: ' Class G(Of T) ' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal) ' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T) ' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T) ' ... ' inf(New G(Of Car), New Animal) ' inf(Of Animal)(New G(Of Car), New Animal) ' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure, ' even though the explicitly-provided T=Animal ends up working. ' ' Well, it's the best we can do without some major re-architecting of the way ' hints and type-inference works. That's because all our hints inhere to the ' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter. ' But I don't think we'll ever do better than this, just because trying to do ' type inference inferring to arguments/parameters becomes exponential. ' Variance generic parameters will work the same. ' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction: Dim paramInferenceRestrictions As RequiredConversion Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance Case VarianceKind.In paramInferenceRestrictions = Conversions.InvertConversionRequirement( Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)) Case VarianceKind.Out paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions) Case Else Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance) paramInferenceRestrictions = RequiredConversion.Identity End Select Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter If paramInferenceRestrictions = RequiredConversion.Reference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter Else _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), argumentTypeByAssumption, parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), param, _DigThroughToBasesAndImplements, paramInferenceRestrictions ) Then ' TODO: Would it make sense to continue through other type arguments even if inference failed for ' the current one? Return False End If Next ' Do not forget about type parameters of containing type parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType Loop While parameterTypeAsNamedType IsNot Nothing Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing) Return True End If ElseIf parameterTypeAsNamedType.IsNullableType() Then ' we reach here when the ParameterType is an instantiation of Nullable, ' and the argument type is NOT a generic type. ' lwischik: ??? what do array elements have to do with nullables? Return InferTypeArgumentsFromArgument( argumentLocation, argumentType, argumentTypeByAssumption, parameterTypeAsNamedType.GetNullableUnderlyingType(), param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement)) End If Return False End If ElseIf parameterType.IsArrayType() Then If argumentType.IsArrayType() Then Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol) Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If parameterArray.Rank = argumentArray.Rank AndAlso (argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then Return InferTypeArgumentsFromArgument( argumentLocation, argumentArray.ElementType, argumentTypeByAssumption, parameterArray.ElementType, param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement))) End If End If Return False End If Return True End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))", ' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))". ' The task is to infer hints for T, e.g. "T=int". ' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _). ' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly" ' to do that. ' ' Note: this function returns "false" if it failed to pattern-match between argument and parameter type, ' and "true" if it succeeded. ' Success in pattern-matching may or may not produce type-hints for generic parameters. ' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced ' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints, ' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from ' here (to show success at pattern-matching) and leave the downstream code to produce an error message about ' failing to infer T. Friend Function InferTypeArgumentsFromArgument( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then Return True End If ' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable. Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) If Inferred Then Return True End If If parameterType.IsTypeParameter() Then ' If we failed to match an argument against a generic parameter T, it means that the ' argument was something unmatchable, e.g. an AddressOf. Return False End If ' If we didn't find a direct match, we will have to look in base classes for a match. ' We'll either fix ParameterType and look amongst the bases of ArgumentType, ' or we'll fix ArgumentType and look amongst the bases of ParameterType, ' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by ' covariance and contravariance... If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then Return False End If ' Special handling for Anonymous Delegates. If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso (inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse inferenceRestrictions = RequiredConversion.AnyAndReverse) Then Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol) Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType) ' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type. If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then ' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type. ' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g. ' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer) ' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T)) ' // maybe defined as Delegate Function D(Of T)(x as T) as T. ' We're looking to achieve the same functionality in pattern-matching these types as we already ' have for calling "inf(function(i as integer) i)" directly. ' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions). ' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more. ' And it does allow a function BaseSearchType to be used for a sub FixedType. ' ' Anyway, the plan is to match each of the parameters in the ArgumentType delegate ' to the equivalent parameters in the ParameterType delegate, and also match the return types. ' ' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for ' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed ' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed ' with some inferred types, for the sake of better error messages, even though we know that ultimately ' it will fail (because no non-anonymous delegate type can be converted to a delegate type). Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then ' If parameter-counts are mismatched then it's a failure. ' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument ' to be supplied to a function which expects a parameterfull delegate. Return False End If ' First we'll check that the argument types all match. For i As Integer = 0 To argumentParams.Length - 1 If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then ' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works. Return False End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentParams(i).Type, argumentTypeByAssumption, parameterParams(i).Type, param, MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments Return False End If Next ' Now check that the return type matches. ' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate. If parameterInvokeProc.IsSub Then ' A *sub* delegate parameter can accept either a *function* or a *sub* argument: Return True ElseIf argumentInvokeProc.IsSub Then ' A *function* delegate parameter cannot accept a *sub* argument. Return False Else ' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter: Return InferTypeArgumentsFromArgument( argumentLocation, argumentInvokeProc.ReturnType, argumentTypeByAssumption, parameterInvokeProc.ReturnType, param, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, RequiredConversion.Any) ' Any: covariance in delegate returns End If End If End If ' MatchBaseOfGenericArgumentToParameter: used for covariant situations, ' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)". ' ' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations, ' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))". Dim fContinue As Boolean = False If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then fContinue = FindMatchingBase(argumentType, parameterType) Else fContinue = FindMatchingBase(parameterType, argumentType) End If If Not fContinue Then Return False End If ' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType. ' Therefore the above statement has altered either ArgumentType or ParameterType. Return InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) End Function Private Function FindMatchingBase( ByRef baseSearchType As TypeSymbol, ByRef fixedType As TypeSymbol ) As Boolean Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing) If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then ' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList), ' then we won't learn anything about generic type parameters here: Return False End If Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then ' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface. ' (it's impossible to inherit from anything else). Return False End If Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then ' The things listed above are the only ones that have bases that could ever lead anywhere useful. ' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes. Return False End If If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then ' If the types checked were already identical, then exit Return False End If ' Otherwise, if we got through all the above tests, then it really is worth searching through the base ' types to see if that helps us find a match. Dim matchingBase As TypeSymbol = Nothing If fixedTypeTypeKind = TypeKind.Class Then FindMatchingBaseClass(baseSearchType, fixedType, matchingBase) Else Debug.Assert(fixedTypeTypeKind = TypeKind.Interface) FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase) End If If matchingBase Is Nothing Then Return False End If ' And this is what we found baseSearchType = matchingBase Return True End Function Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean If match Is Nothing Then match = type Return True ElseIf match.IsSameTypeIgnoringAll(type) Then Return True Else match = Nothing Return False End If End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then Return False End If Next Case Else For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual([interface], match) Then Return False End If End If Next End Select Return True End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If ' TODO: Do we need to continue even if we already have a matching base class? ' It looks like Dev10 continues. If Not FindMatchingBaseClass(constraint, baseClass, match) Then Return False End If Next Case Else Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) While baseType IsNot Nothing If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(baseType, match) Then Return False End If Exit While End If baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) End While End Select Return True End Function Public Function InferTypeArgumentsFromAddressOfArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean If parameterType.IsDelegateType() Then Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return False End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim addrOf = DirectCast(argument, BoundAddressOfOperator) Dim fromMethod As MethodSymbol = Nothing Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed( addrOf, invokeMethod, ignoreMethodReturnType:=True, diagnostics:=BindingDiagnosticBag.Discarded) fromMethod = matchingMethod.Key methodConversions = matchingMethod.Value If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse (addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then Return False End If If fromMethod.IsSub Then ReportNotFailedInferenceDueToObject() Return True End If Dim targetReturnType As TypeSymbol = fromMethod.ReturnType If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then ' Return false if we didn't make any inference progress. Return False End If Return InferTypeArgumentsFromArgument( argument.Syntax, targetReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) End If ' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. ReportNotFailedInferenceDueToObject() Return True End Function Public Function InferTypeArgumentsFromLambdaArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse argument.Kind = BoundKind.QueryLambda OrElse argument.Kind = BoundKind.GroupTypeInferenceLambda) If parameterType.IsTypeParameter() Then Dim anonymousLambdaType As TypeSymbol = Nothing Select Case argument.Kind Case BoundKind.QueryLambda ' Do not infer Anonymous Delegate type from query lambda. Case BoundKind.GroupTypeInferenceLambda ' Can't infer from this lambda. Case BoundKind.UnboundLambda ' Infer Anonymous Delegate type from unbound lambda. Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then Dim delegateInvokeMethod As MethodSymbol = Nothing If inferredAnonymousDelegate.Key IsNot Nothing Then delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod End If If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then anonymousLambdaType = inferredAnonymousDelegate.Key End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If anonymousLambdaType IsNot Nothing Then Return InferTypeArgumentsFromArgument( argument.Syntax, anonymousLambdaType, argumentTypeByAssumption:=False, parameterType:=parameterType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) Else Return True End If ElseIf parameterType.IsDelegateType() Then Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. ' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to ' infer more stuff from other non-lambda arguments, we might have a better chance to have ' more type information for the lambda, allowing successful lambda interpretation. ' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters ' are inferred. Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return True End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim lambdaParams As ImmutableArray(Of ParameterSymbol) Select Case argument.Kind Case BoundKind.QueryLambda lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParams = DirectCast(argument, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters If lambdaParams.Length > delegateParams.Length Then Return True End If For i As Integer = 0 To lambdaParams.Length - 1 Step 1 Dim lambdaParam As ParameterSymbol = lambdaParams(i) Dim delegateParam As ParameterSymbol = delegateParams(i) If lambdaParam.Type Is Nothing Then ' If a lambda parameter has no type and the delegate parameter refers ' to an unbound generic parameter, we can't infer yet. If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then ' Skip this type argument and other parameters will infer it or ' if that doesn't happen it will report an error. ' TODO: Why does it make sense to continue here? It looks like we can infer something from ' lambda's return type based on incomplete information. Also, this 'if' is redundant, ' there is nothing left to do in this loop anyway, and "continue" doesn't change anything. Continue For End If Else ' report the type of the lambda parameter to the delegate parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. InferTypeArgumentsFromArgument( argument.Syntax, lambdaParam.Type, argumentTypeByAssumption:=False, parameterType:=delegateParam.Type, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If Next ' OK, now try to infer delegates return type from the lambda. Dim lambdaReturnType As TypeSymbol Select Case argument.Kind Case BoundKind.QueryLambda Dim queryLambda = DirectCast(argument, BoundQueryLambda) lambdaReturnType = queryLambda.LambdaSymbol.ReturnType If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then lambdaReturnType = queryLambda.Expression.Type If lambdaReturnType Is Nothing Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Debug.Assert(Me.Diagnostic IsNot Nothing) lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type End If End If Case BoundKind.GroupTypeInferenceLambda lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams) Case BoundKind.UnboundLambda Dim unboundLambda = DirectCast(argument, UnboundLambda) If unboundLambda.IsFunctionLambda Then Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False) Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature) If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then lambdaReturnType = Nothing ' Let's keep return type inference errors If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then lambdaReturnType = Nothing Else Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes, inferenceSignature.ParameterIsByRef, returnTypeInfo.Key, returnsByRef:=False)) Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then lambdaReturnType = returnTypeInfo.Key ' Let's keep return type inference warnings, if any. If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies) Else lambdaReturnType = Nothing ' Let's preserve diagnostics that caused the failure If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(boundLambda.Diagnostics) End If End If End If ' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter ' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T... If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then ' By this stage we know that ' * we have an async/iterator lambda argument ' * the parameter-to-match is a delegate type whose result type refers to generic parameters ' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have ' to dig in. Or it might be a delegate with result type "T" in which case we ' don't dig in. Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol) Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol) If lambdaReturnNamedType.Arity = 1 AndAlso IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition, returnNamedType.OriginalDefinition) Then ' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T) ' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation. Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything)) lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) End If End If Else lambdaReturnType = Nothing If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then If _asyncLambdaSubToFunctionMismatch Is Nothing Then _asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance) End If _asyncLambdaSubToFunctionMismatch.Add(unboundLambda) End If End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If lambdaReturnType Is Nothing Then ' Inference failed, give up. Return False End If If lambdaReturnType.IsErrorType() Then Return True End If ' Now infer from the result type ' not ArgumentTypeByAssumption ??? lwischik: but maybe it should... Return InferTypeArgumentsFromArgument( argument.Syntax, lambdaReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param) End If Return True End Function Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. Dim methodSymbol As MethodSymbol = Candidate Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length) For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1 Dim typeNode As TypeParameterNode = _typeParameterNodes(i) Dim newType As TypeSymbol If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then 'No substitution newType = methodSymbol.TypeParameters(i) Else newType = typeNode.CandidateInferredType End If typeArguments.Add(New TypeWithModifiers(newType)) Next Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree()) ' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type End Function Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list") ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub ReportIncompatibleInferenceError( typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) If typeInfos.Count < 1 Then Return End If ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons) _inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons 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 Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The only public entry point is the Infer method. ''' </summary> Friend MustInherit Class TypeArgumentInference Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, Optional inferTheseTypeParameters As BitVector = Nothing ) As Boolean Debug.Assert(candidate Is candidate.ConstructedFrom) Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons, inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch, useSiteInfo, diagnostic, inferTheseTypeParameters) End Function ' No-one should create instances of this class. Private Sub New() End Sub Public Enum InferenceLevel As Byte None = 0 ' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate ' or no delegate in the overload resolution hence both have value 0 such that overload resolution ' will not prefer a non inferred method over an inferred one. Whidbey = 0 Orcas = 1 ' Keep invalid the biggest number Invalid = 2 End Enum ' MatchGenericArgumentParameter: ' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T). ' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm). ' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg). ' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical. ' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T). Public Enum MatchGenericArgumentToParameter MatchBaseOfGenericArgumentToParameter MatchArgumentToBaseOfGenericParameter MatchGenericArgumentToParameterExactly End Enum Private Enum InferenceNodeType As Byte ArgumentNode TypeParameterNode End Enum Private MustInherit Class InferenceNode Inherits GraphNode(Of InferenceNode) Public ReadOnly NodeType As InferenceNodeType Public InferenceComplete As Boolean Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType) MyBase.New(graph) Me.NodeType = nodeType End Sub Public Shadows ReadOnly Property Graph As InferenceGraph Get Return DirectCast(MyBase.Graph, InferenceGraph) End Get End Property ''' <summary> ''' Returns True if the inference algorithm should be restarted. ''' </summary> Public MustOverride Function InferTypeAndPropagateHints() As Boolean <Conditional("DEBUG")> Public Sub VerifyIncomingInferenceComplete( ByVal nodeType As InferenceNodeType ) If Not Graph.SomeInferenceHasFailed() Then For Each current As InferenceNode In IncomingEdges Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.") Debug.Assert(current.InferenceComplete, "Should have inferred type already") Next End If End Sub End Class Private Class DominantTypeDataTypeInference Inherits DominantTypeData ' Fields needed for error reporting Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention? Public Parameter As ParameterSymbol Public InferredFromObject As Boolean Public TypeParameter As TypeParameterSymbol Public ArgumentLocation As SyntaxNode End Class Private Class TypeParameterNode Inherits InferenceNode Public ReadOnly DeclaredTypeParam As TypeParameterSymbol Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference) Private _inferredType As TypeSymbol Private _inferredFromLocation As SyntaxNodeOrToken Private _inferredTypeByAssumption As Boolean ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' This one, cannot be changed once set. We need to clean this up later. Private _candidateInferredType As TypeSymbol Private _parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol) MyBase.New(graph, InferenceNodeType.TypeParameterNode) DeclaredTypeParam = typeParameter InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)() End Sub Public ReadOnly Property InferredType As TypeSymbol Get Return _inferredType End Get End Property Public ReadOnly Property CandidateInferredType As TypeSymbol Get Return _candidateInferredType End Get End Property Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken Get Return _inferredFromLocation End Get End Property Public ReadOnly Property InferredTypeByAssumption As Boolean Get Return _inferredTypeByAssumption End Get End Property Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean) ' Make sure ArrayLiteralTypeSymbol does not leak out Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol) If arrayLiteralType IsNot Nothing Then Dim arrayLiteral = arrayLiteralType.ArrayLiteral Dim arrayType = arrayLiteral.InferredType If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso arrayType.ElementType.SpecialType = SpecialType.System_Object Then ' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error ' when option strict is on and the array type is object() and there wasn't a dominant type. However, ' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type ' to suppress the error. inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly) Else inferredType = arrayLiteral.InferredType End If End If Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol)) _inferredType = inferredType _inferredFromLocation = inferredFromLocation _inferredTypeByAssumption = inferredTypeByAssumption ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' We need to clean this up. If _candidateInferredType Is Nothing Then _candidateInferredType = inferredType End If End Sub Public ReadOnly Property Parameter As ParameterSymbol Get Return _parameter End Get End Property Public Sub SetParameter(parameter As ParameterSymbol) Debug.Assert(_parameter Is Nothing) _parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean Dim numberOfIncomingEdges As Integer = IncomingEdges.Count Dim restartAlgorithm As Boolean = False Dim argumentLocation As SyntaxNode Dim numberOfIncomingWithNothing As Integer = 0 If numberOfIncomingEdges > 0 Then argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax Else argumentLocation = Nothing End If Dim numberOfAssertions As Integer = 0 Dim incomingFromObject As Boolean = False Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.") Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode) If currentNamedNode.Expression.Type IsNot Nothing AndAlso currentNamedNode.Expression.Type.IsObjectType() Then incomingFromObject = True End If If Not currentNamedNode.InferenceComplete Then Graph.RemoveEdge(currentNamedNode, Me) restartAlgorithm = True numberOfAssertions += 1 Else ' We should not infer from a Nothing literal. If currentNamedNode.Expression.IsStrictNothingLiteral() Then numberOfIncomingWithNothing += 1 End If End If Next If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then ' !! Inference has failed: All incoming type hints, were based on 'Nothing' Graph.MarkInferenceFailure() Graph.ReportNotFailedInferenceDueToObject() End If Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count() If numberOfTypeHints = 0 Then If numberOfAssertions = numberOfIncomingEdges Then Graph.MarkInferenceLevel(InferenceLevel.Orcas) Else ' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict. RegisterInferredType(Nothing, Nothing, False) Graph.MarkInferenceFailure() If Not incomingFromObject Then Graph.ReportNotFailedInferenceDueToObject() End If End If ElseIf numberOfTypeHints = 1 Then Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0) If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then argumentLocation = typeData.ArgumentLocation End If RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption) Else ' Run the whidbey algorithm to see if we are smarter now. Dim firstInferredType As TypeSymbol = Nothing Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList() For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData If firstInferredType Is Nothing Then firstInferredType = currentTypeInfo.ResultType ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then ' Whidbey failed hard here, in Orcas we added dominant type information. Graph.MarkInferenceLevel(InferenceLevel.Orcas) End If Next Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance() Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo) If dominantTypeDataList.Count = 1 Then ' //consider: scottwis ' // This seems dangerous to me, that we ' // remove error reasons here. ' // Instead of clearing these, what we should be doing is ' // asserting that they are not set. ' // If for some reason they get set, but ' // we enter this path, then we have a bug. ' // This code is just masking any such bugs. errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest)) Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0) RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption) ' // Also update the location of the argument for constraint error reporting later on. Else If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then ' !! Inference has failed. Dominant type algorithm found ambiguous types. Graph.ReportAmbiguousInferenceError(dominantTypeDataList) Else ' //consider: scottwis ' // This code appears to be operating under the assumption that if the error reason is not due to an ' // ambiguity then it must be because there was no best match. ' // We should be asserting here to verify that assertion. ' !! Inference has failed. Dominant type algorithm could not find a dominant type. Graph.ReportIncompatibleInferenceError(allTypeData) End If RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False) Graph.MarkInferenceFailure() End If Graph.RegisterErrorReasons(errorReasons) dominantTypeDataList.Free() End If InferenceComplete = True Return restartAlgorithm End Function Public Sub AddTypeHint( type As TypeSymbol, typeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal") ' Don't add error types to the type argument inference collection. If type.IsErrorType Then Return End If Dim foundInList As Boolean = False ' Do not merge array literals with other expressions If TypeOf type IsNot ArrayLiteralTypeSymbol Then For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList() ' Do not merge array literals with other expressions If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type) competitor.InferenceRestrictions = Conversions.CombineConversionRequirements( competitor.InferenceRestrictions, inferenceRestrictions) competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.") foundInList = True ' TODO: Should we simply exit the loop for RELEASE build? End If Next End If If Not foundInList Then Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference() typeData.ResultType = type typeData.ByAssumption = typeByAssumption typeData.InferenceRestrictions = inferenceRestrictions typeData.ArgumentLocation = argumentLocation typeData.Parameter = parameter typeData.InferredFromObject = inferredFromObject typeData.TypeParameter = DeclaredTypeParam InferenceTypeCollection.GetTypeDataList().Add(typeData) End If End Sub End Class Private Class ArgumentNode Inherits InferenceNode Public ReadOnly ParameterType As TypeSymbol Public ReadOnly Expression As BoundExpression Public ReadOnly Parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol) MyBase.New(graph, InferenceNodeType.ArgumentNode) Me.Expression = expression Me.ParameterType = parameterType Me.Parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean #If DEBUG Then VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode) #End If ' Check if all incoming are ok, otherwise skip inference. For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.") Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode) If currentTypedNode.InferredType Is Nothing Then Dim skipThisNode As Boolean = True If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then ' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able ' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam ' of the method we are inferring that is not yet inferred. ' Now find the invoke method of the delegate Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol) Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then Dim unboundLambda = DirectCast(Expression, UnboundLambda) Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1 Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol) Dim delegateParam As ParameterSymbol = delegateParameters(i) If lambdaParameter.Type Is Nothing AndAlso delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then If Graph.Diagnostic Is Nothing Then Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies) End If ' If this was an argument to the unbound Lambda, infer Object. If Graph.ObjectType Is Nothing Then Debug.Assert(Graph.Diagnostic IsNot Nothing) Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic) End If currentTypedNode.RegisterInferredType(Graph.ObjectType, lambdaParameter.TypeSyntax, currentTypedNode.InferredTypeByAssumption) ' ' Port SP1 CL 2941063 to VS10 ' Bug 153317 ' Report an error if Option Strict On or a warning if Option Strict Off ' because we have no hints about the lambda parameter ' and we are assuming that it is an object. ' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)" ' needs to put the squiggly on the first "z". Debug.Assert(Graph.Diagnostic IsNot Nothing) unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic) skipThisNode = False Exit For End If Next End If End If If skipThisNode Then InferenceComplete = True Return False ' DOn't restart the algorithm. End If End If Next Dim argumentType As TypeSymbol = Nothing Dim inferenceOk As Boolean = False Select Case Expression.Kind Case BoundKind.AddressOfOperator inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument( Expression, ParameterType, Parameter) Case BoundKind.LateAddressOfOperator ' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. Graph.ReportNotFailedInferenceDueToObject() inferenceOk = True Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda ' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available. ' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType ' will be set and not be Void. In this case the lambda argument should be treated as a regular ' argument so fall through in this case. Debug.Assert(Expression.Type Is Nothing) ' TODO: We are setting inference level before ' even trying to infer something from the lambda. It is possible ' that we won't infer anything, should consider changing the ' inference level after. Graph.MarkInferenceLevel(InferenceLevel.Orcas) inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument( Expression, ParameterType, Parameter) Case Else HandleAsAGeneralExpression: ' We should not infer from a Nothing literal. If Expression.IsStrictNothingLiteral() Then InferenceComplete = True ' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark ' the inference as failed. Return False End If Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any If Parameter IsNot Nothing AndAlso Parameter.IsByRef AndAlso (Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then ' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into ' that argument. Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef") inferenceRestrictions = Conversions.CombineConversionRequirements( inferenceRestrictions, Conversions.InvertConversionRequirement(inferenceRestrictions)) Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion") End If Dim arrayLiteral As BoundArrayLiteral = Nothing Dim argumentTypeByAssumption As Boolean = False Dim expressionType As TypeSymbol If Expression.Kind = BoundKind.ArrayLiteral Then arrayLiteral = DirectCast(Expression, BoundArrayLiteral) argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1 expressionType = New ArrayLiteralTypeSymbol(arrayLiteral) ElseIf Expression.Kind = BoundKind.TupleLiteral Then expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType Else expressionType = Expression.Type End If ' Need to create an ArrayLiteralTypeSymbol inferenceOk = Graph.InferTypeArgumentsFromArgument( Expression.Syntax, expressionType, argumentTypeByAssumption, ParameterType, Parameter, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions) End Select If Not inferenceOk Then ' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints. Graph.MarkInferenceFailure() If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then Graph.ReportNotFailedInferenceDueToObject() End If End If InferenceComplete = True Return False ' // Don't restart the algorithm; End Function End Class Private Class InferenceGraph Inherits Graph(Of InferenceNode) Public Diagnostic As BindingDiagnosticBag Public ObjectType As NamedTypeSymbol Public ReadOnly Candidate As MethodSymbol Public ReadOnly Arguments As ImmutableArray(Of BoundExpression) Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer) Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer) Public ReadOnly DelegateReturnType As TypeSymbol Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) Private _someInferenceFailed As Boolean Private _inferenceErrorReasons As InferenceErrorReasons Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise. Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode) Private ReadOnly _verifyingAssertions As Boolean Private Sub New( diagnostic As BindingDiagnosticBag, candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing) Me.Diagnostic = diagnostic Me.Candidate = candidate Me.Arguments = arguments Me.ParameterToArgumentMap = parameterToArgumentMap Me.ParamArrayItems = paramArrayItems Me.DelegateReturnType = delegateReturnType Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch Me.UseSiteInfo = useSiteInfo ' Allocate the array of TypeParameter nodes. Dim arity As Integer = candidate.Arity Dim typeParameterNodes(arity - 1) As TypeParameterNode For i As Integer = 0 To arity - 1 Step 1 typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i)) Next _typeParameterNodes = typeParameterNodes.AsImmutableOrNull() End Sub Public ReadOnly Property SomeInferenceHasFailed As Boolean Get Return _someInferenceFailed End Get End Property Public Sub MarkInferenceFailure() _someInferenceFailed = True End Sub Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean Get Return _allFailedInferenceIsDueToObject End Get End Property Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons Get Return _inferenceErrorReasons End Get End Property Public Sub ReportNotFailedInferenceDueToObject() _allFailedInferenceIsDueToObject = False End Sub Public ReadOnly Property TypeInferenceLevel As InferenceLevel Get Return _typeInferenceLevel End Get End Property Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel) If _typeInferenceLevel < typeInferenceLevel Then _typeInferenceLevel = typeInferenceLevel End If End Sub Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, inferTheseTypeParameters As BitVector ) As Boolean Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch, useSiteInfo) ' Build a graph describing the flow of type inference data. ' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments. ' In the rest of this function that graph is then processed (see below for more details). Essentially, for each ' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant ' type algorithm is then performed over the list of hints associated with each node. ' ' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed ' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type ' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type ' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)), ' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for ' Array co-variance. graph.PopulateGraph() Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance() ' This is the restart point of the algorithm Do Dim restartAlgorithm As Boolean = False Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) = graph.BuildStronglyConnectedComponents() topoSortedGraph.Clear() stronglyConnectedComponents.TopoSort(topoSortedGraph) ' We now iterate over the topologically-sorted strongly connected components of the graph, and generate ' type hints as appropriate. ' ' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer ' types for all type parameters referenced by that argument and then propagate those types as hints ' to the referenced type parameters. If there are incoming edges into the argument node, they correspond ' to parameters of lambda arguments that get their value from the delegate type that contains type ' parameters that would have been inferred during a previous iteration of the loop. Those types are ' flowed into the lambda argument. ' ' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run ' the dominant type algorithm over all of it's hints and use the resulting type as the value for the ' referenced type parameter. ' ' If we find a strongly connected component with more than one node, it means we ' have a cycle and cannot simply run the inference algorithm. When this happens, ' we look through the nodes in the cycle for a type parameter node with at least ' one type hint. If we find one, we remove all incoming edges to that node, ' infer the type using its hints, and then restart the whole algorithm from the ' beginning (recompute the strongly connected components, resort them, and then ' iterate over the graph again). The source nodes of the incoming edges we ' removed are added to an "assertion list". After graph traversal is done we ' then run inference on any "assertion nodes" we may have created. For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes ' Small optimization if one node If childNodes.Count = 1 Then If childNodes(0).InferTypeAndPropagateHints() Then ' consider: scottwis ' We should be asserting here, because this code is unreachable.. ' There are two implementations of InferTypeAndPropagateHints, ' one for "named nodes" (nodes corresponding to arguments) and another ' for "type nodes" (nodes corresponding to types). ' The implementation for "named nodes" always returns false, which means ' "don't restart the algorithm". The implementation for "type nodes" only returns true ' if a node has incoming edges that have not been visited previously. In order for that ' to happen the node must be inside a strongly connected component with more than one node ' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in ' topological order, which means all incoming edges should have already been visited. ' That means that if we reach this code, there is probably a bug in the traversal process. We ' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error. ' ' An argument could be made that it is good to have this because ' InferTypeAndPropagateHints is virtual, and should some new node type be ' added it's implementation may return true, and so this would follow that ' path. That argument does make some tiny amount of sense, and so we ' should keep this code here to make it easier to make any such ' modifications in the future. However, we still need an assert to guard ' against graph traversal bugs, and in the event that such changes are ' made, leave it to the modifier to remove the assert if necessary. Throw ExceptionUtilities.Unreachable End If Else Dim madeInferenceProgress As Boolean = False For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then If child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If madeInferenceProgress = True End If Next If Not madeInferenceProgress Then ' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now, ' will infer object if no type hints. For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If Next End If If restartAlgorithm Then Exit For ' For Each sccNode End If End If Next If restartAlgorithm Then Continue Do End If Exit Do Loop 'The commented code below is from Dev10, but it looks like 'it doesn't do anything useful because topoSortedGraph contains 'StronglyConnectedComponents, which have NodeType=None. ' 'graph.m_VerifyingAssertions = True 'GraphNodeListIterator assertionIter(&topoSortedGraph); ' While (assertionIter.MoveNext()) '{ ' GraphNode* currentNode = assertionIter.Current(); ' if (currentNode->m_NodeType == TypedNodeType) ' { ' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode; ' currentTypeNode->VerifyTypeAssertions(); ' } '} 'graph.m_VerifyingAssertions = False topoSortedGraph.Free() Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed someInferenceFailed = graph.SomeInferenceHasFailed allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject inferenceErrorReasons = graph.InferenceErrorReasons ' Make sure that allFailedInferenceIsDueToObject only stays set, ' if there was an actual inference failure. If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then allFailedInferenceIsDueToObject = False End If Dim arity As Integer = candidate.Arity Dim inferredTypes(arity - 1) As TypeSymbol Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken For i As Integer = 0 To arity - 1 Step 1 ' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter, ' it might not be cleaned in case of a failure. Will use the former for now. Dim typeParameterNode = graph._typeParameterNodes(i) Dim inferredType As TypeSymbol = typeParameterNode.InferredType If inferredType Is Nothing AndAlso (inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then succeeded = False End If If typeParameterNode.InferredTypeByAssumption Then If inferredTypeByAssumption.IsNull Then inferredTypeByAssumption = BitVector.Create(arity) End If inferredTypeByAssumption(i) = True End If inferredTypes(i) = inferredType inferredFromLocation(i) = typeParameterNode.InferredFromLocation Next typeArguments = inferredTypes.AsImmutableOrNull() typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull() inferenceLevel = graph._typeInferenceLevel Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic) diagnostic = graph.Diagnostic asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch useSiteInfo = graph.UseSiteInfo Return succeeded End Function Private Sub PopulateGraph() Dim candidate As MethodSymbol = Me.Candidate Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing) Dim argIndex As Integer For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then Continue For End If If Not isExpandedParamArrayForm Then argIndex = parameterToArgumentMap(paramIndex) Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex)) Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. '!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!! If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then Continue For End If RegisterArgument(paramArrayArgument, targetType, param) Else Debug.Assert(isExpandedParamArrayForm) '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form. ' Note, that explicitly converted NOTHING is treated the same way by Dev10. If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then Continue For End If ' Otherwise, for a ParamArray parameter, all the matching arguments are passed ' ByVal as instances of the element type of the ParamArray. ' Perform the conversions to the element type of the ParamArray here. Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then Continue For End If targetType = arrayType.ElementType If targetType.Kind = SymbolKind.ErrorType Then Continue For End If For j As Integer = 0 To paramArrayItems.Count - 1 Step 1 If arguments(paramArrayItems(j)).HasErrors Then Continue For End If RegisterArgument(arguments(paramArrayItems(j)), targetType, param) Next End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) Dim argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then Continue For End If RegisterArgument(argument, targetType, param) Next AddDelegateReturnTypeToGraph() End Sub Private Sub AddDelegateReturnTypeToGraph() If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax, Me.DelegateReturnType) Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing) ' Add the edges from all the current generic parameters to this named node. For Each current As InferenceNode In Vertices If current.NodeType = InferenceNodeType.TypeParameterNode Then AddEdge(current, returnNode) End If Next ' Add the edges from the resultType outgoing to the generic parameters. AddTypeToGraph(returnNode, isOutgoingEdge:=True) End If End Sub Private Sub RegisterArgument( argument As BoundExpression, targetType As TypeSymbol, param As ParameterSymbol ) ' Dig through parenthesized. If Not argument.IsNothingLiteral Then argument = argument.GetMostEnclosedParenthesizedExpression() End If Dim argNode As New ArgumentNode(Me, argument, targetType, param) Select Case argument.Kind Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda AddLambdaToGraph(argNode, argument.GetBinderFromLambda()) Case BoundKind.AddressOfOperator AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder) Case BoundKind.TupleLiteral AddTupleLiteralToGraph(argNode) Case Else AddTypeToGraph(argNode, isOutgoingEdge:=True) End Select End Sub Private Sub AddTypeToGraph( node As ArgumentNode, isOutgoingEdge As Boolean ) AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length)) End Sub Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode Dim ordinal As Integer = typeParameter.Ordinal If ordinal < _typeParameterNodes.Length AndAlso _typeParameterNodes(ordinal) IsNot Nothing AndAlso typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then Return _typeParameterNodes(ordinal) End If Return Nothing End Function Private Sub AddTypeToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, isOutgoingEdge As Boolean, ByRef haveSeenTypeParameters As BitVector ) Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter) If typeParameterNode IsNot Nothing AndAlso Not haveSeenTypeParameters(typeParameter.Ordinal) Then If typeParameterNode.Parameter Is Nothing Then typeParameterNode.SetParameter(argNode.Parameter) End If If (isOutgoingEdge) Then AddEdge(argNode, typeParameterNode) Else AddEdge(typeParameterNode, argNode) End If haveSeenTypeParameters(typeParameter.Ordinal) = True End If Case SymbolKind.ArrayType AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters) Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select End Sub Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode) AddTupleLiteralToGraph(argNode.ParameterType, argNode) End Sub Private Sub AddTupleLiteralToGraph( parameterType As TypeSymbol, argNode As ArgumentNode ) Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral) Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral) Dim tupleArguments = tupleLiteral.Arguments If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible For i As Integer = 0 To tupleArguments.Length - 1 RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter) Next Return End If AddTypeToGraph(argNode, isOutgoingEdge:=True) End Sub Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder) AddAddressOfToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddAddressOfToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator) If parameterType.IsTypeParameter() Then AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge haveSeenTypeParameters.Clear() For Each delegateParameter As ParameterSymbol In invoke.Parameters AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge Next End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder) AddLambdaToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddLambdaToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) If parameterType.IsTypeParameter() Then ' Lambda is bound to a generic typeParam, just infer anonymous delegate AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) Select Case argNode.Expression.Kind Case BoundKind.QueryLambda lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind) End Select Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1 If lambdaParameters(i).Type IsNot Nothing Then ' Prepopulate the hint from the lambda's parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. ' TODO: Consider using location for the type declaration. InferTypeArgumentsFromArgument( argNode.Expression.Syntax, lambdaParameters(i).Type, argumentTypeByAssumption:=False, parameterType:=delegateParameters(i).Type, param:=delegateParameters(i), digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) Next haveSeenTypeParameters.Clear() AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean Dim argumentType As TypeSymbol = argument.Type Dim isArrayLiteral As Boolean = False If argumentType Is Nothing Then If argument.Kind = BoundKind.ArrayLiteral Then isArrayLiteral = True argumentType = DirectCast(argument, BoundArrayLiteral).InferredType Else Return False End If End If While paramType.IsArrayType() If Not argumentType.IsArrayType() Then Return False End If Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol) ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If argumentArray.Rank <> paramArrayType.Rank OrElse (Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then Return False End If isArrayLiteral = False argumentType = argumentArray.ElementType paramType = paramArrayType.ElementType End While Return True End Function Public Sub RegisterTypeParameterHint( genericParameter As TypeParameterSymbol, inferredType As TypeSymbol, inferredTypeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter) If typeNode IsNot Nothing Then typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions) End If End Sub Private Function RefersToGenericParameterToInferArgumentFor( parameterType As TypeSymbol ) As Boolean Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter) ' TODO: It looks like this check can give us a false positive. For example, ' if we are resolving a recursive call we might already bind a type ' parameter to itself (to the same type parameter of the containing method). ' So, the fact that we ran into this type parameter doesn't necessary mean ' that there is anything to infer. I am not sure if this can lead to some ' negative effect. Dev10 appears to have the same behavior, from what I see ' in the code. If typeNode IsNot Nothing Then Return True End If Case SymbolKind.ArrayType Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes If RefersToGenericParameterToInferArgumentFor(elementType) Then Return True End If Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If RefersToGenericParameterToInferArgumentFor(typeArgument) Then Return True End If Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select Return False End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' If a generic method is parameterized by T, an argument of type A matches a parameter of type ' P, this function tries to infer type for T by using these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T Private Function InferTypeArgumentsFromArgumentDirectly( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If argumentType Is Nothing OrElse argumentType.IsVoidType() Then ' We should never be able to infer a value from something that doesn't provide a value, e.g: ' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar()) Return False End If ' If a generic method is parameterized by T, an argument of type A matching a parameter of type ' P can be used to infer a type for T by these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T ' -- If P is (T, T) and A is (X, X), then infer X for T If parameterType.IsTypeParameter() Then RegisterTypeParameterHint( DirectCast(parameterType, TypeParameterSymbol), argumentType, argumentTypeByAssumption, argumentLocation, param, False, inferenceRestrictions) Return True End If Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType). TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then If parameterElementTypes.Length <> argumentElementTypes.Length Then Return False End If For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1 Dim parameterElementType = parameterElementTypes(typeArgumentIndex) Dim argumentElementType = argumentElementTypes(typeArgumentIndex) ' propagate restrictions to the elements If Not InferTypeArgumentsFromArgument( argumentLocation, argumentElementType, argumentTypeByAssumption, parameterElementType, param, digThroughToBasesAndImplements, inferenceRestrictions ) Then Return False End If Next Return True ElseIf parameterType.Kind = SymbolKind.NamedType Then ' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T) Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol) If parameterTypeAsNamedType.IsGenericType Then Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing) If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then Do For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1 ' The following code is subtle. Let's recap what's going on... ' We've so far encountered some context, e.g. "_" or "ICovariant(_)" ' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions. ' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)" ' and we have to apply extra restrictions to each of those subcontexts. ' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint. ' For variant parameters it's more subtle. First, we have to strengthen the ' restrictions to require reference conversion (rather than just VB conversion or ' whatever it was). Second, if it was an In parameter, then we have to invert ' the sense. ' ' Processing of generics is tricky in the case that we've already encountered ' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction ' "AnyConversionAndReverse", so that the argument could be copied into the parameter ' and back again. But now consider if we find a generic inside that ByRef, e.g. ' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case ' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)". ' What's needed for any candidate for T is that G(Of Hint) be convertible to ' G(Of Candidate), and vice versa for the copyback. ' ' But then what should we write down for the hints? The problem is that hints inhere ' to the generic parameter T, not to the function parameter G(Of T). So we opt for a ' safe approximation: we just require CLR identity between a candidate and the hint. ' This is safe but is a little overly-strict. For example: ' Class G(Of T) ' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal) ' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T) ' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T) ' ... ' inf(New G(Of Car), New Animal) ' inf(Of Animal)(New G(Of Car), New Animal) ' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure, ' even though the explicitly-provided T=Animal ends up working. ' ' Well, it's the best we can do without some major re-architecting of the way ' hints and type-inference works. That's because all our hints inhere to the ' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter. ' But I don't think we'll ever do better than this, just because trying to do ' type inference inferring to arguments/parameters becomes exponential. ' Variance generic parameters will work the same. ' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction: Dim paramInferenceRestrictions As RequiredConversion Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance Case VarianceKind.In paramInferenceRestrictions = Conversions.InvertConversionRequirement( Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)) Case VarianceKind.Out paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions) Case Else Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance) paramInferenceRestrictions = RequiredConversion.Identity End Select Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter If paramInferenceRestrictions = RequiredConversion.Reference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter Else _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), argumentTypeByAssumption, parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), param, _DigThroughToBasesAndImplements, paramInferenceRestrictions ) Then ' TODO: Would it make sense to continue through other type arguments even if inference failed for ' the current one? Return False End If Next ' Do not forget about type parameters of containing type parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType Loop While parameterTypeAsNamedType IsNot Nothing Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing) Return True End If ElseIf parameterTypeAsNamedType.IsNullableType() Then ' we reach here when the ParameterType is an instantiation of Nullable, ' and the argument type is NOT a generic type. ' lwischik: ??? what do array elements have to do with nullables? Return InferTypeArgumentsFromArgument( argumentLocation, argumentType, argumentTypeByAssumption, parameterTypeAsNamedType.GetNullableUnderlyingType(), param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement)) End If Return False End If ElseIf parameterType.IsArrayType() Then If argumentType.IsArrayType() Then Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol) Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If parameterArray.Rank = argumentArray.Rank AndAlso (argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then Return InferTypeArgumentsFromArgument( argumentLocation, argumentArray.ElementType, argumentTypeByAssumption, parameterArray.ElementType, param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement))) End If End If Return False End If Return True End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))", ' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))". ' The task is to infer hints for T, e.g. "T=int". ' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _). ' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly" ' to do that. ' ' Note: this function returns "false" if it failed to pattern-match between argument and parameter type, ' and "true" if it succeeded. ' Success in pattern-matching may or may not produce type-hints for generic parameters. ' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced ' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints, ' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from ' here (to show success at pattern-matching) and leave the downstream code to produce an error message about ' failing to infer T. Friend Function InferTypeArgumentsFromArgument( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then Return True End If ' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable. Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) If Inferred Then Return True End If If parameterType.IsTypeParameter() Then ' If we failed to match an argument against a generic parameter T, it means that the ' argument was something unmatchable, e.g. an AddressOf. Return False End If ' If we didn't find a direct match, we will have to look in base classes for a match. ' We'll either fix ParameterType and look amongst the bases of ArgumentType, ' or we'll fix ArgumentType and look amongst the bases of ParameterType, ' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by ' covariance and contravariance... If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then Return False End If ' Special handling for Anonymous Delegates. If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso (inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse inferenceRestrictions = RequiredConversion.AnyAndReverse) Then Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol) Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType) ' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type. If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then ' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type. ' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g. ' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer) ' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T)) ' // maybe defined as Delegate Function D(Of T)(x as T) as T. ' We're looking to achieve the same functionality in pattern-matching these types as we already ' have for calling "inf(function(i as integer) i)" directly. ' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions). ' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more. ' And it does allow a function BaseSearchType to be used for a sub FixedType. ' ' Anyway, the plan is to match each of the parameters in the ArgumentType delegate ' to the equivalent parameters in the ParameterType delegate, and also match the return types. ' ' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for ' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed ' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed ' with some inferred types, for the sake of better error messages, even though we know that ultimately ' it will fail (because no non-anonymous delegate type can be converted to a delegate type). Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then ' If parameter-counts are mismatched then it's a failure. ' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument ' to be supplied to a function which expects a parameterfull delegate. Return False End If ' First we'll check that the argument types all match. For i As Integer = 0 To argumentParams.Length - 1 If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then ' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works. Return False End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentParams(i).Type, argumentTypeByAssumption, parameterParams(i).Type, param, MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments Return False End If Next ' Now check that the return type matches. ' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate. If parameterInvokeProc.IsSub Then ' A *sub* delegate parameter can accept either a *function* or a *sub* argument: Return True ElseIf argumentInvokeProc.IsSub Then ' A *function* delegate parameter cannot accept a *sub* argument. Return False Else ' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter: Return InferTypeArgumentsFromArgument( argumentLocation, argumentInvokeProc.ReturnType, argumentTypeByAssumption, parameterInvokeProc.ReturnType, param, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, RequiredConversion.Any) ' Any: covariance in delegate returns End If End If End If ' MatchBaseOfGenericArgumentToParameter: used for covariant situations, ' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)". ' ' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations, ' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))". Dim fContinue As Boolean = False If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then fContinue = FindMatchingBase(argumentType, parameterType) Else fContinue = FindMatchingBase(parameterType, argumentType) End If If Not fContinue Then Return False End If ' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType. ' Therefore the above statement has altered either ArgumentType or ParameterType. Return InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) End Function Private Function FindMatchingBase( ByRef baseSearchType As TypeSymbol, ByRef fixedType As TypeSymbol ) As Boolean Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing) If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then ' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList), ' then we won't learn anything about generic type parameters here: Return False End If Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then ' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface. ' (it's impossible to inherit from anything else). Return False End If Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then ' The things listed above are the only ones that have bases that could ever lead anywhere useful. ' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes. Return False End If If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then ' If the types checked were already identical, then exit Return False End If ' Otherwise, if we got through all the above tests, then it really is worth searching through the base ' types to see if that helps us find a match. Dim matchingBase As TypeSymbol = Nothing If fixedTypeTypeKind = TypeKind.Class Then FindMatchingBaseClass(baseSearchType, fixedType, matchingBase) Else Debug.Assert(fixedTypeTypeKind = TypeKind.Interface) FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase) End If If matchingBase Is Nothing Then Return False End If ' And this is what we found baseSearchType = matchingBase Return True End Function Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean If match Is Nothing Then match = type Return True ElseIf match.IsSameTypeIgnoringAll(type) Then Return True Else match = Nothing Return False End If End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then Return False End If Next Case Else For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual([interface], match) Then Return False End If End If Next End Select Return True End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If ' TODO: Do we need to continue even if we already have a matching base class? ' It looks like Dev10 continues. If Not FindMatchingBaseClass(constraint, baseClass, match) Then Return False End If Next Case Else Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) While baseType IsNot Nothing If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(baseType, match) Then Return False End If Exit While End If baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) End While End Select Return True End Function Public Function InferTypeArgumentsFromAddressOfArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean If parameterType.IsDelegateType() Then Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return False End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim addrOf = DirectCast(argument, BoundAddressOfOperator) Dim fromMethod As MethodSymbol = Nothing Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed( addrOf, invokeMethod, ignoreMethodReturnType:=True, diagnostics:=BindingDiagnosticBag.Discarded) fromMethod = matchingMethod.Key methodConversions = matchingMethod.Value If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse (addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then Return False End If If fromMethod.IsSub Then ReportNotFailedInferenceDueToObject() Return True End If Dim targetReturnType As TypeSymbol = fromMethod.ReturnType If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then ' Return false if we didn't make any inference progress. Return False End If Return InferTypeArgumentsFromArgument( argument.Syntax, targetReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) End If ' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. ReportNotFailedInferenceDueToObject() Return True End Function Public Function InferTypeArgumentsFromLambdaArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse argument.Kind = BoundKind.QueryLambda OrElse argument.Kind = BoundKind.GroupTypeInferenceLambda) If parameterType.IsTypeParameter() Then Dim anonymousLambdaType As TypeSymbol = Nothing Select Case argument.Kind Case BoundKind.QueryLambda ' Do not infer Anonymous Delegate type from query lambda. Case BoundKind.GroupTypeInferenceLambda ' Can't infer from this lambda. Case BoundKind.UnboundLambda ' Infer Anonymous Delegate type from unbound lambda. Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then Dim delegateInvokeMethod As MethodSymbol = Nothing If inferredAnonymousDelegate.Key IsNot Nothing Then delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod End If If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then anonymousLambdaType = inferredAnonymousDelegate.Key End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If anonymousLambdaType IsNot Nothing Then Return InferTypeArgumentsFromArgument( argument.Syntax, anonymousLambdaType, argumentTypeByAssumption:=False, parameterType:=parameterType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) Else Return True End If ElseIf parameterType.IsDelegateType() Then Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. ' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to ' infer more stuff from other non-lambda arguments, we might have a better chance to have ' more type information for the lambda, allowing successful lambda interpretation. ' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters ' are inferred. Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return True End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim lambdaParams As ImmutableArray(Of ParameterSymbol) Select Case argument.Kind Case BoundKind.QueryLambda lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParams = DirectCast(argument, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters If lambdaParams.Length > delegateParams.Length Then Return True End If For i As Integer = 0 To lambdaParams.Length - 1 Step 1 Dim lambdaParam As ParameterSymbol = lambdaParams(i) Dim delegateParam As ParameterSymbol = delegateParams(i) If lambdaParam.Type Is Nothing Then ' If a lambda parameter has no type and the delegate parameter refers ' to an unbound generic parameter, we can't infer yet. If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then ' Skip this type argument and other parameters will infer it or ' if that doesn't happen it will report an error. ' TODO: Why does it make sense to continue here? It looks like we can infer something from ' lambda's return type based on incomplete information. Also, this 'if' is redundant, ' there is nothing left to do in this loop anyway, and "continue" doesn't change anything. Continue For End If Else ' report the type of the lambda parameter to the delegate parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. InferTypeArgumentsFromArgument( argument.Syntax, lambdaParam.Type, argumentTypeByAssumption:=False, parameterType:=delegateParam.Type, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If Next ' OK, now try to infer delegates return type from the lambda. Dim lambdaReturnType As TypeSymbol Select Case argument.Kind Case BoundKind.QueryLambda Dim queryLambda = DirectCast(argument, BoundQueryLambda) lambdaReturnType = queryLambda.LambdaSymbol.ReturnType If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then lambdaReturnType = queryLambda.Expression.Type If lambdaReturnType Is Nothing Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Debug.Assert(Me.Diagnostic IsNot Nothing) lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type End If End If Case BoundKind.GroupTypeInferenceLambda lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams) Case BoundKind.UnboundLambda Dim unboundLambda = DirectCast(argument, UnboundLambda) If unboundLambda.IsFunctionLambda Then Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False) Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature) If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then lambdaReturnType = Nothing ' Let's keep return type inference errors If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then lambdaReturnType = Nothing Else Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes, inferenceSignature.ParameterIsByRef, returnTypeInfo.Key, returnsByRef:=False)) Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then lambdaReturnType = returnTypeInfo.Key ' Let's keep return type inference warnings, if any. If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies) Else lambdaReturnType = Nothing ' Let's preserve diagnostics that caused the failure If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(boundLambda.Diagnostics) End If End If End If ' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter ' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T... If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then ' By this stage we know that ' * we have an async/iterator lambda argument ' * the parameter-to-match is a delegate type whose result type refers to generic parameters ' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have ' to dig in. Or it might be a delegate with result type "T" in which case we ' don't dig in. Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol) Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol) If lambdaReturnNamedType.Arity = 1 AndAlso IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition, returnNamedType.OriginalDefinition) Then ' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T) ' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation. Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything)) lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) End If End If Else lambdaReturnType = Nothing If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then If _asyncLambdaSubToFunctionMismatch Is Nothing Then _asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance) End If _asyncLambdaSubToFunctionMismatch.Add(unboundLambda) End If End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If lambdaReturnType Is Nothing Then ' Inference failed, give up. Return False End If If lambdaReturnType.IsErrorType() Then Return True End If ' Now infer from the result type ' not ArgumentTypeByAssumption ??? lwischik: but maybe it should... Return InferTypeArgumentsFromArgument( argument.Syntax, lambdaReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param) End If Return True End Function Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. Dim methodSymbol As MethodSymbol = Candidate Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length) For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1 Dim typeNode As TypeParameterNode = _typeParameterNodes(i) Dim newType As TypeSymbol If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then 'No substitution newType = methodSymbol.TypeParameters(i) Else newType = typeNode.CandidateInferredType End If typeArguments.Add(New TypeWithModifiers(newType)) Next Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree()) ' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type End Function Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list") ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub ReportIncompatibleInferenceError( typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) If typeInfos.Count < 1 Then Return End If ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons) _inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasic/EndConstructGeneration/VisualBasicEndConstructGenerationService.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 System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration <ExportLanguageService(GetType(IEndConstructGenerationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEndConstructService Implements IEndConstructGenerationService Private ReadOnly _smartIndentationService As ISmartIndentationService Private ReadOnly _undoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Private ReadOnly _editorOptionsFactoryService As IEditorOptionsFactoryService <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New( smartIndentationService As ISmartIndentationService, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService, editorOptionsFactoryService As IEditorOptionsFactoryService) ThrowIfNull(smartIndentationService) ThrowIfNull(undoHistoryRegistry) ThrowIfNull(editorOperationsFactoryService) ThrowIfNull(editorOptionsFactoryService) _smartIndentationService = smartIndentationService _undoHistoryRegistry = undoHistoryRegistry _editorOperationsFactoryService = editorOperationsFactoryService _editorOptionsFactoryService = editorOptionsFactoryService End Sub Private Shared Function IsMissingStatementError(statement As SyntaxNode, [error] As String) As Boolean Select Case [error] ' TODO(jasonmal): get rid of this. It is an open design goal to move missing end errors from the ' statement to the block. Besides making incremental parsing easier, it will also clean this mess up. ' Until then, I'm content with this hack. Case "BC30012" ' Missing #End If Return True Case "BC30481" ' Missing End Class Return True Case "BC30625" ' Missing End Module Return True Case "BC30185" ' Missing End Enum Return True Case "BC30253" ' Missing End Interface Return True Case "BC30624" ' Missing End Structure Return True Case "BC30626" ' Missing End Namespace Return True Case "BC30026" ' Missing End Sub Return True Case "BC30027" ' Missing End Function Return True Case "BC30631" ' Missing End Get Return True Case "BC30633" ' Missing End Set Return True Case "BC30025" ' Missing End Property Return True Case "BC30081" ' Missing End If Return True Case "BC30082" ' Missing End While Return True Case "BC30083" ' Missing Loop Return True Case "BC30084" ' Missing Next Return True Case "BC30085" ' Missing End With Return True Case "BC30095" ' Missing End Select Return True Case "BC36008" ' Missing End Using Return True Case "BC30675" ' Missing End SyncLock Return True Case "BC30681" ' Missing #End Region Return True Case "BC33005" ' Missing End Operator Return True Case "BC36759" ' Auto-implemented properties cannot have parameters Return True Case "BC36673" ' Missing End Sub for Lambda Return True Case "BC36674" ' Missing End Function for Lambda Return True Case "BC30384" ' Missing End Try Return True Case "BC30198", "BC30199" ' These happen if I type Dim x = Function without parenthesis, so as long as we are in that content, ' count this as an acceptable error. Return TypeOf statement Is LambdaHeaderSyntax Case "BC31114" ' Missing End Event Return True End Select Return False End Function Private Shared Function IsExpectedXmlNameError([error] As String) As Boolean Return [error] = "BC31146" End Function Private Shared Function IsMissingXmlEndTagError([error] As String) As Boolean Return [error] = "BC31151" End Function Private Shared Function IsExpectedXmlEndEmbeddedError([error] As String) As Boolean Return [error] = "BC31159" End Function Private Shared Function IsExpectedXmlEndPIError([error] As String) As Boolean Return [error] = "BC31160" End Function Private Shared Function IsExpectedXmlEndCommentError([error] As String) As Boolean Return [error] = "BC31161" End Function Private Shared Function IsExpectedXmlEndCDataError([error] As String) As Boolean Return [error] = "BC31162" End Function Private Function GetEndConstructState(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As EndConstructState Dim caretPosition = textView.GetCaretPoint(subjectBuffer) If caretPosition Is Nothing Then Return Nothing End If Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return Nothing End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim tokenToLeft = tree.FindTokenOnLeftOfPosition(caretPosition.Value, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True) If tokenToLeft.Kind = SyntaxKind.None Then Return Nothing End If Dim bufferOptions = _editorOptionsFactoryService.GetOptions(subjectBuffer) Return New EndConstructState( caretPosition.Value, New Lazy(Of SemanticModel)(Function() document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken)), tree, tokenToLeft, bufferOptions.GetNewLineCharacter()) End Function Friend Overridable Function TryDoEndConstructForEnterKey(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_DoStatement, cancellationToken) Using transaction = New CaretPreservingEditTransaction(VBEditorResources.End_Construct, textView, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance ' The user may have some text selected. In this scenario, we want to guarantee ' two things: ' ' 1) the text that was selected is deleted, as a normal pressing of an enter key ' would do. Since we're not letting the editor do it's own thing during end ' construct generation, we need to make sure the selection is deleted. ' 2) that we compute what statements we should spit assuming the selected text ' is no longer there. Consider a scenario where the user has something like: ' ' If True Then ~~~~ ' ' and the completely invalid "~~~~" is selected. In VS2010, if you pressed ' enter, we would still spit enter, since we effectively view that code as ' "no longer there." ' ' The fix is simple: as a part of our transaction, we'll just delete anything ' under our selection. As long as our transaction goes through, the user won't ' suspect anything was fishy. If we don't spit, we'll cancel the transaction ' which will roll back this edit. _editorOperationsFactoryService.GetEditorOperations(textView).ReplaceSelection("") Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If ' Are we in the middle of XML tags? If state.TokenToLeft.Kind = SyntaxKind.GreaterThanToken Then Dim element = state.TokenToLeft.GetAncestor(Of XmlElementSyntax) If element IsNot Nothing Then If element.StartTag IsNot Nothing AndAlso element.StartTag.Span.End = state.CaretPosition AndAlso element.EndTag IsNot Nothing AndAlso element.EndTag.SpanStart = state.CaretPosition Then InsertBlankLineBetweenXmlTags(state, textView, subjectBuffer) transaction.Complete() Return True End If End If End If ' Figure out which statement that is to the left of us Dim statement = state.TokenToLeft.FirstAncestorOrSelf(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is DirectiveTriviaSyntax) ' Make sure we are after the last token of the statement or ' if the statement is a single-line If statement that ' we're after the "Then" or "Else" token. If statement Is Nothing Then Return False ElseIf statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) If state.TokenToLeft <> asSingleLine.ThenKeyword AndAlso (asSingleLine.ElseClause Is Nothing OrElse state.TokenToLeft <> asSingleLine.ElseClause.ElseKeyword) Then Return False End If ElseIf statement.GetLastToken() <> state.TokenToLeft Then Return False End If ' Make sure we were on the same line as the last token. Dim caretLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.CaretPosition) Dim lineOfLastToken = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.TokenToLeft.SpanStart) If caretLine <> lineOfLastToken Then Return False End If ' Make sure that we don't have any skipped trivia between our target token and ' the end of the line Dim nextToken = state.TokenToLeft.GetNextTokenOrEndOfFile() Dim nextTokenLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(nextToken.SpanStart) If nextToken.IsKind(SyntaxKind.EndOfFileToken) AndAlso nextTokenLine = caretLine Then If nextToken.LeadingTrivia.Any(Function(trivia) trivia.IsKind(SyntaxKind.SkippedTokensTrivia)) Then Return False End If End If ' If this is an Imports or Implements declaration, we should use the enclosing type declaration. If TypeOf statement Is InheritsOrImplementsStatementSyntax Then Dim baseDeclaration = DirectCast(statement, InheritsOrImplementsStatementSyntax) Dim typeBlock = baseDeclaration.GetAncestor(Of TypeBlockSyntax)() If typeBlock Is Nothing Then Return False End If statement = typeBlock.BlockStatement End If If statement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(statement) If errors.Any(Function(e) Not IsMissingStatementError(statement, e.Id)) Then If statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) Dim span = TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End) If errors.Any(Function(e) span.Contains(e.Location.SourceSpan)) Then Return False End If Else Return False End If End If ' Make sure this statement does not end with the line continuation character If statement.GetLastToken(includeZeroWidth:=True).TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) Then Return False End If Dim visitor = New EndConstructStatementVisitor(textView, subjectBuffer, state, cancellationToken) Dim result = visitor.Visit(statement) If result Is Nothing Then Return False End If result.Apply(textView, subjectBuffer, state.CaretPosition, _smartIndentationService, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.Complete() End Using End Using Return True End Function Private Sub InsertBlankLineBetweenXmlTags(state As EndConstructState, textView As ITextView, subjectBuffer As ITextBuffer) ' Add an extra newline first Using edit = subjectBuffer.CreateEdit() Dim aligningWhitespace = subjectBuffer.CurrentSnapshot.GetAligningWhitespace(state.TokenToLeft.Parent.Span.Start) edit.Insert(state.CaretPosition, state.NewLineCharacter + aligningWhitespace) edit.ApplyAndLogExceptions() End Using ' And now just send down a normal enter textView.TryMoveCaretToAndEnsureVisible(New SnapshotPoint(subjectBuffer.CurrentSnapshot, state.CaretPosition)) _editorOperationsFactoryService.GetEditorOperations(textView).InsertNewLine() End Sub Private Shared Function GetNodeFromToken(Of T As SyntaxNode)(token As SyntaxToken, expectedKind As SyntaxKind) As T If token.Kind <> expectedKind Then Return Nothing End If Return TryCast(token.Parent, T) End Function Private Shared Function InsertEndTextAndUpdateCaretPosition( view As ITextView, insertPosition As Integer, caretPosition As Integer, endText As String, cancellationToken As CancellationToken ) As Boolean Dim document = view.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If document.Project.Solution.Workspace.ApplyTextChanges( document.Id, SpecializedCollections.SingletonEnumerable( New TextChange(New TextSpan(insertPosition, 0), endText)), cancellationToken) Dim caretPosAfterEdit = New SnapshotPoint(view.TextSnapshot, caretPosition) view.TryMoveCaretToAndEnsureVisible(caretPosAfterEdit) Return True End Function Friend Function TryDoXmlCDataEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlCData, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlCData = GetNodeFromToken(Of XmlCDataSectionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.BeginCDataToken) If xmlCData Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlCData) ' Exactly one error is expected: ERRID_ExpectedXmlEndCData If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCDataError(errors(0).Id) Then Return False End If Dim endText = "]]>" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Friend Function TryDoXmlCommentEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlComment, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlComment = GetNodeFromToken(Of XmlCommentSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanExclamationMinusMinusToken) If xmlComment Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlComment) ' Exactly one error is expected: ERRID_ExpectedXmlEndComment If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCommentError(errors(0).Id) Then Return False End If Dim endText = "-->" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Friend Function TryDoXmlElementEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlElement, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlStartElement = GetNodeFromToken(Of XmlElementStartTagSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.GreaterThanToken) If xmlStartElement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlStartElement) ' Exactly one error is expected: ERRID_MissingXmlEndTag If errors.Count <> 1 Then Return False End If If Not IsMissingXmlEndTagError(errors(0).Id) Then Return False End If Dim endTagText = "</" & xmlStartElement.Name.ToString & ">" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endTagText, cancellationToken) End Using End Function Friend Function TryDoXmlEmbeddedExpressionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlEmbeddedExpression, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlEmbeddedExpression = GetNodeFromToken(Of XmlEmbeddedExpressionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanPercentEqualsToken) If xmlEmbeddedExpression Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlEmbeddedExpression) ' Errors should contain ERRID_ExpectedXmlEndEmbedded If Not errors.Any(Function(e) IsExpectedXmlEndEmbeddedError(e.Id)) Then Return False End If Dim endText = " %>" ' NOTE: two spaces are inserted. The caret will be moved between them Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End + 1, endText, cancellationToken) End Using End Function Friend Function TryDoXmlProcessingInstructionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlProcessingInstruction, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlProcessingInstruction = GetNodeFromToken(Of XmlProcessingInstructionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanQuestionToken) If xmlProcessingInstruction Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlProcessingInstruction) ' Exactly two errors are expected: ERRID_ExpectedXmlName and ERRID_ExpectedXmlEndPI If errors.Count <> 2 Then Return False End If If Not (errors.Any(Function(e) IsExpectedXmlNameError(e.Id)) AndAlso errors.Any(Function(e) IsExpectedXmlEndPIError(e.Id))) Then Return False End If Dim endText = "?>" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Public Function TryDo(textView As ITextView, subjectBuffer As ITextBuffer, typedChar As Char, cancellationToken As CancellationToken) As Boolean Implements IEndConstructGenerationService.TryDo Select Case typedChar Case vbLf(0) Return Me.TryDoEndConstructForEnterKey(textView, subjectBuffer, cancellationToken) Case ">"c Return Me.TryDoXmlElementEndConstruct(textView, subjectBuffer, cancellationToken) Case "-"c Return Me.TryDoXmlCommentEndConstruct(textView, subjectBuffer, cancellationToken) Case "="c Return Me.TryDoXmlEmbeddedExpressionEndConstruct(textView, subjectBuffer, cancellationToken) Case "["c Return Me.TryDoXmlCDataEndConstruct(textView, subjectBuffer, cancellationToken) Case "?"c Return Me.TryDoXmlProcessingInstructionEndConstruct(textView, subjectBuffer, cancellationToken) End Select Return False 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 System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration <ExportLanguageService(GetType(IEndConstructGenerationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEndConstructService Implements IEndConstructGenerationService Private ReadOnly _smartIndentationService As ISmartIndentationService Private ReadOnly _undoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Private ReadOnly _editorOptionsFactoryService As IEditorOptionsFactoryService <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New( smartIndentationService As ISmartIndentationService, undoHistoryRegistry As ITextUndoHistoryRegistry, editorOperationsFactoryService As IEditorOperationsFactoryService, editorOptionsFactoryService As IEditorOptionsFactoryService) ThrowIfNull(smartIndentationService) ThrowIfNull(undoHistoryRegistry) ThrowIfNull(editorOperationsFactoryService) ThrowIfNull(editorOptionsFactoryService) _smartIndentationService = smartIndentationService _undoHistoryRegistry = undoHistoryRegistry _editorOperationsFactoryService = editorOperationsFactoryService _editorOptionsFactoryService = editorOptionsFactoryService End Sub Private Shared Function IsMissingStatementError(statement As SyntaxNode, [error] As String) As Boolean Select Case [error] ' TODO(jasonmal): get rid of this. It is an open design goal to move missing end errors from the ' statement to the block. Besides making incremental parsing easier, it will also clean this mess up. ' Until then, I'm content with this hack. Case "BC30012" ' Missing #End If Return True Case "BC30481" ' Missing End Class Return True Case "BC30625" ' Missing End Module Return True Case "BC30185" ' Missing End Enum Return True Case "BC30253" ' Missing End Interface Return True Case "BC30624" ' Missing End Structure Return True Case "BC30626" ' Missing End Namespace Return True Case "BC30026" ' Missing End Sub Return True Case "BC30027" ' Missing End Function Return True Case "BC30631" ' Missing End Get Return True Case "BC30633" ' Missing End Set Return True Case "BC30025" ' Missing End Property Return True Case "BC30081" ' Missing End If Return True Case "BC30082" ' Missing End While Return True Case "BC30083" ' Missing Loop Return True Case "BC30084" ' Missing Next Return True Case "BC30085" ' Missing End With Return True Case "BC30095" ' Missing End Select Return True Case "BC36008" ' Missing End Using Return True Case "BC30675" ' Missing End SyncLock Return True Case "BC30681" ' Missing #End Region Return True Case "BC33005" ' Missing End Operator Return True Case "BC36759" ' Auto-implemented properties cannot have parameters Return True Case "BC36673" ' Missing End Sub for Lambda Return True Case "BC36674" ' Missing End Function for Lambda Return True Case "BC30384" ' Missing End Try Return True Case "BC30198", "BC30199" ' These happen if I type Dim x = Function without parenthesis, so as long as we are in that content, ' count this as an acceptable error. Return TypeOf statement Is LambdaHeaderSyntax Case "BC31114" ' Missing End Event Return True End Select Return False End Function Private Shared Function IsExpectedXmlNameError([error] As String) As Boolean Return [error] = "BC31146" End Function Private Shared Function IsMissingXmlEndTagError([error] As String) As Boolean Return [error] = "BC31151" End Function Private Shared Function IsExpectedXmlEndEmbeddedError([error] As String) As Boolean Return [error] = "BC31159" End Function Private Shared Function IsExpectedXmlEndPIError([error] As String) As Boolean Return [error] = "BC31160" End Function Private Shared Function IsExpectedXmlEndCommentError([error] As String) As Boolean Return [error] = "BC31161" End Function Private Shared Function IsExpectedXmlEndCDataError([error] As String) As Boolean Return [error] = "BC31162" End Function Private Function GetEndConstructState(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As EndConstructState Dim caretPosition = textView.GetCaretPoint(subjectBuffer) If caretPosition Is Nothing Then Return Nothing End If Dim document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return Nothing End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim tokenToLeft = tree.FindTokenOnLeftOfPosition(caretPosition.Value, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True) If tokenToLeft.Kind = SyntaxKind.None Then Return Nothing End If Dim bufferOptions = _editorOptionsFactoryService.GetOptions(subjectBuffer) Return New EndConstructState( caretPosition.Value, New Lazy(Of SemanticModel)(Function() document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken)), tree, tokenToLeft, bufferOptions.GetNewLineCharacter()) End Function Friend Overridable Function TryDoEndConstructForEnterKey(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_DoStatement, cancellationToken) Using transaction = New CaretPreservingEditTransaction(VBEditorResources.End_Construct, textView, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance ' The user may have some text selected. In this scenario, we want to guarantee ' two things: ' ' 1) the text that was selected is deleted, as a normal pressing of an enter key ' would do. Since we're not letting the editor do it's own thing during end ' construct generation, we need to make sure the selection is deleted. ' 2) that we compute what statements we should spit assuming the selected text ' is no longer there. Consider a scenario where the user has something like: ' ' If True Then ~~~~ ' ' and the completely invalid "~~~~" is selected. In VS2010, if you pressed ' enter, we would still spit enter, since we effectively view that code as ' "no longer there." ' ' The fix is simple: as a part of our transaction, we'll just delete anything ' under our selection. As long as our transaction goes through, the user won't ' suspect anything was fishy. If we don't spit, we'll cancel the transaction ' which will roll back this edit. _editorOperationsFactoryService.GetEditorOperations(textView).ReplaceSelection("") Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If ' Are we in the middle of XML tags? If state.TokenToLeft.Kind = SyntaxKind.GreaterThanToken Then Dim element = state.TokenToLeft.GetAncestor(Of XmlElementSyntax) If element IsNot Nothing Then If element.StartTag IsNot Nothing AndAlso element.StartTag.Span.End = state.CaretPosition AndAlso element.EndTag IsNot Nothing AndAlso element.EndTag.SpanStart = state.CaretPosition Then InsertBlankLineBetweenXmlTags(state, textView, subjectBuffer) transaction.Complete() Return True End If End If End If ' Figure out which statement that is to the left of us Dim statement = state.TokenToLeft.FirstAncestorOrSelf(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is DirectiveTriviaSyntax) ' Make sure we are after the last token of the statement or ' if the statement is a single-line If statement that ' we're after the "Then" or "Else" token. If statement Is Nothing Then Return False ElseIf statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) If state.TokenToLeft <> asSingleLine.ThenKeyword AndAlso (asSingleLine.ElseClause Is Nothing OrElse state.TokenToLeft <> asSingleLine.ElseClause.ElseKeyword) Then Return False End If ElseIf statement.GetLastToken() <> state.TokenToLeft Then Return False End If ' Make sure we were on the same line as the last token. Dim caretLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.CaretPosition) Dim lineOfLastToken = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(state.TokenToLeft.SpanStart) If caretLine <> lineOfLastToken Then Return False End If ' Make sure that we don't have any skipped trivia between our target token and ' the end of the line Dim nextToken = state.TokenToLeft.GetNextTokenOrEndOfFile() Dim nextTokenLine = subjectBuffer.CurrentSnapshot.GetLineNumberFromPosition(nextToken.SpanStart) If nextToken.IsKind(SyntaxKind.EndOfFileToken) AndAlso nextTokenLine = caretLine Then If nextToken.LeadingTrivia.Any(Function(trivia) trivia.IsKind(SyntaxKind.SkippedTokensTrivia)) Then Return False End If End If ' If this is an Imports or Implements declaration, we should use the enclosing type declaration. If TypeOf statement Is InheritsOrImplementsStatementSyntax Then Dim baseDeclaration = DirectCast(statement, InheritsOrImplementsStatementSyntax) Dim typeBlock = baseDeclaration.GetAncestor(Of TypeBlockSyntax)() If typeBlock Is Nothing Then Return False End If statement = typeBlock.BlockStatement End If If statement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(statement) If errors.Any(Function(e) Not IsMissingStatementError(statement, e.Id)) Then If statement.Kind = SyntaxKind.SingleLineIfStatement Then Dim asSingleLine = DirectCast(statement, SingleLineIfStatementSyntax) Dim span = TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End) If errors.Any(Function(e) span.Contains(e.Location.SourceSpan)) Then Return False End If Else Return False End If End If ' Make sure this statement does not end with the line continuation character If statement.GetLastToken(includeZeroWidth:=True).TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) Then Return False End If Dim visitor = New EndConstructStatementVisitor(textView, subjectBuffer, state, cancellationToken) Dim result = visitor.Visit(statement) If result Is Nothing Then Return False End If result.Apply(textView, subjectBuffer, state.CaretPosition, _smartIndentationService, _undoHistoryRegistry, _editorOperationsFactoryService) transaction.Complete() End Using End Using Return True End Function Private Sub InsertBlankLineBetweenXmlTags(state As EndConstructState, textView As ITextView, subjectBuffer As ITextBuffer) ' Add an extra newline first Using edit = subjectBuffer.CreateEdit() Dim aligningWhitespace = subjectBuffer.CurrentSnapshot.GetAligningWhitespace(state.TokenToLeft.Parent.Span.Start) edit.Insert(state.CaretPosition, state.NewLineCharacter + aligningWhitespace) edit.ApplyAndLogExceptions() End Using ' And now just send down a normal enter textView.TryMoveCaretToAndEnsureVisible(New SnapshotPoint(subjectBuffer.CurrentSnapshot, state.CaretPosition)) _editorOperationsFactoryService.GetEditorOperations(textView).InsertNewLine() End Sub Private Shared Function GetNodeFromToken(Of T As SyntaxNode)(token As SyntaxToken, expectedKind As SyntaxKind) As T If token.Kind <> expectedKind Then Return Nothing End If Return TryCast(token.Parent, T) End Function Private Shared Function InsertEndTextAndUpdateCaretPosition( view As ITextView, insertPosition As Integer, caretPosition As Integer, endText As String, cancellationToken As CancellationToken ) As Boolean Dim document = view.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If document.Project.Solution.Workspace.ApplyTextChanges( document.Id, SpecializedCollections.SingletonEnumerable( New TextChange(New TextSpan(insertPosition, 0), endText)), cancellationToken) Dim caretPosAfterEdit = New SnapshotPoint(view.TextSnapshot, caretPosition) view.TryMoveCaretToAndEnsureVisible(caretPosAfterEdit) Return True End Function Friend Function TryDoXmlCDataEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlCData, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlCData = GetNodeFromToken(Of XmlCDataSectionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.BeginCDataToken) If xmlCData Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlCData) ' Exactly one error is expected: ERRID_ExpectedXmlEndCData If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCDataError(errors(0).Id) Then Return False End If Dim endText = "]]>" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Friend Function TryDoXmlCommentEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlComment, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlComment = GetNodeFromToken(Of XmlCommentSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanExclamationMinusMinusToken) If xmlComment Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlComment) ' Exactly one error is expected: ERRID_ExpectedXmlEndComment If errors.Count <> 1 Then Return False End If If Not IsExpectedXmlEndCommentError(errors(0).Id) Then Return False End If Dim endText = "-->" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Friend Function TryDoXmlElementEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlElement, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlStartElement = GetNodeFromToken(Of XmlElementStartTagSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.GreaterThanToken) If xmlStartElement Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlStartElement) ' Exactly one error is expected: ERRID_MissingXmlEndTag If errors.Count <> 1 Then Return False End If If Not IsMissingXmlEndTagError(errors(0).Id) Then Return False End If Dim endTagText = "</" & xmlStartElement.Name.ToString & ">" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endTagText, cancellationToken) End Using End Function Friend Function TryDoXmlEmbeddedExpressionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlEmbeddedExpression, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlEmbeddedExpression = GetNodeFromToken(Of XmlEmbeddedExpressionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanPercentEqualsToken) If xmlEmbeddedExpression Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlEmbeddedExpression) ' Errors should contain ERRID_ExpectedXmlEndEmbedded If Not errors.Any(Function(e) IsExpectedXmlEndEmbeddedError(e.Id)) Then Return False End If Dim endText = " %>" ' NOTE: two spaces are inserted. The caret will be moved between them Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End + 1, endText, cancellationToken) End Using End Function Friend Function TryDoXmlProcessingInstructionEndConstruct(textView As ITextView, subjectBuffer As ITextBuffer, cancellationToken As CancellationToken) As Boolean Using Logger.LogBlock(FunctionId.EndConstruct_XmlProcessingInstruction, cancellationToken) Dim state = GetEndConstructState(textView, subjectBuffer, cancellationToken) If state Is Nothing Then Return False End If Dim xmlProcessingInstruction = GetNodeFromToken(Of XmlProcessingInstructionSyntax)(state.TokenToLeft, expectedKind:=SyntaxKind.LessThanQuestionToken) If xmlProcessingInstruction Is Nothing Then Return False End If Dim errors = state.SyntaxTree.GetDiagnostics(xmlProcessingInstruction) ' Exactly two errors are expected: ERRID_ExpectedXmlName and ERRID_ExpectedXmlEndPI If errors.Count <> 2 Then Return False End If If Not (errors.Any(Function(e) IsExpectedXmlNameError(e.Id)) AndAlso errors.Any(Function(e) IsExpectedXmlEndPIError(e.Id))) Then Return False End If Dim endText = "?>" Return InsertEndTextAndUpdateCaretPosition(textView, state.CaretPosition, state.TokenToLeft.Span.End, endText, cancellationToken) End Using End Function Public Function TryDo(textView As ITextView, subjectBuffer As ITextBuffer, typedChar As Char, cancellationToken As CancellationToken) As Boolean Implements IEndConstructGenerationService.TryDo Select Case typedChar Case vbLf(0) Return Me.TryDoEndConstructForEnterKey(textView, subjectBuffer, cancellationToken) Case ">"c Return Me.TryDoXmlElementEndConstruct(textView, subjectBuffer, cancellationToken) Case "-"c Return Me.TryDoXmlCommentEndConstruct(textView, subjectBuffer, cancellationToken) Case "="c Return Me.TryDoXmlEmbeddedExpressionEndConstruct(textView, subjectBuffer, cancellationToken) Case "["c Return Me.TryDoXmlCDataEndConstruct(textView, subjectBuffer, cancellationToken) Case "?"c Return Me.TryDoXmlProcessingInstructionEndConstruct(textView, subjectBuffer, cancellationToken) End Select Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent Public Class GenerateEventCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a(x As Integer) Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>public interface i { event gooEventHandler goo; } public delegate void gooEventHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a as EventHandler Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>using System; public interface i { event EventHandler goo; }</text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> <WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")> Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c WithEvents field as Program Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public class Program { } </Document> </Project> </Workspace> Dim expected = <text>public class Program { public event EvHandler Ev; } public delegate void EvHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function #Disable Warning CA2243 ' Attribute string literals should parse correctly <WorkItem(144843, "Generate method stub generates into *.Designer.cs")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task #Enable Warning CA2243 ' Attribute string literals should parse correctly Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document> Class c WithEvents field as UserControl1 Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> <Document FilePath="UserControl1.Designer.vb"> ' This file is auto-generated Partial Class UserControl1 End Class </Document> <Document FilePath="UserControl1.vb"> Partial Public Class UserControl1 End Class </Document> </Project> </Workspace> Dim expectedFileWithText = New Dictionary(Of String, String) From { {"UserControl1.vb", <Text> Partial Public Class UserControl1 Public Event Ev(x As Integer) End Class </Text>.Value.Trim()}, {"UserControl1.Designer.vb", <Text> ' This file is auto-generated Partial Class UserControl1 End Class </Text>.Value.Trim()} } Await TestAsync(input, fileNameToExpected:=expectedFileWithText) 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent Public Class GenerateEventCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a(x As Integer) Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>public interface i { event gooEventHandler goo; } public delegate void gooEventHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c Implements i Event a as EventHandler Implements $$i.goo End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public interface i { } </Document> </Project> </Workspace> Dim expected = <text>using System; public interface i { event EventHandler goo; }</text>.Value.Trim() Await TestAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> <WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")> Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class c WithEvents field as Program Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true"> <Document FilePath=<%= DestinationDocument %>> public class Program { } </Document> </Project> </Workspace> Dim expected = <text>public class Program { public event EvHandler Ev; } public delegate void EvHandler(int x); </text>.Value.Trim() Await TestAsync(input, expected) End Function #Disable Warning CA2243 ' Attribute string literals should parse correctly <WorkItem(144843, "Generate method stub generates into *.Designer.cs")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)> Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task #Enable Warning CA2243 ' Attribute string literals should parse correctly Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document> Class c WithEvents field as UserControl1 Sub Goo(x as Integer) Handles field.Ev$$ End Sub End Class </Document> <Document FilePath="UserControl1.Designer.vb"> ' This file is auto-generated Partial Class UserControl1 End Class </Document> <Document FilePath="UserControl1.vb"> Partial Public Class UserControl1 End Class </Document> </Project> </Workspace> Dim expectedFileWithText = New Dictionary(Of String, String) From { {"UserControl1.vb", <Text> Partial Public Class UserControl1 Public Event Ev(x As Integer) End Class </Text>.Value.Trim()}, {"UserControl1.Designer.vb", <Text> ' This file is auto-generated Partial Class UserControl1 End Class </Text>.Value.Trim()} } Await TestAsync(input, fileNameToExpected:=expectedFileWithText) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDynamicMemberReferenceExpression.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 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_SimplePropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F'BIND:"d.F" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F(Of String)'BIND:"d.F(Of String)" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F(Of String)') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F(Of String)') Type Arguments(1): Symbol: System.String Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_InvalidGenericPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F(Of)'BIND:"d.F(Of)" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.F(Of)') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsInvalid) (Syntax: 'd.F(Of)') Type Arguments(1): Symbol: ? Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. d.F(Of)'BIND:"d.F(Of)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_SimpleMethodCall() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F()'BIND:"d.F()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F()') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_InvalidMethodCall_MissingParen() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F('BIND:"d.F(" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.F(') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30198: ')' expected. d.F('BIND:"d.F(" ~ BC30201: Expression expected. d.F('BIND:"d.F(" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_SingleGeneric() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String)()'BIND:"d.GetValue(Of String)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.GetValue(Of String)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.GetValue(Of String)') Type Arguments(1): Symbol: System.String Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_MultipleGeneric() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String, Integer)()'BIND:"d.GetValue(Of String, Integer)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.GetValue( ... Integer)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.GetValue( ... g, Integer)') Type Arguments(2): Symbol: System.String Symbol: System.Int32 Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_InvalidGenericParameter() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String,)()'BIND:"d.GetValue(Of String,)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.GetValue(Of String,)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsInvalid) (Syntax: 'd.GetValue(Of String,)') Type Arguments(2): Symbol: System.String Symbol: ? Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. d.GetValue(Of String,)()'BIND:"d.GetValue(Of String,)()" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Prop1.Prop2'BIND:"d.Prop1.Prop2" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Prop1.Prop2') Expression: IDynamicMemberReferenceOperation (Member Name: "Prop2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1.Prop2') Type Arguments(0) Instance Receiver: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedMethodAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Method1().Method2()'BIND:"d.Method1().Method2()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Method1().Method2()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Method1().Method2') Type Arguments(0) Instance Receiver: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Method1()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Method1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedPropertyAndMethodAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Prop1.Method2()'BIND:"d.Prop1.Method2()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Prop1.Method2()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1.Method2') Type Arguments(0) Instance Receiver: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_LateBoundModuleFunction() Dim source = <![CDATA[ Option Strict Off Imports System.Collections.Generic Module Module1 Sub Main() Dim x As Object = New List(Of Integer)() fun(x)'BIND:"fun(x)" End Sub Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'fun(x)') Expression: IDynamicMemberReferenceOperation (Member Name: "fun", Containing Type: Module1) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'fun') Type Arguments(0) Instance Receiver: null Arguments(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_LateBoundClassFunction() Dim source = <![CDATA[ Option Strict Off Imports System.Collections.Generic Module Module1 Sub Main() Dim x As Object = New List(Of Integer)() Dim c1 As New C1 c1.fun(x)'BIND:"c1.fun(x)" End Sub Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'c1.fun(x)') Expression: IDynamicMemberReferenceOperation (Member Name: "fun", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'c1.fun') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Module1.C1) (Syntax: 'c1') Arguments(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_NoControlFlow() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d As Object, p As Object)'BIND:"Private Sub M(d As Object, p As Object)" p = d.Prop1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = d.Prop1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = d.Prop1') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d1 As Object, d2 As Object, p As Object)'BIND:"Private Sub M(d1 As Object, d2 As Object, p As Object)" p = If(d1, d2).Prop1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(d1, d2).Prop1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = If(d1, d2).Prop1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'If(d1, d2).Prop1') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(d1, d2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_ControlFlowInReceiver_TypeArguments() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d1 As Object, d2 As Object, p As Object)'BIND:"Private Sub M(d1 As Object, d2 As Object, p As Object)" p = If(d1, d2).Prop1(Of Integer) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(d1, ... Of Integer)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = If(d1, ... Of Integer)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'If(d1, d2). ... Of Integer)') Type Arguments(1): Symbol: System.Int32 Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(d1, d2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(27034, "https://github.com/dotnet/roslyn/issues/27034")> <Fact()> Public Sub DynamicMemberReference_OffObjectCollectionInitializer() Dim source = <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Module Mod1 Class C Implements IEnumerable(Of Integer) Sub M(a As Object, b As Object) Dim i = New C From {a}.Add(b)'BIND:"New C From {a}.Add" End Sub Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(i As Integer) End Sub Public Sub Add(l As Long) End Sub End Class End Module]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedOperationTree = <![CDATA[ IDynamicMemberReferenceOperation (Member Name: "Add", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'New C From {a}.Add') Type Arguments(0) Instance Receiver: IObjectCreationOperation (Constructor: Sub Mod1.C..ctor()) (OperationKind.ObjectCreation, Type: Mod1.C) (Syntax: 'New C From {a}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Mod1.C) (Syntax: 'From {a}') Initializers(1): IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsImplicit) (Syntax: 'a') Expression: IDynamicMemberReferenceOperation (Member Name: "Add", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsImplicit) (Syntax: 'a') Type Arguments(0) Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Mod1.C, IsImplicit) (Syntax: 'New C From {a}') Arguments(1): IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, 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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_SimplePropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F'BIND:"d.F" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F(Of String)'BIND:"d.F(Of String)" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F(Of String)') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F(Of String)') Type Arguments(1): Symbol: System.String Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_InvalidGenericPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F(Of)'BIND:"d.F(Of)" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.F(Of)') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsInvalid) (Syntax: 'd.F(Of)') Type Arguments(1): Symbol: ? Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. d.F(Of)'BIND:"d.F(Of)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_SimpleMethodCall() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F()'BIND:"d.F()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.F()') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_InvalidMethodCall_MissingParen() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.F('BIND:"d.F(" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.F(') Expression: IDynamicMemberReferenceOperation (Member Name: "F", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.F') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30198: ')' expected. d.F('BIND:"d.F(" ~ BC30201: Expression expected. d.F('BIND:"d.F(" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_SingleGeneric() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String)()'BIND:"d.GetValue(Of String)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.GetValue(Of String)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.GetValue(Of String)') Type Arguments(1): Symbol: System.String Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_MultipleGeneric() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String, Integer)()'BIND:"d.GetValue(Of String, Integer)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.GetValue( ... Integer)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.GetValue( ... g, Integer)') Type Arguments(2): Symbol: System.String Symbol: System.Int32 Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_GenericMethodCall_InvalidGenericParameter() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.GetValue(Of String,)()'BIND:"d.GetValue(Of String,)()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsInvalid) (Syntax: 'd.GetValue(Of String,)()') Expression: IDynamicMemberReferenceOperation (Member Name: "GetValue", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsInvalid) (Syntax: 'd.GetValue(Of String,)') Type Arguments(2): Symbol: System.String Symbol: ? Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. d.GetValue(Of String,)()'BIND:"d.GetValue(Of String,)()" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedPropertyAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Prop1.Prop2'BIND:"d.Prop1.Prop2" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Prop1.Prop2') Expression: IDynamicMemberReferenceOperation (Member Name: "Prop2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1.Prop2') Type Arguments(0) Instance Receiver: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedMethodAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Method1().Method2()'BIND:"d.Method1().Method2()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Method1().Method2()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Method1().Method2') Type Arguments(0) Instance Receiver: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Method1()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Method1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_NestedPropertyAndMethodAccess() Dim source = <![CDATA[ Option Strict Off Module Program Sub Main(args As String()) Dim d = Nothing d.Prop1.Method2()'BIND:"d.Prop1.Method2()" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'd.Prop1.Method2()') Expression: IDynamicMemberReferenceOperation (Member Name: "Method2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1.Method2') Type Arguments(0) Instance Receiver: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: System.Object) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_LateBoundModuleFunction() Dim source = <![CDATA[ Option Strict Off Imports System.Collections.Generic Module Module1 Sub Main() Dim x As Object = New List(Of Integer)() fun(x)'BIND:"fun(x)" End Sub Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'fun(x)') Expression: IDynamicMemberReferenceOperation (Member Name: "fun", Containing Type: Module1) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'fun') Type Arguments(0) Instance Receiver: null Arguments(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IDynamicMemberReferenceExpression_LateBoundClassFunction() Dim source = <![CDATA[ Option Strict Off Imports System.Collections.Generic Module Module1 Sub Main() Dim x As Object = New List(Of Integer)() Dim c1 As New C1 c1.fun(x)'BIND:"c1.fun(x)" End Sub Class C1 Sub fun(Of X)(ByVal a As List(Of X)) End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'c1.fun(x)') Expression: IDynamicMemberReferenceOperation (Member Name: "fun", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'c1.fun') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Module1.C1) (Syntax: 'c1') Arguments(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_NoControlFlow() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d As Object, p As Object)'BIND:"Private Sub M(d As Object, p As Object)" p = d.Prop1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = d.Prop1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = d.Prop1') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'd.Prop1') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d1 As Object, d2 As Object, p As Object)'BIND:"Private Sub M(d1 As Object, d2 As Object, p As Object)" p = If(d1, d2).Prop1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(d1, d2).Prop1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = If(d1, d2).Prop1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'If(d1, d2).Prop1') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(d1, d2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub DynamicMemberReference_ControlFlowInReceiver_TypeArguments() Dim source = <![CDATA[ Option Strict Off Class C Private Sub M(d1 As Object, d2 As Object, p As Object)'BIND:"Private Sub M(d1 As Object, d2 As Object, p As Object)" p = If(d1, d2).Prop1(Of Integer) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(d1, ... Of Integer)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'p = If(d1, ... Of Integer)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p') Right: IDynamicMemberReferenceOperation (Member Name: "Prop1", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'If(d1, d2). ... Of Integer)') Type Arguments(1): Symbol: System.Int32 Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(d1, d2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(27034, "https://github.com/dotnet/roslyn/issues/27034")> <Fact()> Public Sub DynamicMemberReference_OffObjectCollectionInitializer() Dim source = <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Module Mod1 Class C Implements IEnumerable(Of Integer) Sub M(a As Object, b As Object) Dim i = New C From {a}.Add(b)'BIND:"New C From {a}.Add" End Sub Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(i As Integer) End Sub Public Sub Add(l As Long) End Sub End Class End Module]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedOperationTree = <![CDATA[ IDynamicMemberReferenceOperation (Member Name: "Add", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'New C From {a}.Add') Type Arguments(0) Instance Receiver: IObjectCreationOperation (Constructor: Sub Mod1.C..ctor()) (OperationKind.ObjectCreation, Type: Mod1.C) (Syntax: 'New C From {a}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Mod1.C) (Syntax: 'From {a}') Initializers(1): IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object, IsImplicit) (Syntax: 'a') Expression: IDynamicMemberReferenceOperation (Member Name: "Add", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object, IsImplicit) (Syntax: 'a') Type Arguments(0) Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Mod1.C, IsImplicit) (Syntax: 'New C From {a}') Arguments(1): IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a') ArgumentNames(0) ArgumentRefKinds: null ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/VisualBasicTest/Structure/ConstructorDeclarationStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class ConstructorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SubNewStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ConstructorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor1() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor2() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor3() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} ' .ctor End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestPrivateConstructor() As Task Const code = " Class C1 {|span:Private Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Private Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructorWithComments() As Task Const code = " Class C1 {|span1:'My 'Constructor|} {|span2:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span1", "' My ...", autoCollapse:=True), Region("span2", "Sub New() ...", autoCollapse:=True)) 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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class ConstructorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SubNewStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ConstructorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor1() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor2() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructor3() As Task Const code = " Class C1 {|span:Sub $$New() End Sub|} ' .ctor End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestPrivateConstructor() As Task Const code = " Class C1 {|span:Private Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Private Sub New() ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestConstructorWithComments() As Task Const code = " Class C1 {|span1:'My 'Constructor|} {|span2:Sub $$New() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span1", "' My ...", autoCollapse:=True), Region("span2", "Sub New() ...", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Symbol/SymbolDisplay/SymbolDisplayTests.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 System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolDisplayTests Inherits BasicTestBase <Fact> Public Sub TestClassNameOnlySimple() Dim text = <compilation> <file name="a.vb"> class A end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly) TestSymbolDescription( text, findSymbol, format, "A", {SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestClassNameOnlyComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() End Function Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly) TestSymbolDescription( text, findSymbol, format, "C2", {SymbolDisplayPartKind.ClassName}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes) TestSymbolDescription( text, findSymbol, format, "C1.C2", {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "N1.N2.N3.C1.C2", {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestFullyQualifiedFormat() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() End Function TestSymbolDescription( text, findSymbol, SymbolDisplayFormat.FullyQualifiedFormat, "Global.N1.N2.N3.C1.C2", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestMethodNameOnlySimple() Dim text = <compilation> <file name="a.vb"> class A Sub M() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat() TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMethodNameOnlyComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 public shared function M(nullable x as integer, c as C1) as Integer() end function end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat() TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestClassNameOnlyWithKindSimple() Dim text = <compilation> <file name="a.vb"> class A end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, kindOptions:=SymbolDisplayKindOptions.IncludeTypeKeyword) TestSymbolDescription( text, findSymbol, format, "Class A", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestClassWithKindComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("A").Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, kindOptions:=SymbolDisplayKindOptions.IncludeTypeKeyword) TestSymbolDescription( text, findSymbol, format, "Class N1.N2.N3.A", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestNamespaceWithKindSimple() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, kindOptions:=SymbolDisplayKindOptions.IncludeNamespaceKeyword) TestSymbolDescription( text, findSymbol, format, "Namespace N3", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName}) End Sub <Fact()> Public Sub TestNamespaceWithKindComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, kindOptions:=SymbolDisplayKindOptions.IncludeNamespaceKeyword) TestSymbolDescription( text, findSymbol, format, "Namespace N1.N2.N3", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}) End Sub <Fact()> Public Sub TestMethodAndParamsSimple() Dim text = <compilation> <file name="a.vb"> class A Private sub M() End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Private Sub M()", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeType, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "M()", {SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMethodAndParamsComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 public shared function M(x? as integer, c as C1) as Integer() end function end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Shared Function M(x As Integer?, c As C1) As Integer()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact> Public Sub TestExtensionMethodAsStatic() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.StaticMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1(Of TSource).M(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestExtensionMethodAsDefault() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.Default, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestIrreducibleExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource As Structure)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim c2Type = globalns.GetTypeMember("C2") Dim method = c2Type.GetMember(Of MethodSymbol)("M") Return method.Construct(c2Type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of C2)(source As C1(Of C2), index As Integer) As C2", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsStatic() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.StaticMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1, index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1.M(Of TSource)(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsDefault() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.Default, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1.M(Of TSource)(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact()> Public Sub TestNothingParameters() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format As SymbolDisplayFormat = Nothing ' default is show asterisks for VB. If this is changed, this test will fail ' in this case, please rewrite the test TestNoArrayAsterisks to TestArrayAsterisks TestSymbolDescription( text, findSymbol, format, "Public f As Integer()(*,*)(*,*,*)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestArrayRank() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "f As Integer()(,)(,,)", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestEscapeKeywordIdentifiers() Dim text = <compilation> <file name="a.vb"> namespace N1 class [Integer] Class [class] Shared Sub [shared]([boolean] As System.String) If [boolean] Then Console.WriteLine("true") Else Console.WriteLine("false") End If End Sub End Class End Class end namespace namespace [Global] namespace [Integer] end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("Integer").Single(). GetTypeMembers("class").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' no escaping because N1 does not need to be escaped TestSymbolDescription( text, findSymbol, format, "N1.Integer.class", { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' outer class needs escaping TestSymbolDescription( text, findSymbol, format, "[Integer].class", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' outer class needs escaping TestSymbolDescription( text, findSymbol, format, "[class]", { SymbolDisplayPartKind.ClassName }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("Integer").Single(). GetTypeMembers("class").Single().GetMembers("shared").Single() format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' actual test case from bug 4389 TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As System.String)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' making sure that types still get escaped if no special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As [String])", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) ' making sure that types don't get escaped if special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As String)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"Global"}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' making sure that types don't get escaped if special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "[Global]", { SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global.Global", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) findSymbol = Function(globalns) globalns ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global", { SymbolDisplayPartKind.Keyword }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"Global"}).LookupNestedNamespace({"Integer"}) ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global.Global.Integer", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "[Global].Integer", { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "[Integer]", { SymbolDisplayPartKind.NamespaceName }) End Sub <Fact()> Public Sub AlwaysEscapeMethodNamedNew() Dim text = <compilation> <file name="a.vb"> Class C Sub [New]() End Sub End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' The method should be escaped TestSymbolDescription( text, Function(globalns As NamespaceSymbol) globalns.GetTypeMembers("C").Single().GetMembers("New").Single(), format, "C.[New]", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName }) ' The constructor should not TestSymbolDescription( text, Function(globalns As NamespaceSymbol) globalns.GetTypeMembers("C").Single().InstanceConstructors.Single(), format, "C.New", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Keyword }) End Sub <Fact()> Public Sub TestExplicitMethodImplNameOnly() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "I_M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestExplicitMethodImplNameAndInterface() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeExplicitInterface) TestSymbolDescription( text, findSymbol, format, "I_M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestExplicitMethodImplNameAndInterfaceAndType() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeContainingType) TestSymbolDescription( text, findSymbol, format, "C.I_M", {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestGlobalNamespaceCode() Dim text = <compilation> <file name="a.vb"> Class C end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included) TestSymbolDescription( text, findSymbol, format, "Global.C", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestGlobalNamespaceHumanReadable() Dim text = <compilation> <file name="a.vb"> Class C End Class namespace [Global] end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included) TestSymbolDescription( text, findSymbol, format, "Global", {SymbolDisplayPartKind.Keyword}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "Global", {SymbolDisplayPartKind.Keyword}) End Sub <Fact()> Public Sub TestSpecialTypes() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "f As Integer", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword }) End Sub <Fact()> Public Sub TestNoArrayAsterisks() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.None) TestSymbolDescription( text, findSymbol, format, "f As Int32()(,)(,,)", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestMetadataMethodNames() Dim text = <compilation> <file name="a.vb"> Class C New C() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers(".ctor").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) TestSymbolDescription( text, findSymbol, format, "Sub .ctor", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestArityForGenericTypes() Dim text = <compilation> <file name="a.vb"> Class C(Of T, U, V) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes) TestSymbolDescription( text, findSymbol, format, "C`3", { SymbolDisplayPartKind.ClassName, InternalSymbolDisplayPartKind.Arity}) End Sub <Fact()> Public Sub TestGenericTypeParameters() Dim text = <compilation> <file name="a.vb"> Class C(Of In T, Out U, V) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "C(Of T, U, V)", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericTypeParametersAndVariance() Dim text = <compilation> <file name="a.vb"> Interface I(Of In T, Out U, V) End Interface </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("I") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance) TestSymbolDescription( text, findSymbol, format, "I(Of In T, Out U, V)", { SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericTypeConstraints() Dim text = <compilation> <file name="a.vb"> Class C(Of T As C(Of T)) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) TestSymbolDescription( text, findSymbol, format, "C(Of T As C(Of T))", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodParameters() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(Of In T, Out U, V)() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "M(Of T, U, V)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodParametersAndVariance() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(Of In T, Out U, V)() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance) TestSymbolDescription( text, findSymbol, format, "M(Of T, U, V)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodConstraints() Dim text = <compilation> <file name="a.vb"> Class C(Of T) Public Sub M(Of U, V As {T, Class, U})() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) TestSymbolDescription( text, findSymbol, format, "M(Of U, V As {Class, T, U})", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Sub M(p as Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMemberMethodAll() Dim text = <compilation> <file name="a.vb"> Class C Sub M(p as Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Public Sub C.M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethodAll() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Public Declare Unicode Sub C.M Lib ""goo"" ()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethod_NoType() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters) TestSymbolDescription( text, findSymbol, format, "Public C.M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethod_NoAccessibility_NoContainingType_NoParameters() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" Alias "bar" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Declare Unicode Sub M Lib ""goo"" Alias ""bar""", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral}) End Sub <Fact()> Public Sub TestMemberDeclareMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "M", { SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMemberFieldNone() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "f", {SymbolDisplayPartKind.FieldName}) End Sub <Fact()> Public Sub TestMemberFieldAll() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType) TestSymbolDescription( text, findSymbol, format, "Private C.f As Int32", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact> Public Sub TestConstantFieldValue() Dim text = <compilation> <file name="a.vb"> Class C Const f As Integer = 1 End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As Int32 = 1", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact> Public Sub TestConstantFieldValue_EnumMember() Dim text = <compilation> <file name="a.vb"> Enum E A B C End Enum Class C Const f As E = E.B End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As E = E.B", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestConstantFieldValue_EnumMember_Flags() Dim text = <compilation> <file name="a.vb"> &lt;System.FlagsAttribute&gt; Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum Class C Const f As E = E.D End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As E = E.D", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestEnumMember() Dim text = <compilation> <file name="a.vb"> Enum E A B C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("B").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.B = 1", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact> Public Sub TestEnumMember_Flags() Dim text = <compilation> <file name="a.vb"> &lt;System.FlagsAttribute&gt; Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("D").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.D = E.A Or E.B Or E.C", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestEnumMember_FlagsWithoutAttribute() Dim text = <compilation> <file name="a.vb"> Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("D").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.D = 7", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact()> Public Sub TestMemberPropertyNone() Dim text = <compilation> <file name="c.vb"> Class C Private ReadOnly Property P As Integer Get Return 0 End Get End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("P").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "P", {SymbolDisplayPartKind.PropertyName}) End Sub <Fact()> Public Sub TestMemberPropertyAll() Dim text = <compilation> <file name="c.vb"> Class C Public Default Readonly Property P(x As Object) as Integer Get return 23 End Get End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Public Default Property C.P(x As Object) As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestMemberPropertyGetSet() Dim text = <compilation> <file name="c.vb"> Class C Public ReadOnly Property P as integer Get Return 0 End Get End Property Public WriteOnly Property Q Set End Set End Property Public Property R End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:=SymbolDisplayPropertyStyle.ShowReadWriteDescriptor) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("P").Single(), format, "ReadOnly Property P As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("Q").Single(), format, "WriteOnly Property Q As Object", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName }) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("R").Single(), format, "Property R As Object", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName }) End Sub <Fact()> Public Sub TestPropertyGetAccessor() Dim text = <compilation> <file name="c.vb"> Class C Private Property P As Integer Get Return 0 End Get Set End Set End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("get_P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private Property Get C.P() As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private C.P() As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestPropertySetAccessor() Dim text = <compilation> <file name="c.vb"> Class C Private WriteOnly Property P As Integer Set End Set End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("set_P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private Property Set C.P(Value As Int32)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestParameterMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Sub M(obj as object, byref s as short, i as integer = 1) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.None) TestSymbolDescription( text, findSymbol, format, "M()", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterBrackets() Dim text = <compilation> <file name="a.vb"> Class C Sub M(Optional i As Integer = 0) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeOptionalBrackets) TestSymbolDescription( text, findSymbol, format, "M([i As Int32])", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterValue_String() Dim text = <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Class C Sub M(Optional s As String = ChrW(&amp;HFFFE) &amp; "a" &amp; ChrW(0) &amp; vbCrLf) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue) TestSymbolDescription( text, findSymbol, format, "M(s As String = ChrW(&HFFFE) & ""a"" & vbNullChar & vbCrLf)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterValue_Char() Dim text = <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Class C Sub M(Optional a As Char = ChrW(&amp;HFFFE), Optional b As Char = ChrW(8)) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue) TestSymbolDescription( text, findSymbol, format, "M(a As Char = ChrW(&HFFFE), b As Char = vbBack)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestOptionalParameterValue_InvariantCulture1() Dim text = <compilation> <file name="a.vb"> Class C Sub M( Optional p1 as SByte = -1, Optional p2 as Short = -1, Optional p3 as Integer = -1, Optional p4 as Long = -1, Optional p5 as Single = -0.5, Optional p6 as Double = -0.5, Optional p7 as Decimal = -0.5) End Sub End Class </file> </compilation> Dim oldCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CType(oldCulture.Clone(), CultureInfo) Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~" Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "," Dim Compilation = CreateCompilationWithMscorlib40(text) Compilation.VerifyDiagnostics() Dim methodSymbol = Compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Assert.Equal("Sub C.M(" + "[p1 As System.SByte = -1], " + "[p2 As System.Int16 = -1], " + "[p3 As System.Int32 = -1], " + "[p4 As System.Int64 = -1], " + "[p5 As System.Single = -0.5], " + "[p6 As System.Double = -0.5], " + "[p7 As System.Decimal = -0.5])", methodSymbol.ToTestDisplayString()) Finally Thread.CurrentThread.CurrentCulture = oldCulture End Try End Sub <Fact()> Public Sub TestOptionalParameterValue_InvariantCulture() Dim text = <compilation> <file name="a.vb"> Class C Sub M( Optional p1 as SByte = -1, Optional p2 as Short = -1, Optional p3 as Integer = -1, Optional p4 as Long = -1, Optional p5 as Single = -0.5, Optional p6 as Double = -0.5, Optional p7 as Decimal = -0.5) End Sub End Class </file> </compilation> Dim oldCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CType(oldCulture.Clone(), CultureInfo) Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~" Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "," Dim Compilation = CreateCompilationWithMscorlib40(text) Compilation.VerifyDiagnostics() Dim methodSymbol = Compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Assert.Equal("Sub C.M(" + "[p1 As System.SByte = -1], " + "[p2 As System.Int16 = -1], " + "[p3 As System.Int32 = -1], " + "[p4 As System.Int64 = -1], " + "[p5 As System.Single = -0.5], " + "[p6 As System.Double = -0.5], " + "[p7 As System.Decimal = -0.5])", methodSymbol.ToTestDisplayString()) Finally Thread.CurrentThread.CurrentCulture = oldCulture End Try End Sub <Fact()> Public Sub TestMethodReturnType1() Dim text = <compilation> <file name="a.vb"> Class C shared function M() as Integer End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Function M() As System.Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestMethodReturnType2() Dim text = <compilation> <file name="a.vb"> Class C shared sub M() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Sub M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestParameterMethodNameTypeModifiers() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(byref s as short, i as integer , ParamArray args as string()) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "M(ByRef s As Int16, i As Int32, ParamArray args As String())", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) ' Without SymbolDisplayParameterOptions.IncludeParamsRefOut. TestSymbolDescription( text, findSymbol, format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName), "M(s As Int16, i As Int32, args As String())", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) ' Without SymbolDisplayParameterOptions.IncludeType. TestSymbolDescription( text, findSymbol, format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeName), "M(ByRef s, i, ParamArray args)", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation) End Sub ' "Public" and "MustOverride" should not be included for interface members. <Fact()> Public Sub TestInterfaceMembers() Dim text = <compilation> <file name="a.vb"> Interface I Property P As Integer Function F() As Object End Interface MustInherit Class C MustOverride Function F() As Object Interface I Sub M() End Interface End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:= SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("I", 0).Single().GetMembers("P").Single(), format, "Property P As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("I", 0).Single().GetMembers("F").Single(), format, "Function F() As Object") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("F").Single(), format, "Public MustOverride Function F() As Object") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetTypeMembers("I", 0).Single().GetMember(Of MethodSymbol)("M"), format, "Sub M()") End Sub ' "Shared" should not be included for Module members. <Fact()> Public Sub TestSharedMembers() Dim text = <compilation> <file name="a.vb"> Class C Shared Sub M() End Sub Public Shared F As Integer Public Shared P As Object End Class Module M Sub M() End Sub Public F As Integer Public P As Object End Module </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M"), format, "Public Shared Sub M()") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("F").Single(), format, "Public Shared F As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("P").Single(), format, "Public Shared P As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMember(Of MethodSymbol)("M"), format, "Public Sub M()") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMembers("F").Single(), format, "Public F As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMembers("P").Single(), format, "Public P As Object") End Sub <WorkItem(540253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540253")> <Fact()> Public Sub TestOverloads() Dim text = <compilation> <file name="a.vb"> MustInherit Class B Protected MustOverride Overloads Function M(s As Single) Overloads Sub M() End Sub Friend NotOverridable Overloads WriteOnly Property P(x) Set(value) End Set End Property Overloads ReadOnly Property P(x, y) Get Return Nothing End Get End Property Public Overridable Overloads ReadOnly Property Q Get Return Nothing End Get End Property End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:= SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions:= SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType) TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("M").First(), format, "Protected MustOverride Overloads Function M(s As Single) As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("P").First(), format, "Friend NotOverridable Overloads WriteOnly Property P(x As Object) As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("Q").First(), format, "Public Overridable Overloads ReadOnly Property Q As Object") End Sub <Fact> Public Sub TestAlias1() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3 Namespace N1 NAmespace N2 NAmespace N3 class C1 class C2 End class End class ENd namespace end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "Goo.C1.C2", code.IndexOf("Namespace", StringComparison.Ordinal), { SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestAlias2() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3.C1 Namespace N1 NAmespace N2 NAmespace N3 class C1 class C2 End class End class ENd namespace end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "Goo.C2", code.IndexOf("Namespace", StringComparison.Ordinal), { SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestAlias3() Dim text = <compilation> <file name="a.vb">Imports Goo = N1.C1 Namespace N1 Class C1 End Class Class Goo End Class end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("C1").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = SymbolDisplayFormat.MinimallyQualifiedFormat TestSymbolDescription( text, findSymbol, format, "C1", code.IndexOf("Class Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestMinimalNamespace1() Dim text = <compilation> <file name="a.vb"> Imports Microsoft Imports OUTER namespace N0 end namespace namespace N1 namespace N2 namespace N3 class C1 class C2 end class end class end namespace end namespace end namespace Module Program Sub Main(args As String()) Dim x As Microsoft.VisualBasic.Collection Dim y As OUTER.INNER.GOO End Sub End Module Namespace OUTER Namespace INNER Friend Class GOO End Class End Namespace End Namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) End Function Dim format = New SymbolDisplayFormat() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, format, "N1.N2.N3", code.IndexOf("N0", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N1.N2.N3", text.Value.IndexOf("N1", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N2.N3", text.Value.IndexOf("N2", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N3", text.Value.IndexOf("C1", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N3", text.Value.IndexOf("C2", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName}, True) Dim findGOO As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"OUTER"}). LookupNestedNamespace({"INNER"}).GetTypeMembers("Goo").Single() End Function TestSymbolDescription(text, findGOO, format, "INNER.GOO", text.Value.IndexOf("OUTER.INNER.GOO", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) Dim findCollection As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"Microsoft"}). LookupNestedNamespace({"VisualBasic"}).GetTypeMembers("Collection").Single() End Function TestSymbolDescription(text, findCollection, format, "VisualBasic.Collection", text.Value.IndexOf("Microsoft.VisualBasic.Collection", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=True, references:={SystemRef, MsvbRef}) End Sub <Fact> Public Sub TestMinimalClass1() Dim text = <compilation> <file name="a.vb"> imports System.Collections.Generic class C1 Dim Private goo as System.Collections.Generic.IDictionary(Of System.Collections.Generic.IList(Of System.Int32), System.String) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "C1.goo As IDictionary(Of IList(Of Integer), String)", code.IndexOf("goo", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact()> Public Sub TestRemoveAttributeSuffix1() Dim text = <compilation> <file name="a.vb"> Class Class1Attribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Class1Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "Class1Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "Class1", code.IndexOf("Inherits System.Attribute", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <Fact> Public Sub TestRemoveAttributeSuffix2() Dim text = <compilation> <file name="a.vb"> Class ClassAttribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("ClassAttribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "ClassAttribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "ClassAttribute", SymbolDisplayPartKind.ClassName) End Sub <Fact> Public Sub TestRemoveAttributeSuffix3() Dim text = <compilation> <file name="a.vb"> Class _Attribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("_Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "_Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "_Attribute", SymbolDisplayPartKind.ClassName) End Sub <Fact> Public Sub TestRemoveAttributeSuffix4() Dim text = <compilation> <file name="a.vb"> Class Class1Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Class1Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "Class1Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "Class1Attribute", SymbolDisplayPartKind.ClassName) End Sub <WorkItem(537447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537447")> <Fact> Public Sub TestBug2239() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3 class GC1(Of T) end class class X inherits GC1(Of BOGUS) End class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("X").Single.BaseType Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "GC1(Of BOGUS)", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ErrorTypeName, SymbolDisplayPartKind.Punctuation}) End Sub <WorkItem(538954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538954")> <Fact> Public Sub ParameterOptionsIncludeName() Dim text = <compilation> <file name="a.vb"> Class Class1 Sub Sub1(ByVal param1 As Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim sub1 = CType(globalns.GetTypeMembers("Class1").Single().GetMembers("Sub1").Single(), MethodSymbol) Return sub1.Parameters.Single() End Function Dim format = New SymbolDisplayFormat(parameterOptions:=SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "param1", {SymbolDisplayPartKind.ParameterName}) End Sub <WorkItem(539076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539076")> <Fact> Public Sub Bug4878() Dim text = <compilation> <file name="a.vb"> Namespace Global Namespace Global ' invalid because nested, would need escaping Public Class c1 End Class End Namespace End Namespace </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Assert.Equal("[Global]", comp.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString()) Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) Assert.Equal("Global.Global", comp.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString(format)) Assert.Equal("Global.Global.c1", comp.SourceModule.GlobalNamespace.LookupNestedNamespace({"Global"}).GetTypeMembers.Single().ToDisplayString(format)) End Sub <WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")> <Fact> Public Sub Bug7515() Dim text = <compilation> <file name="a.vb"> Public Class C1 Delegate Sub MyDel(x as MyDel) End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim m_DelegateSignatureFormat As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.GlobalNamespaceStyle, typeQualificationStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.MemberOptions, parameterOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.LocalOptions, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword Or SymbolDisplayKindOptions.IncludeNamespaceKeyword Or SymbolDisplayKindOptions.IncludeTypeKeyword, delegateStyle:=SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.MiscellaneousOptions) Assert.Equal("Delegate Sub C1.MyDel(x As C1.MyDel)", comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single(). GetMembers("MyDel").Single().ToDisplayString(m_DelegateSignatureFormat)) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field As Global.System.Action Public field2 As System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "Global.System.Action", code.IndexOf("Global.System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.DelegateName}, minimal:=True) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913_2() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field As Global.System.Action Public field2 As System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "System.Action", code.IndexOf("Global.System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.DelegateName}, minimal:=True) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913_3() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field2 As System.Action Public field As Global.System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field2").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "System.Action", code.IndexOf("System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <Fact()> Public Sub TestMinimalOfContextualKeywordAsIdentifier() Dim text = <compilation> <file name="a.vb"> Class Take Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Take").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub [Take].X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact()> Public Sub TestMinimalOfContextualKeywordAsIdentifierTypeKeyword() Dim text = <compilation> <file name="a.vb"> Class [Type] Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits [Type] End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Type").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Type.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) text = <compilation> <file name="a.vb"> Imports System Class Goo Public Bar as Type End Class </file> </compilation> findSymbol = Function(globalns) globalns.GetTypeMembers("Goo").Single().GetMembers("Bar").Single() code = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Goo.Bar As Type", code.IndexOf("Public Bar as Type", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <WorkItem(543938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543938")> <Fact> Public Sub Bug12025() Dim text = <compilation> <file name="a.vb"> Class CBase Public Overridable Property [Class] As Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Class").Single(), PropertySymbol) Return field End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "Property CBase.Class As Integer", code.IndexOf("Public Overridable Property [Class] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) End Sub <Fact, WorkItem(544414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544414")> Public Sub Bug12724() Dim text = <compilation> <file name="a.vb"> Class CBase Public Overridable Property [Class] As Integer Public [Interface] As Integer Event [Event]() Public Overridable Sub [Sub]() Public Overridable Function [Function]() Class [Dim] End Class End Class </file> </compilation> Dim findProperty As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Class").Single(), PropertySymbol) Return field End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findProperty, format, "Property CBase.Class As Integer", code.IndexOf("Public Overridable Property [Class] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findSub As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Sub").Single(), MethodSymbol) TestSymbolDescription( text, findSub, format, "Sub CBase.Sub()", code.IndexOf("Public Overridable Sub [Sub]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) Dim findFunction As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Function").Single(), MethodSymbol) TestSymbolDescription( text, findFunction, format, "Function CBase.Function() As Object", code.IndexOf("Public Overridable Function [Function]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findField As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Interface").Single(), FieldSymbol) TestSymbolDescription( text, findField, format, "CBase.Interface As Integer", code.IndexOf("Public [Interface] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findEvent As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Event").Single(), EventSymbol) TestSymbolDescription( text, findEvent, format, "Event CBase.Event()", code.IndexOf("Event [Event]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) Dim findClass As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Dim").Single(), NamedTypeSymbol) TestSymbolDescription( text, findClass, New SymbolDisplayFormat(typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces), "CBase.Dim", code.IndexOf("Class [Dim]", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=False) End Sub <Fact, WorkItem(543806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543806")> Public Sub Bug11752() Dim text = <compilation> <file name="a.vb"> Class Explicit Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Explicit").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Explicit.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact(), WorkItem(529764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529764")> Public Sub TypeParameterFromMetadata() Dim src1 = <compilation> <file name="lib.vb"> Public Class LibG(Of T) End Class </file> </compilation> Dim src2 = <compilation> <file name="use.vb"> Public Class Gen(Of V) Public Sub M(p as LibG(Of V)) End Sub Public Function F(p as Object) As Object End Function End Class </file> </compilation> Dim dummy = <compilation> <file name="app.vb"> </file> </compilation> Dim complib = CreateCompilationWithMscorlib40(src1) Dim compref = New VisualBasicCompilationReference(complib) Dim comp1 = CreateCompilationWithMscorlib40AndReferences(src2, references:={compref}) Dim mtdata = comp1.EmitToArray() Dim mtref = MetadataReference.CreateFromImage(mtdata) Dim comp2 = CreateCompilationWithMscorlib40AndReferences(dummy, references:={mtref}) Dim tsym1 = comp1.SourceModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Gen") Assert.NotNull(tsym1) Dim msym1 = tsym1.GetMember(Of MethodSymbol)("M") Assert.NotNull(msym1) ' Public Sub M(p As LibG(Of V)) ' C# is like - Gen(Of V).M(LibG(Of V)) Assert.Equal("Public Sub M(p As LibG(Of V))", msym1.ToDisplayString()) Dim tsym2 = comp2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Gen") Assert.NotNull(tsym2) Dim msym2 = tsym2.GetMember(Of MethodSymbol)("M") Assert.NotNull(msym2) Assert.Equal(msym1.ToDisplayString(), msym2.ToDisplayString()) End Sub <Fact, WorkItem(545625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545625")> Public Sub ReverseArrayRankSpecifiers() Dim text = <compilation> <file name="a.vb"> class C Private F as C()(,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of FieldSymbol)("F").Type Dim normalFormat As New SymbolDisplayFormat() Dim reverseFormat As New SymbolDisplayFormat( compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers) TestSymbolDescription( text, findSymbol, normalFormat, "C()(,)", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) TestSymbolDescription( text, findSymbol, reverseFormat, "C(,)()", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) End Sub <Fact> Public Sub TestMethodCSharp() Dim text = <text> class A { public void Goo(int a) { } } </text>.Value Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CreateCSharpCompilation("c", text) Dim a = DirectCast(comp.GlobalNamespace.GetMembers("A").Single(), ITypeSymbol) Dim goo = a.GetMembers("Goo").Single() Dim parts = VisualBasic.SymbolDisplay.ToDisplayParts(goo, format) Verify(parts, "Public Sub Goo(a As Integer)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact> Public Sub SupportSpeculativeSemanticModel() Dim text = <compilation> <file name="a.vb"> Class Explicit Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Explicit").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Explicit.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, useSpeculativeSemanticModel:=True, minimal:=True) End Sub <WorkItem(765287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765287")> <Fact> Public Sub TestCSharpSymbols() Dim csComp = CreateCSharpCompilation("CSharp", <![CDATA[ class Outer { class Inner<T> { } void M<U>() { } string P { set { } } int F; event System.Action E; delegate void D(); Missing Error() { } } ]]>) Dim outer = DirectCast(csComp.GlobalNamespace.GetMembers("Outer").Single(), INamedTypeSymbol) Dim type = outer.GetMembers("Inner").Single() Dim method = outer.GetMembers("M").Single() Dim [property] = outer.GetMembers("P").Single() Dim field = outer.GetMembers("F").Single() Dim [event] = outer.GetMembers("E").Single() Dim [delegate] = outer.GetMembers("D").Single() Dim [error] = outer.GetMembers("Error").Single() Assert.IsNotType(Of Symbol)(type) Assert.IsNotType(Of Symbol)(method) Assert.IsNotType(Of Symbol)([property]) Assert.IsNotType(Of Symbol)(field) Assert.IsNotType(Of Symbol)([event]) Assert.IsNotType(Of Symbol)([delegate]) Assert.IsNotType(Of Symbol)([error]) ' 1) Looks like VB. ' 2) Doesn't blow up. Assert.Equal("Outer.Inner(Of T)", VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) Assert.Equal("Sub Outer.M(Of U)()", VisualBasic.SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat)) Assert.Equal("WriteOnly Property Outer.P As System.String", VisualBasic.SymbolDisplay.ToDisplayString([property], SymbolDisplayFormat.TestFormat)) Assert.Equal("Outer.F As System.Int32", VisualBasic.SymbolDisplay.ToDisplayString(field, SymbolDisplayFormat.TestFormat)) Assert.Equal("Event Outer.E As System.Action", VisualBasic.SymbolDisplay.ToDisplayString([event], SymbolDisplayFormat.TestFormat)) Assert.Equal("Outer.D", VisualBasic.SymbolDisplay.ToDisplayString([delegate], SymbolDisplayFormat.TestFormat)) Assert.Equal("Function Outer.Error() As Missing", VisualBasic.SymbolDisplay.ToDisplayString([error], SymbolDisplayFormat.TestFormat)) End Sub <Fact> Public Sub FormatPrimitive() Assert.Equal("Nothing", SymbolDisplay.FormatPrimitive(Nothing, quoteStrings:=True, useHexadecimalNumbers:=True)) Assert.Equal("3", SymbolDisplay.FormatPrimitive(OutputKind.NetModule, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000003", SymbolDisplay.FormatPrimitive(OutputKind.NetModule, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("""x""c", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=True, useHexadecimalNumbers:=True)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("""x""c", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=True, useHexadecimalNumbers:=False)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x", quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("""x""", SymbolDisplay.FormatPrimitive("x", quoteStrings:=True, useHexadecimalNumbers:=False)) Assert.Equal("True", SymbolDisplay.FormatPrimitive(True, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(1, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000001", SymbolDisplay.FormatPrimitive(1, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CUInt(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000001", SymbolDisplay.FormatPrimitive(CUInt(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CByte(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H01", SymbolDisplay.FormatPrimitive(CByte(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CSByte(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H01", SymbolDisplay.FormatPrimitive(CSByte(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CShort(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0001", SymbolDisplay.FormatPrimitive(CShort(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CUShort(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0001", SymbolDisplay.FormatPrimitive(CUShort(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CLng(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0000000000000001", SymbolDisplay.FormatPrimitive(CLng(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CULng(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0000000000000001", SymbolDisplay.FormatPrimitive(CULng(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(1.1, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(1.1, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CSng(1.1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CSng(1.1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CDec(1.1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CDec(1.1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("#1/1/2000 12:00:00 AM#", SymbolDisplay.FormatPrimitive(#1/1/2000#, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("#1/1/2000 12:00:00 AM#", SymbolDisplay.FormatPrimitive(#1/1/2000#, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal(Nothing, SymbolDisplay.FormatPrimitive(New Object(), quoteStrings:=False, useHexadecimalNumbers:=False)) End Sub <Fact> Public Sub AllowDefaultLiteral() Dim text = <compilation> <file name="a.vb"> Class C Sub Method(Optional cancellationToken as CancellationToken = Nothing) End Sub End Class </file> </compilation> Dim formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral)) Dim formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral) Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral)) ' Visual Basic doesn't have default expressions, so AllowDefaultLiteral does not change behavior Const ExpectedText As String = "Sub C.Method(cancellationToken As CancellationToken = Nothing)" TestSymbolDescription(text, FindSymbol("C.Method"), formatWithoutAllowDefaultLiteral, ExpectedText) TestSymbolDescription(text, FindSymbol("C.Method"), formatWithAllowDefaultLiteral, ExpectedText) End Sub <Fact()> Public Sub Tuple() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (Integer, String) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType), "f As (Int32, String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation) End Sub <WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")> <Fact()> Public Sub TupleWith1Arity() TestSymbolDescription( <compilation> <file name="a.vb"> Imports System Class C Private f As ValueTuple(Of Integer) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters), "f As ValueTuple(Of Int32)", 0, {SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation}, references:={MetadataReference.CreateFromImage(TestResources.NetFX.ValueTuple.tuplelib)}) End Sub <Fact()> Public Sub TupleWithNames() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (x As Integer, y As String) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType), "f As (x As Int32, y As String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub LongTupleWithSpecialTypes() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (Integer, String, Boolean, Byte, Long, ULong, Short, UShort) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes), "f As (Integer, String, Boolean, Byte, Long, ULong, Short, UShort)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub TupleProperty() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Property P As (Item1 As Integer, Item2 As String) End Class </file> </compilation>, FindSymbol("C.P"), New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes), "P As (Item1 As Integer, Item2 As String)", SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub TupleQualifiedNames() Dim text = "Imports NAB = N.A.B Namespace N Class A Friend Class B End Class End Class Class C(Of T) ' offset 1 End Class End Namespace Class C Private f As (One As Integer, N.C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As N.A) ' offset 2 End Class" Dim source = <compilation> <file name="a.vb"><%= text %></file> </compilation> Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source, references:={SystemRuntimeFacadeRef, ValueTupleRef}) comp.VerifyDiagnostics() Dim symbol = comp.GetMember("C.f") ' Fully qualified format. Verify( SymbolDisplay.ToDisplayParts(symbol, format), "f As (One As Integer, Global.N.C(Of (Object(), Two As Global.N.A.B)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As Global.N.A)") ' Minimally qualified format. Verify( SymbolDisplay.ToDisplayParts(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "C.f As (One As Integer, C(Of (Object(), Two As B)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As A)") ' ToMinimalDisplayParts. Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Verify( SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 1"), format), "f As (One As Integer, C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As A)") Verify( SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 2"), format), "f As (One As Integer, N.C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As N.A)") End Sub ' A tuple type symbol that is not Microsoft.CodeAnalysis.VisualBasic.Symbols.TupleTypeSymbol. <Fact()> Public Sub NonTupleTypeSymbol() Dim source = "class C { #pragma warning disable CS0169 (int Alice, string Bob) F; (int, string) G; #pragma warning restore CS0169 }" Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CreateCSharpCompilation(GetUniqueName(), source, referencedAssemblies:={MscorlibRef, SystemRuntimeFacadeRef, ValueTupleRef}) comp.VerifyDiagnostics() Dim type = comp.GlobalNamespace.GetTypeMembers("C").Single() Verify( SymbolDisplay.ToDisplayParts(type.GetMembers("F").Single(), format), "F As (Alice As Integer, Bob As String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) Verify( SymbolDisplay.ToDisplayParts(type.GetMembers("G").Single(), format), "G As (Integer, String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact> <WorkItem(23970, "https://github.com/dotnet/roslyn/pull/23970")> Public Sub MeDisplayParts() Dim Text = <compilation> <file name="b.vb"> Class A Sub M([Me] As Integer) Me.M([Me]) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(Text) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim invocation = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.Equal("Me.M([Me])", invocation.ToString()) Dim actualThis = DirectCast(invocation.Expression, MemberAccessExpressionSyntax).Expression Assert.Equal("Me", actualThis.ToString()) Verify( ToDisplayParts(model.GetSymbolInfo(actualThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "Me As A", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName) Dim escapedThis = invocation.ArgumentList.Arguments(0).GetExpression() Assert.Equal("[Me]", escapedThis.ToString()) Verify( ToDisplayParts(model.GetSymbolInfo(escapedThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "[Me] As Integer", SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End Sub ' SymbolDisplayMemberOptions.IncludeRef is ignored in VB. <WorkItem(11356, "https://github.com/dotnet/roslyn/issues/11356")> <Fact()> Public Sub RefReturn() Dim sourceA = "public delegate ref int D(); public class C { public ref int F(ref int i) => ref i; int _p; public ref int P => ref _p; public ref int this[int i] => ref _p; }" Dim compA = CreateCSharpCompilation(GetUniqueName(), sourceA) compA.VerifyDiagnostics() Dim refA = compA.EmitToImageReference() ' From C# symbols. RefReturnInternal(compA) Dim sourceB = <compilation> <file name="b.vb"> </file> </compilation> Dim compB = CompilationUtils.CreateCompilationWithMscorlib40(sourceB, references:={refA}) compB.VerifyDiagnostics() ' From VB symbols. RefReturnInternal(compB) End Sub Private Shared Sub RefReturnInternal(comp As Compilation) Dim formatWithRef = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeRef, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeParamsRefOut, propertyStyle:=SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, delegateStyle:=SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim [global] = comp.GlobalNamespace Dim type = [global].GetTypeMembers("C").Single() Dim method = type.GetMembers("F").Single() Dim [property] = type.GetMembers("P").Single() Dim indexer = type.GetMembers().Where(Function(m) m.Kind = SymbolKind.Property AndAlso DirectCast(m, IPropertySymbol).IsIndexer).Single() Dim [delegate] = [global].GetTypeMembers("D").Single() ' Method with IncludeRef. ' https://github.com/dotnet/roslyn/issues/14683: missing ByRef for C# parameters. If comp.Language = "C#" Then Verify( SymbolDisplay.ToDisplayParts(method, formatWithRef), "ByRef F(Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) Else Verify( SymbolDisplay.ToDisplayParts(method, formatWithRef), "ByRef F(ByRef Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End If ' Property with IncludeRef. Verify( SymbolDisplay.ToDisplayParts([property], formatWithRef), "ReadOnly ByRef P As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) ' Indexer with IncludeRef. ' https://github.com/dotnet/roslyn/issues/14684: "this[]" for C# indexer. If comp.Language = "C#" Then Verify( SymbolDisplay.ToDisplayParts(indexer, formatWithRef), "ReadOnly ByRef this[](Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) Else Verify( SymbolDisplay.ToDisplayParts(indexer, formatWithRef), "ReadOnly ByRef Item(Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End If ' Delegate with IncludeRef. Verify( SymbolDisplay.ToDisplayParts([delegate], formatWithRef), "ByRef Function D() As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End Sub <Fact> Public Sub AliasInSpeculativeSemanticModel() Dim text = <compilation> <file name="a.vb"> Imports A = N.M Namespace N.M Class B End Class End Namespace Class C Shared Sub M() Dim o = 1 End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockBaseSyntax)().First() Dim position = methodDecl.Statements(0).SpanStart tree = VisualBasicSyntaxTree.ParseText(" Class C Shared Sub M() Dim o = 1 End Sub End Class") methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockBaseSyntax)().First() Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(position, methodDecl, model)) Dim symbol = comp.GetMember(Of NamedTypeSymbol)("N.M.B") position = methodDecl.Statements(0).SpanStart Dim description = symbol.ToMinimalDisplayParts(model, position, SymbolDisplayFormat.MinimallyQualifiedFormat) Verify(description, "A.B", SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName) End Sub #Region "Helpers" Private Shared Sub TestSymbolDescription( text As XElement, findSymbol As Func(Of NamespaceSymbol, Symbol), format As SymbolDisplayFormat, expectedText As String, position As Integer, kinds As SymbolDisplayPartKind(), Optional minimal As Boolean = False, Optional useSpeculativeSemanticModel As Boolean = False, Optional references As IEnumerable(Of MetadataReference) = Nothing) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) If references IsNot Nothing Then comp = comp.AddReferences(references.ToArray()) End If Dim symbol = findSymbol(comp.GlobalNamespace) Dim description As ImmutableArray(Of SymbolDisplayPart) If minimal Then Dim tree = comp.SyntaxTrees.First() Dim semanticModel As SemanticModel = comp.GetSemanticModel(tree) Dim tokenPosition = tree.GetRoot().FindToken(position).SpanStart If useSpeculativeSemanticModel Then Dim newTree = tree.WithChangedText(tree.GetText()) Dim token = newTree.GetRoot().FindToken(position) tokenPosition = token.SpanStart Dim member = token.Parent.FirstAncestorOrSelf(Of MethodBlockBaseSyntax)() Dim speculativeModel As SemanticModel = Nothing semanticModel.TryGetSpeculativeSemanticModelForMethodBody(member.BlockStatement.Span.End, member, speculativeModel) semanticModel = speculativeModel End If description = VisualBasic.SymbolDisplay.ToMinimalDisplayParts(symbol, semanticModel, tokenPosition, format) Else description = VisualBasic.SymbolDisplay.ToDisplayParts(symbol, format) End If Verify(description, expectedText, kinds) End Sub Private Shared Sub TestSymbolDescription( text As XElement, findSymbol As Func(Of NamespaceSymbol, Symbol), format As SymbolDisplayFormat, expectedText As String, ParamArray kinds As SymbolDisplayPartKind()) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(text, references:={TestMetadata.Net40.SystemCore}) ' symbol: Dim symbol = findSymbol(comp.GlobalNamespace) Dim description = VisualBasic.SymbolDisplay.ToDisplayParts(symbol, format) Verify(description, expectedText, kinds) ' retargeted symbol: Dim retargetedAssembly = New Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting.RetargetingAssemblySymbol(comp.SourceAssembly, isLinked:=False) retargetedAssembly.SetCorLibrary(comp.SourceAssembly.CorLibrary) Dim retargetedSymbol = findSymbol(retargetedAssembly.GlobalNamespace) Dim retargetedDescription = VisualBasic.SymbolDisplay.ToDisplayParts(retargetedSymbol, format) Verify(retargetedDescription, expectedText, kinds) End Sub Private Shared Function Verify(parts As ImmutableArray(Of SymbolDisplayPart), expectedText As String, ParamArray kinds As SymbolDisplayPartKind()) As ImmutableArray(Of SymbolDisplayPart) Assert.Equal(expectedText, parts.ToDisplayString()) If (kinds.Length > 0) Then AssertEx.Equal(kinds, parts.Select(Function(p) p.Kind), itemInspector:=Function(p) $" SymbolDisplayPartKind.{p}") End If Return parts End Function Private Shared Function FindSymbol(qualifiedName As String) As Func(Of NamespaceSymbol, Symbol) Return Function([namespace]) [namespace].GetMember(qualifiedName) 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.Globalization Imports System.Threading Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolDisplayTests Inherits BasicTestBase <Fact> Public Sub TestClassNameOnlySimple() Dim text = <compilation> <file name="a.vb"> class A end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly) TestSymbolDescription( text, findSymbol, format, "A", {SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestClassNameOnlyComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() End Function Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly) TestSymbolDescription( text, findSymbol, format, "C2", {SymbolDisplayPartKind.ClassName}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes) TestSymbolDescription( text, findSymbol, format, "C1.C2", {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "N1.N2.N3.C1.C2", {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestFullyQualifiedFormat() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() End Function TestSymbolDescription( text, findSymbol, SymbolDisplayFormat.FullyQualifiedFormat, "Global.N1.N2.N3.C1.C2", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact> Public Sub TestMethodNameOnlySimple() Dim text = <compilation> <file name="a.vb"> class A Sub M() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat() TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMethodNameOnlyComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 public shared function M(nullable x as integer, c as C1) as Integer() end function end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat() TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestClassNameOnlyWithKindSimple() Dim text = <compilation> <file name="a.vb"> class A end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, kindOptions:=SymbolDisplayKindOptions.IncludeTypeKeyword) TestSymbolDescription( text, findSymbol, format, "Class A", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestClassWithKindComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("A").Single() Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, kindOptions:=SymbolDisplayKindOptions.IncludeTypeKeyword) TestSymbolDescription( text, findSymbol, format, "Class N1.N2.N3.A", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestNamespaceWithKindSimple() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, kindOptions:=SymbolDisplayKindOptions.IncludeNamespaceKeyword) TestSymbolDescription( text, findSymbol, format, "Namespace N3", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName}) End Sub <Fact()> Public Sub TestNamespaceWithKindComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class A end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, kindOptions:=SymbolDisplayKindOptions.IncludeNamespaceKeyword) TestSymbolDescription( text, findSymbol, format, "Namespace N1.N2.N3", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}) End Sub <Fact()> Public Sub TestMethodAndParamsSimple() Dim text = <compilation> <file name="a.vb"> class A Private sub M() End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("A", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Private Sub M()", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeType, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "M()", {SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMethodAndParamsComplex() Dim text = <compilation> <file name="a.vb"> namespace N1 namespace N2.N3 class C1 class C2 public shared function M(x? as integer, c as C1) as Integer() end function end class end class end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Shared Function M(x As Integer?, c As C1) As Integer()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact> Public Sub TestExtensionMethodAsStatic() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.StaticMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1(Of TSource).M(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestExtensionMethodAsDefault() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C2", 0).Single(). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.Default, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1(Of TSource), index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestIrreducibleExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1(Of T) end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource As Structure)(source As C1(Of TSource), index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim c2Type = globalns.GetTypeMember("C2") Dim method = c2Type.GetMember(Of MethodSymbol)("M") Return method.Construct(c2Type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of C2)(source As C1(Of C2), index As Integer) As C2", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsStatic() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.StaticMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C2.M(Of TSource)(source As C1, index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ModuleName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsInstance() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1.M(Of TSource)(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact> Public Sub TestReducedExtensionMethodAsDefault() Dim text = <compilation> <file name="a.vb"> class C1 end class module C2 &lt;System.Runtime.CompilerServices.ExtensionAttribute()&gt; public function M(Of TSource)(source As C1, index As Integer) As TSource end function end module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim type = globalns.GetTypeMember("C1") Dim method = DirectCast(globalns.GetTypeMember("C2").GetMember("M"), MethodSymbol) Return method.ReduceExtensionMethod(type) End Function Dim format = New SymbolDisplayFormat( extensionMethodStyle:=SymbolDisplayExtensionMethodStyle.Default, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeExtensionThis Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "Public Function C1.M(Of TSource)(index As Integer) As TSource", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ExtensionMethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName}) End Sub <Fact()> Public Sub TestNothingParameters() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format As SymbolDisplayFormat = Nothing ' default is show asterisks for VB. If this is changed, this test will fail ' in this case, please rewrite the test TestNoArrayAsterisks to TestArrayAsterisks TestSymbolDescription( text, findSymbol, format, "Public f As Integer()(*,*)(*,*,*)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestArrayRank() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "f As Integer()(,)(,,)", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestEscapeKeywordIdentifiers() Dim text = <compilation> <file name="a.vb"> namespace N1 class [Integer] Class [class] Shared Sub [shared]([boolean] As System.String) If [boolean] Then Console.WriteLine("true") Else Console.WriteLine("false") End If End Sub End Class End Class end namespace namespace [Global] namespace [Integer] end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("Integer").Single(). GetTypeMembers("class").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' no escaping because N1 does not need to be escaped TestSymbolDescription( text, findSymbol, format, "N1.Integer.class", { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' outer class needs escaping TestSymbolDescription( text, findSymbol, format, "[Integer].class", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' outer class needs escaping TestSymbolDescription( text, findSymbol, format, "[class]", { SymbolDisplayPartKind.ClassName }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("Integer").Single(). GetTypeMembers("class").Single().GetMembers("shared").Single() format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' actual test case from bug 4389 TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As System.String)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' making sure that types still get escaped if no special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As [String])", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation }) format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeParameters, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) ' making sure that types don't get escaped if special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "Public Sub [shared]([boolean] As String)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"Global"}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' making sure that types don't get escaped if special type formatting was chosen TestSymbolDescription( text, findSymbol, format, "[Global]", { SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global.Global", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) findSymbol = Function(globalns) globalns ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global", { SymbolDisplayPartKind.Keyword }) findSymbol = Function(globalns) globalns.LookupNestedNamespace({"Global"}).LookupNestedNamespace({"Integer"}) ' never escape "the" Global namespace, but escape other ns named "global" always TestSymbolDescription( text, findSymbol, format, "Global.Global.Integer", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "[Global].Integer", { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName }) format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "[Integer]", { SymbolDisplayPartKind.NamespaceName }) End Sub <Fact()> Public Sub AlwaysEscapeMethodNamedNew() Dim text = <compilation> <file name="a.vb"> Class C Sub [New]() End Sub End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) ' The method should be escaped TestSymbolDescription( text, Function(globalns As NamespaceSymbol) globalns.GetTypeMembers("C").Single().GetMembers("New").Single(), format, "C.[New]", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName }) ' The constructor should not TestSymbolDescription( text, Function(globalns As NamespaceSymbol) globalns.GetTypeMembers("C").Single().InstanceConstructors.Single(), format, "C.New", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Keyword }) End Sub <Fact()> Public Sub TestExplicitMethodImplNameOnly() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "I_M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestExplicitMethodImplNameAndInterface() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeExplicitInterface) TestSymbolDescription( text, findSymbol, format, "I_M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestExplicitMethodImplNameAndInterfaceAndType() Dim text = <compilation> <file name="a.vb"> Interface I sub M() End Sub end Interface Class C Implements I sub I_M() implements I.M End Sub end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("I_M").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeContainingType) TestSymbolDescription( text, findSymbol, format, "C.I_M", {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestGlobalNamespaceCode() Dim text = <compilation> <file name="a.vb"> Class C end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included) TestSymbolDescription( text, findSymbol, format, "Global.C", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}) End Sub <Fact()> Public Sub TestGlobalNamespaceHumanReadable() Dim text = <compilation> <file name="a.vb"> Class C End Class namespace [Global] end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included) TestSymbolDescription( text, findSymbol, format, "Global", {SymbolDisplayPartKind.Keyword}) format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) TestSymbolDescription( text, findSymbol, format, "Global", {SymbolDisplayPartKind.Keyword}) End Sub <Fact()> Public Sub TestSpecialTypes() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, findSymbol, format, "f As Integer", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword }) End Sub <Fact()> Public Sub TestNoArrayAsterisks() Dim text = <compilation> <file name="a.vb"> class C1 dim public f as Integer()(,)(,,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("f").Single() Dim format As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.None) TestSymbolDescription( text, findSymbol, format, "f As Int32()(,)(,,)", { SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestMetadataMethodNames() Dim text = <compilation> <file name="a.vb"> Class C New C() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers(".ctor").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) TestSymbolDescription( text, findSymbol, format, "Sub .ctor", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestArityForGenericTypes() Dim text = <compilation> <file name="a.vb"> Class C(Of T, U, V) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes) TestSymbolDescription( text, findSymbol, format, "C`3", { SymbolDisplayPartKind.ClassName, InternalSymbolDisplayPartKind.Arity}) End Sub <Fact()> Public Sub TestGenericTypeParameters() Dim text = <compilation> <file name="a.vb"> Class C(Of In T, Out U, V) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "C(Of T, U, V)", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericTypeParametersAndVariance() Dim text = <compilation> <file name="a.vb"> Interface I(Of In T, Out U, V) End Interface </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("I") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance) TestSymbolDescription( text, findSymbol, format, "I(Of In T, Out U, V)", { SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericTypeConstraints() Dim text = <compilation> <file name="a.vb"> Class C(Of T As C(Of T)) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) TestSymbolDescription( text, findSymbol, format, "C(Of T As C(Of T))", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodParameters() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(Of In T, Out U, V)() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "M(Of T, U, V)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodParametersAndVariance() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(Of In T, Out U, V)() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance) TestSymbolDescription( text, findSymbol, format, "M(Of T, U, V)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestGenericMethodConstraints() Dim text = <compilation> <file name="a.vb"> Class C(Of T) Public Sub M(Of U, V As {T, Class, U})() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) TestSymbolDescription( text, findSymbol, format, "M(Of U, V As {Class, T, U})", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Sub M(p as Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "M", {SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMemberMethodAll() Dim text = <compilation> <file name="a.vb"> Class C Sub M(p as Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Public Sub C.M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethodAll() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Public Declare Unicode Sub C.M Lib ""goo"" ()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethod_NoType() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters) TestSymbolDescription( text, findSymbol, format, "Public C.M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestMemberDeclareMethod_NoAccessibility_NoContainingType_NoParameters() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" Alias "bar" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Declare Unicode Sub M Lib ""goo"" Alias ""bar""", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral}) End Sub <Fact()> Public Sub TestMemberDeclareMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Declare Unicode Sub M Lib "goo" (p as Integer) End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "M", { SymbolDisplayPartKind.MethodName}) End Sub <Fact()> Public Sub TestMemberFieldNone() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "f", {SymbolDisplayPartKind.FieldName}) End Sub <Fact()> Public Sub TestMemberFieldAll() Dim text = <compilation> <file name="a.vb"> Class C dim f as Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType) TestSymbolDescription( text, findSymbol, format, "Private C.f As Int32", {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact> Public Sub TestConstantFieldValue() Dim text = <compilation> <file name="a.vb"> Class C Const f As Integer = 1 End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As Int32 = 1", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact> Public Sub TestConstantFieldValue_EnumMember() Dim text = <compilation> <file name="a.vb"> Enum E A B C End Enum Class C Const f As E = E.B End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As E = E.B", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestConstantFieldValue_EnumMember_Flags() Dim text = <compilation> <file name="a.vb"> &lt;System.FlagsAttribute&gt; Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum Class C Const f As E = E.D End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("C", 0).Single(). GetMembers("f").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "Private Const C.f As E = E.D", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ConstantName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestEnumMember() Dim text = <compilation> <file name="a.vb"> Enum E A B C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("B").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.B = 1", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact> Public Sub TestEnumMember_Flags() Dim text = <compilation> <file name="a.vb"> &lt;System.FlagsAttribute&gt; Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("D").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.D = E.A Or E.B Or E.C", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName) End Sub <Fact> Public Sub TestEnumMember_FlagsWithoutAttribute() Dim text = <compilation> <file name="a.vb"> Enum E A = 1 B = 2 C = 4 D = A Or B Or C End Enum </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) _ globalns.GetTypeMembers("E", 0).Single(). GetMembers("D").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeConstantValue) TestSymbolDescription( text, findSymbol, format, "E.D = 7", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EnumMemberName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral) End Sub <Fact()> Public Sub TestMemberPropertyNone() Dim text = <compilation> <file name="c.vb"> Class C Private ReadOnly Property P As Integer Get Return 0 End Get End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("P").Single() Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.None) TestSymbolDescription( text, findSymbol, format, "P", {SymbolDisplayPartKind.PropertyName}) End Sub <Fact()> Public Sub TestMemberPropertyAll() Dim text = <compilation> <file name="c.vb"> Class C Public Default Readonly Property P(x As Object) as Integer Get return 23 End Get End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Public Default Property C.P(x As Object) As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestMemberPropertyGetSet() Dim text = <compilation> <file name="c.vb"> Class C Public ReadOnly Property P as integer Get Return 0 End Get End Property Public WriteOnly Property Q Set End Set End Property Public Property R End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:=SymbolDisplayPropertyStyle.ShowReadWriteDescriptor) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("P").Single(), format, "ReadOnly Property P As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("Q").Single(), format, "WriteOnly Property Q As Object", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName }) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("R").Single(), format, "Property R As Object", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName }) End Sub <Fact()> Public Sub TestPropertyGetAccessor() Dim text = <compilation> <file name="c.vb"> Class C Private Property P As Integer Get Return 0 End Get Set End Set End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("get_P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private Property Get C.P() As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private C.P() As Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestPropertySetAccessor() Dim text = <compilation> <file name="c.vb"> Class C Private WriteOnly Property P As Integer Set End Set End Property End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMembers("set_P").Single() Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeContainingType Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:= SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "Private Property Set C.P(Value As Int32)", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestParameterMethodNone() Dim text = <compilation> <file name="a.vb"> Class C Sub M(obj as object, byref s as short, i as integer = 1) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:=SymbolDisplayParameterOptions.None) TestSymbolDescription( text, findSymbol, format, "M()", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterBrackets() Dim text = <compilation> <file name="a.vb"> Class C Sub M(Optional i As Integer = 0) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeOptionalBrackets) TestSymbolDescription( text, findSymbol, format, "M([i As Int32])", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterValue_String() Dim text = <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Class C Sub M(Optional s As String = ChrW(&amp;HFFFE) &amp; "a" &amp; ChrW(0) &amp; vbCrLf) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue) TestSymbolDescription( text, findSymbol, format, "M(s As String = ChrW(&HFFFE) & ""a"" & vbNullChar & vbCrLf)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation}) End Sub <Fact()> Public Sub TestOptionalParameterValue_Char() Dim text = <compilation> <file name="a.vb"> Imports Microsoft.VisualBasic Class C Sub M(Optional a As Char = ChrW(&amp;HFFFE), Optional b As Char = ChrW(8)) End Sub End Class </file> </compilation> Dim findSymbol = Function(globalns As NamespaceSymbol) globalns _ .GetMember(Of NamedTypeSymbol)("C") _ .GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue) TestSymbolDescription( text, findSymbol, format, "M(a As Char = ChrW(&HFFFE), b As Char = vbBack)", { SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestOptionalParameterValue_InvariantCulture1() Dim text = <compilation> <file name="a.vb"> Class C Sub M( Optional p1 as SByte = -1, Optional p2 as Short = -1, Optional p3 as Integer = -1, Optional p4 as Long = -1, Optional p5 as Single = -0.5, Optional p6 as Double = -0.5, Optional p7 as Decimal = -0.5) End Sub End Class </file> </compilation> Dim oldCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CType(oldCulture.Clone(), CultureInfo) Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~" Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "," Dim Compilation = CreateCompilationWithMscorlib40(text) Compilation.VerifyDiagnostics() Dim methodSymbol = Compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Assert.Equal("Sub C.M(" + "[p1 As System.SByte = -1], " + "[p2 As System.Int16 = -1], " + "[p3 As System.Int32 = -1], " + "[p4 As System.Int64 = -1], " + "[p5 As System.Single = -0.5], " + "[p6 As System.Double = -0.5], " + "[p7 As System.Decimal = -0.5])", methodSymbol.ToTestDisplayString()) Finally Thread.CurrentThread.CurrentCulture = oldCulture End Try End Sub <Fact()> Public Sub TestOptionalParameterValue_InvariantCulture() Dim text = <compilation> <file name="a.vb"> Class C Sub M( Optional p1 as SByte = -1, Optional p2 as Short = -1, Optional p3 as Integer = -1, Optional p4 as Long = -1, Optional p5 as Single = -0.5, Optional p6 as Double = -0.5, Optional p7 as Decimal = -0.5) End Sub End Class </file> </compilation> Dim oldCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CType(oldCulture.Clone(), CultureInfo) Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~" Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "," Dim Compilation = CreateCompilationWithMscorlib40(text) Compilation.VerifyDiagnostics() Dim methodSymbol = Compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Assert.Equal("Sub C.M(" + "[p1 As System.SByte = -1], " + "[p2 As System.Int16 = -1], " + "[p3 As System.Int32 = -1], " + "[p4 As System.Int64 = -1], " + "[p5 As System.Single = -0.5], " + "[p6 As System.Double = -0.5], " + "[p7 As System.Decimal = -0.5])", methodSymbol.ToTestDisplayString()) Finally Thread.CurrentThread.CurrentCulture = oldCulture End Try End Sub <Fact()> Public Sub TestMethodReturnType1() Dim text = <compilation> <file name="a.vb"> Class C shared function M() as Integer End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Function M() As System.Int32", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.StructName }) End Sub <Fact()> Public Sub TestMethodReturnType2() Dim text = <compilation> <file name="a.vb"> Class C shared sub M() End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C"). GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword) TestSymbolDescription( text, findSymbol, format, "Sub M()", { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation }) End Sub <Fact()> Public Sub TestParameterMethodNameTypeModifiers() Dim text = <compilation> <file name="a.vb"> Class C Public Sub M(byref s as short, i as integer , ParamArray args as string()) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M") Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters, parameterOptions:= SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "M(ByRef s As Int16, i As Int32, ParamArray args As String())", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) ' Without SymbolDisplayParameterOptions.IncludeParamsRefOut. TestSymbolDescription( text, findSymbol, format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName), "M(s As Int16, i As Int32, args As String())", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) ' Without SymbolDisplayParameterOptions.IncludeType. TestSymbolDescription( text, findSymbol, format.WithParameterOptions(SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeName), "M(ByRef s, i, ParamArray args)", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation) End Sub ' "Public" and "MustOverride" should not be included for interface members. <Fact()> Public Sub TestInterfaceMembers() Dim text = <compilation> <file name="a.vb"> Interface I Property P As Integer Function F() As Object End Interface MustInherit Class C MustOverride Function F() As Object Interface I Sub M() End Interface End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:= SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("I", 0).Single().GetMembers("P").Single(), format, "Property P As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("I", 0).Single().GetMembers("F").Single(), format, "Function F() As Object") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("F").Single(), format, "Public MustOverride Function F() As Object") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetTypeMembers("I", 0).Single().GetMember(Of MethodSymbol)("M"), format, "Sub M()") End Sub ' "Shared" should not be included for Module members. <Fact()> Public Sub TestSharedMembers() Dim text = <compilation> <file name="a.vb"> Class C Shared Sub M() End Sub Public Shared F As Integer Public Shared P As Object End Class Module M Sub M() End Sub Public F As Integer Public P As Object End Module </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.UseSpecialTypes) TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of MethodSymbol)("M"), format, "Public Shared Sub M()") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("F").Single(), format, "Public Shared F As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMembers("P").Single(), format, "Public Shared P As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMember(Of MethodSymbol)("M"), format, "Public Sub M()") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMembers("F").Single(), format, "Public F As Integer") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("M", 0).Single().GetMembers("P").Single(), format, "Public P As Object") End Sub <WorkItem(540253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540253")> <Fact()> Public Sub TestOverloads() Dim text = <compilation> <file name="a.vb"> MustInherit Class B Protected MustOverride Overloads Function M(s As Single) Overloads Sub M() End Sub Friend NotOverridable Overloads WriteOnly Property P(x) Set(value) End Set End Property Overloads ReadOnly Property P(x, y) Get Return Nothing End Get End Property Public Overridable Overloads ReadOnly Property Q Get Return Nothing End Get End Property End Class </file> </compilation> Dim format = New SymbolDisplayFormat( memberOptions:= SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeExplicitInterface Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle:= SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions:= SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeType) TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("M").First(), format, "Protected MustOverride Overloads Function M(s As Single) As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("P").First(), format, "Friend NotOverridable Overloads WriteOnly Property P(x As Object) As Object") TestSymbolDescription( text, Function(globalns) globalns.GetTypeMembers("B", 0).Single().GetMembers("Q").First(), format, "Public Overridable Overloads ReadOnly Property Q As Object") End Sub <Fact> Public Sub TestAlias1() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3 Namespace N1 NAmespace N2 NAmespace N3 class C1 class C2 End class End class ENd namespace end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "Goo.C1.C2", code.IndexOf("Namespace", StringComparison.Ordinal), { SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestAlias2() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3.C1 Namespace N1 NAmespace N2 NAmespace N3 class C1 class C2 End class End class ENd namespace end namespace end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = New SymbolDisplayFormat( typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) TestSymbolDescription( text, findSymbol, format, "Goo.C2", code.IndexOf("Namespace", StringComparison.Ordinal), { SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestAlias3() Dim text = <compilation> <file name="a.vb">Imports Goo = N1.C1 Namespace N1 Class C1 End Class Class Goo End Class end namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.LookupNestedNamespace({"N1"}). GetTypeMembers("C1").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString Dim format = SymbolDisplayFormat.MinimallyQualifiedFormat TestSymbolDescription( text, findSymbol, format, "C1", code.IndexOf("Class Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName}, True) End Sub <Fact> Public Sub TestMinimalNamespace1() Dim text = <compilation> <file name="a.vb"> Imports Microsoft Imports OUTER namespace N0 end namespace namespace N1 namespace N2 namespace N3 class C1 class C2 end class end class end namespace end namespace end namespace Module Program Sub Main(args As String()) Dim x As Microsoft.VisualBasic.Collection Dim y As OUTER.INNER.GOO End Sub End Module Namespace OUTER Namespace INNER Friend Class GOO End Class End Namespace End Namespace </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"N1"}). LookupNestedNamespace({"N2"}). LookupNestedNamespace({"N3"}) End Function Dim format = New SymbolDisplayFormat() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, format, "N1.N2.N3", code.IndexOf("N0", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N1.N2.N3", text.Value.IndexOf("N1", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N2.N3", text.Value.IndexOf("N2", StringComparison.Ordinal), { SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N3", text.Value.IndexOf("C1", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName}, True) TestSymbolDescription(text, findSymbol, format, "N3", text.Value.IndexOf("C2", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName}, True) Dim findGOO As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"OUTER"}). LookupNestedNamespace({"INNER"}).GetTypeMembers("Goo").Single() End Function TestSymbolDescription(text, findGOO, format, "INNER.GOO", text.Value.IndexOf("OUTER.INNER.GOO", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, True) Dim findCollection As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Return globalns.LookupNestedNamespace({"Microsoft"}). LookupNestedNamespace({"VisualBasic"}).GetTypeMembers("Collection").Single() End Function TestSymbolDescription(text, findCollection, format, "VisualBasic.Collection", text.Value.IndexOf("Microsoft.VisualBasic.Collection", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=True, references:={SystemRef, MsvbRef}) End Sub <Fact> Public Sub TestMinimalClass1() Dim text = <compilation> <file name="a.vb"> imports System.Collections.Generic class C1 Dim Private goo as System.Collections.Generic.IDictionary(Of System.Collections.Generic.IList(Of System.Int32), System.String) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("C1").Single(). GetMembers("goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "C1.goo As IDictionary(Of IList(Of Integer), String)", code.IndexOf("goo", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact()> Public Sub TestRemoveAttributeSuffix1() Dim text = <compilation> <file name="a.vb"> Class Class1Attribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Class1Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "Class1Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "Class1", code.IndexOf("Inherits System.Attribute", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <Fact> Public Sub TestRemoveAttributeSuffix2() Dim text = <compilation> <file name="a.vb"> Class ClassAttribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("ClassAttribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "ClassAttribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "ClassAttribute", SymbolDisplayPartKind.ClassName) End Sub <Fact> Public Sub TestRemoveAttributeSuffix3() Dim text = <compilation> <file name="a.vb"> Class _Attribute Inherits System.Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("_Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "_Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "_Attribute", SymbolDisplayPartKind.ClassName) End Sub <Fact> Public Sub TestRemoveAttributeSuffix4() Dim text = <compilation> <file name="a.vb"> Class Class1Attribute End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Class1Attribute").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(), "Class1Attribute", SymbolDisplayPartKind.ClassName) TestSymbolDescription(text, findSymbol, New SymbolDisplayFormat(miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "Class1Attribute", SymbolDisplayPartKind.ClassName) End Sub <WorkItem(537447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537447")> <Fact> Public Sub TestBug2239() Dim text = <compilation> <file name="a.vb">Imports Goo=N1.N2.N3 class GC1(Of T) end class class X inherits GC1(Of BOGUS) End class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("X").Single.BaseType Dim format = New SymbolDisplayFormat( genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters) TestSymbolDescription( text, findSymbol, format, "GC1(Of BOGUS)", { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ErrorTypeName, SymbolDisplayPartKind.Punctuation}) End Sub <WorkItem(538954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538954")> <Fact> Public Sub ParameterOptionsIncludeName() Dim text = <compilation> <file name="a.vb"> Class Class1 Sub Sub1(ByVal param1 As Integer) End Sub End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim sub1 = CType(globalns.GetTypeMembers("Class1").Single().GetMembers("Sub1").Single(), MethodSymbol) Return sub1.Parameters.Single() End Function Dim format = New SymbolDisplayFormat(parameterOptions:=SymbolDisplayParameterOptions.IncludeName) TestSymbolDescription( text, findSymbol, format, "param1", {SymbolDisplayPartKind.ParameterName}) End Sub <WorkItem(539076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539076")> <Fact> Public Sub Bug4878() Dim text = <compilation> <file name="a.vb"> Namespace Global Namespace Global ' invalid because nested, would need escaping Public Class c1 End Class End Namespace End Namespace </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Assert.Equal("[Global]", comp.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString()) Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces) Assert.Equal("Global.Global", comp.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString(format)) Assert.Equal("Global.Global.c1", comp.SourceModule.GlobalNamespace.LookupNestedNamespace({"Global"}).GetTypeMembers.Single().ToDisplayString(format)) End Sub <WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")> <Fact> Public Sub Bug7515() Dim text = <compilation> <file name="a.vb"> Public Class C1 Delegate Sub MyDel(x as MyDel) End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim m_DelegateSignatureFormat As New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.GlobalNamespaceStyle, typeQualificationStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.MemberOptions, parameterOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.LocalOptions, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword Or SymbolDisplayKindOptions.IncludeNamespaceKeyword Or SymbolDisplayKindOptions.IncludeTypeKeyword, delegateStyle:=SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions:=SymbolDisplayFormat.VisualBasicErrorMessageFormat.MiscellaneousOptions) Assert.Equal("Delegate Sub C1.MyDel(x As C1.MyDel)", comp.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single(). GetMembers("MyDel").Single().ToDisplayString(m_DelegateSignatureFormat)) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field As Global.System.Action Public field2 As System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "Global.System.Action", code.IndexOf("Global.System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.DelegateName}, minimal:=True) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913_2() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field As Global.System.Action Public field2 As System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "System.Action", code.IndexOf("Global.System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.DelegateName}, minimal:=True) End Sub <WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")> <Fact> Public Sub Bug9913_3() Dim text = <compilation> <file name="a.vb"> Public Class Test Public Class System Public Class Action End Class End Class Public field2 As System.Action Public field As Global.System.Action End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("Test").Single().GetMembers("field2").Single(), FieldSymbol) Return field.Type End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "System.Action", code.IndexOf("System.Action", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <Fact()> Public Sub TestMinimalOfContextualKeywordAsIdentifier() Dim text = <compilation> <file name="a.vb"> Class Take Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Take").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub [Take].X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact()> Public Sub TestMinimalOfContextualKeywordAsIdentifierTypeKeyword() Dim text = <compilation> <file name="a.vb"> Class [Type] Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits [Type] End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Type").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Type.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) text = <compilation> <file name="a.vb"> Imports System Class Goo Public Bar as Type End Class </file> </compilation> findSymbol = Function(globalns) globalns.GetTypeMembers("Goo").Single().GetMembers("Bar").Single() code = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Goo.Bar As Type", code.IndexOf("Public Bar as Type", StringComparison.Ordinal), { SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName}, minimal:=True) End Sub <WorkItem(543938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543938")> <Fact> Public Sub Bug12025() Dim text = <compilation> <file name="a.vb"> Class CBase Public Overridable Property [Class] As Integer End Class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Class").Single(), PropertySymbol) Return field End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findSymbol, format, "Property CBase.Class As Integer", code.IndexOf("Public Overridable Property [Class] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) End Sub <Fact, WorkItem(544414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544414")> Public Sub Bug12724() Dim text = <compilation> <file name="a.vb"> Class CBase Public Overridable Property [Class] As Integer Public [Interface] As Integer Event [Event]() Public Overridable Sub [Sub]() Public Overridable Function [Function]() Class [Dim] End Class End Class </file> </compilation> Dim findProperty As Func(Of NamespaceSymbol, Symbol) = Function(globalns) Dim field = CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Class").Single(), PropertySymbol) Return field End Function Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.TypeQualificationStyle, genericsOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions, memberOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions, delegateStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.DelegateStyle, extensionMethodStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.ExtensionMethodStyle, parameterOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.ParameterOptions, propertyStyle:=SymbolDisplayFormat.MinimallyQualifiedFormat.PropertyStyle, localOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.LocalOptions, kindOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.KindOptions, miscellaneousOptions:=SymbolDisplayFormat.MinimallyQualifiedFormat.MiscellaneousOptions) Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription( text, findProperty, format, "Property CBase.Class As Integer", code.IndexOf("Public Overridable Property [Class] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findSub As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Sub").Single(), MethodSymbol) TestSymbolDescription( text, findSub, format, "Sub CBase.Sub()", code.IndexOf("Public Overridable Sub [Sub]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) Dim findFunction As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Function").Single(), MethodSymbol) TestSymbolDescription( text, findFunction, format, "Function CBase.Function() As Object", code.IndexOf("Public Overridable Function [Function]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findField As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Interface").Single(), FieldSymbol) TestSymbolDescription( text, findField, format, "CBase.Interface As Integer", code.IndexOf("Public [Interface] As Integer", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword}, minimal:=True) Dim findEvent As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Event").Single(), EventSymbol) TestSymbolDescription( text, findEvent, format, "Event CBase.Event()", code.IndexOf("Event [Event]()", StringComparison.Ordinal), {SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) Dim findClass As Func(Of NamespaceSymbol, Symbol) = Function(globalns) CType(globalns.GetTypeMembers("CBase").Single().GetMembers("Dim").Single(), NamedTypeSymbol) TestSymbolDescription( text, findClass, New SymbolDisplayFormat(typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces), "CBase.Dim", code.IndexOf("Class [Dim]", StringComparison.Ordinal), {SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName}, minimal:=False) End Sub <Fact, WorkItem(543806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543806")> Public Sub Bug11752() Dim text = <compilation> <file name="a.vb"> Class Explicit Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Explicit").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Explicit.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, minimal:=True) End Sub <Fact(), WorkItem(529764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529764")> Public Sub TypeParameterFromMetadata() Dim src1 = <compilation> <file name="lib.vb"> Public Class LibG(Of T) End Class </file> </compilation> Dim src2 = <compilation> <file name="use.vb"> Public Class Gen(Of V) Public Sub M(p as LibG(Of V)) End Sub Public Function F(p as Object) As Object End Function End Class </file> </compilation> Dim dummy = <compilation> <file name="app.vb"> </file> </compilation> Dim complib = CreateCompilationWithMscorlib40(src1) Dim compref = New VisualBasicCompilationReference(complib) Dim comp1 = CreateCompilationWithMscorlib40AndReferences(src2, references:={compref}) Dim mtdata = comp1.EmitToArray() Dim mtref = MetadataReference.CreateFromImage(mtdata) Dim comp2 = CreateCompilationWithMscorlib40AndReferences(dummy, references:={mtref}) Dim tsym1 = comp1.SourceModule.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Gen") Assert.NotNull(tsym1) Dim msym1 = tsym1.GetMember(Of MethodSymbol)("M") Assert.NotNull(msym1) ' Public Sub M(p As LibG(Of V)) ' C# is like - Gen(Of V).M(LibG(Of V)) Assert.Equal("Public Sub M(p As LibG(Of V))", msym1.ToDisplayString()) Dim tsym2 = comp2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Gen") Assert.NotNull(tsym2) Dim msym2 = tsym2.GetMember(Of MethodSymbol)("M") Assert.NotNull(msym2) Assert.Equal(msym1.ToDisplayString(), msym2.ToDisplayString()) End Sub <Fact, WorkItem(545625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545625")> Public Sub ReverseArrayRankSpecifiers() Dim text = <compilation> <file name="a.vb"> class C Private F as C()(,) end class </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetMember(Of NamedTypeSymbol)("C").GetMember(Of FieldSymbol)("F").Type Dim normalFormat As New SymbolDisplayFormat() Dim reverseFormat As New SymbolDisplayFormat( compilerInternalOptions:=SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers) TestSymbolDescription( text, findSymbol, normalFormat, "C()(,)", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) TestSymbolDescription( text, findSymbol, reverseFormat, "C(,)()", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation) End Sub <Fact> Public Sub TestMethodCSharp() Dim text = <text> class A { public void Goo(int a) { } } </text>.Value Dim format = New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeModifiers Or SymbolDisplayMemberOptions.IncludeAccessibility Or SymbolDisplayMemberOptions.IncludeType, kindOptions:=SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CreateCSharpCompilation("c", text) Dim a = DirectCast(comp.GlobalNamespace.GetMembers("A").Single(), ITypeSymbol) Dim goo = a.GetMembers("Goo").Single() Dim parts = VisualBasic.SymbolDisplay.ToDisplayParts(goo, format) Verify(parts, "Public Sub Goo(a As Integer)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact> Public Sub SupportSpeculativeSemanticModel() Dim text = <compilation> <file name="a.vb"> Class Explicit Class X Public Shared Sub Goo End Sub End Class End Class Class Z(Of T) Inherits Take End Class Module M Sub Main() Dim x = From y In "" Z(Of Integer).X.Goo ' Simplify Z(Of Integer).X End Sub End Module </file> </compilation> Dim findSymbol As Func(Of NamespaceSymbol, Symbol) = Function(globalns) globalns.GetTypeMembers("Explicit").Single(). GetTypeMembers("X").Single(). GetMembers("Goo").Single() Dim code As String = DirectCast(text.FirstNode, XElement).FirstNode.ToString TestSymbolDescription(text, findSymbol, Nothing, "Sub Explicit.X.Goo()", code.IndexOf("Z(Of Integer).X.Goo", StringComparison.Ordinal), { SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation}, useSpeculativeSemanticModel:=True, minimal:=True) End Sub <WorkItem(765287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765287")> <Fact> Public Sub TestCSharpSymbols() Dim csComp = CreateCSharpCompilation("CSharp", <![CDATA[ class Outer { class Inner<T> { } void M<U>() { } string P { set { } } int F; event System.Action E; delegate void D(); Missing Error() { } } ]]>) Dim outer = DirectCast(csComp.GlobalNamespace.GetMembers("Outer").Single(), INamedTypeSymbol) Dim type = outer.GetMembers("Inner").Single() Dim method = outer.GetMembers("M").Single() Dim [property] = outer.GetMembers("P").Single() Dim field = outer.GetMembers("F").Single() Dim [event] = outer.GetMembers("E").Single() Dim [delegate] = outer.GetMembers("D").Single() Dim [error] = outer.GetMembers("Error").Single() Assert.IsNotType(Of Symbol)(type) Assert.IsNotType(Of Symbol)(method) Assert.IsNotType(Of Symbol)([property]) Assert.IsNotType(Of Symbol)(field) Assert.IsNotType(Of Symbol)([event]) Assert.IsNotType(Of Symbol)([delegate]) Assert.IsNotType(Of Symbol)([error]) ' 1) Looks like VB. ' 2) Doesn't blow up. Assert.Equal("Outer.Inner(Of T)", VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) Assert.Equal("Sub Outer.M(Of U)()", VisualBasic.SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat)) Assert.Equal("WriteOnly Property Outer.P As System.String", VisualBasic.SymbolDisplay.ToDisplayString([property], SymbolDisplayFormat.TestFormat)) Assert.Equal("Outer.F As System.Int32", VisualBasic.SymbolDisplay.ToDisplayString(field, SymbolDisplayFormat.TestFormat)) Assert.Equal("Event Outer.E As System.Action", VisualBasic.SymbolDisplay.ToDisplayString([event], SymbolDisplayFormat.TestFormat)) Assert.Equal("Outer.D", VisualBasic.SymbolDisplay.ToDisplayString([delegate], SymbolDisplayFormat.TestFormat)) Assert.Equal("Function Outer.Error() As Missing", VisualBasic.SymbolDisplay.ToDisplayString([error], SymbolDisplayFormat.TestFormat)) End Sub <Fact> Public Sub FormatPrimitive() Assert.Equal("Nothing", SymbolDisplay.FormatPrimitive(Nothing, quoteStrings:=True, useHexadecimalNumbers:=True)) Assert.Equal("3", SymbolDisplay.FormatPrimitive(OutputKind.NetModule, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000003", SymbolDisplay.FormatPrimitive(OutputKind.NetModule, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("""x""c", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=True, useHexadecimalNumbers:=True)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("""x""c", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=True, useHexadecimalNumbers:=False)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x"c, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("x", SymbolDisplay.FormatPrimitive("x", quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("""x""", SymbolDisplay.FormatPrimitive("x", quoteStrings:=True, useHexadecimalNumbers:=False)) Assert.Equal("True", SymbolDisplay.FormatPrimitive(True, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(1, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000001", SymbolDisplay.FormatPrimitive(1, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CUInt(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H00000001", SymbolDisplay.FormatPrimitive(CUInt(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CByte(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H01", SymbolDisplay.FormatPrimitive(CByte(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CSByte(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H01", SymbolDisplay.FormatPrimitive(CSByte(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CShort(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0001", SymbolDisplay.FormatPrimitive(CShort(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CUShort(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0001", SymbolDisplay.FormatPrimitive(CUShort(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CLng(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0000000000000001", SymbolDisplay.FormatPrimitive(CLng(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1", SymbolDisplay.FormatPrimitive(CULng(1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("&H0000000000000001", SymbolDisplay.FormatPrimitive(CULng(1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(1.1, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(1.1, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CSng(1.1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CSng(1.1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CDec(1.1), quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("1.1", SymbolDisplay.FormatPrimitive(CDec(1.1), quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal("#1/1/2000 12:00:00 AM#", SymbolDisplay.FormatPrimitive(#1/1/2000#, quoteStrings:=False, useHexadecimalNumbers:=False)) Assert.Equal("#1/1/2000 12:00:00 AM#", SymbolDisplay.FormatPrimitive(#1/1/2000#, quoteStrings:=False, useHexadecimalNumbers:=True)) Assert.Equal(Nothing, SymbolDisplay.FormatPrimitive(New Object(), quoteStrings:=False, useHexadecimalNumbers:=False)) End Sub <Fact> Public Sub AllowDefaultLiteral() Dim text = <compilation> <file name="a.vb"> Class C Sub Method(Optional cancellationToken as CancellationToken = Nothing) End Sub End Class </file> </compilation> Dim formatWithoutAllowDefaultLiteral = SymbolDisplayFormat.MinimallyQualifiedFormat Assert.False(formatWithoutAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral)) Dim formatWithAllowDefaultLiteral = formatWithoutAllowDefaultLiteral.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral) Assert.True(formatWithAllowDefaultLiteral.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral)) ' Visual Basic doesn't have default expressions, so AllowDefaultLiteral does not change behavior Const ExpectedText As String = "Sub C.Method(cancellationToken As CancellationToken = Nothing)" TestSymbolDescription(text, FindSymbol("C.Method"), formatWithoutAllowDefaultLiteral, ExpectedText) TestSymbolDescription(text, FindSymbol("C.Method"), formatWithAllowDefaultLiteral, ExpectedText) End Sub <Fact()> Public Sub Tuple() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (Integer, String) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType), "f As (Int32, String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation) End Sub <WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")> <Fact()> Public Sub TupleWith1Arity() TestSymbolDescription( <compilation> <file name="a.vb"> Imports System Class C Private f As ValueTuple(Of Integer) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters), "f As ValueTuple(Of Int32)", 0, {SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation}, references:={MetadataReference.CreateFromImage(TestResources.NetFX.ValueTuple.tuplelib)}) End Sub <Fact()> Public Sub TupleWithNames() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (x As Integer, y As String) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat(memberOptions:=SymbolDisplayMemberOptions.IncludeType), "f As (x As Int32, y As String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub LongTupleWithSpecialTypes() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Private f As (Integer, String, Boolean, Byte, Long, ULong, Short, UShort) End Class </file> </compilation>, FindSymbol("C.f"), New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes), "f As (Integer, String, Boolean, Byte, Long, ULong, Short, UShort)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub TupleProperty() TestSymbolDescription( <compilation> <file name="a.vb"> Class C Property P As (Item1 As Integer, Item2 As String) End Class </file> </compilation>, FindSymbol("C.P"), New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes), "P As (Item1 As Integer, Item2 As String)", SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact()> Public Sub TupleQualifiedNames() Dim text = "Imports NAB = N.A.B Namespace N Class A Friend Class B End Class End Class Class C(Of T) ' offset 1 End Class End Namespace Class C Private f As (One As Integer, N.C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As N.A) ' offset 2 End Class" Dim source = <compilation> <file name="a.vb"><%= text %></file> </compilation> Dim format = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(source, references:={SystemRuntimeFacadeRef, ValueTupleRef}) comp.VerifyDiagnostics() Dim symbol = comp.GetMember("C.f") ' Fully qualified format. Verify( SymbolDisplay.ToDisplayParts(symbol, format), "f As (One As Integer, Global.N.C(Of (Object(), Two As Global.N.A.B)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As Global.N.A)") ' Minimally qualified format. Verify( SymbolDisplay.ToDisplayParts(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "C.f As (One As Integer, C(Of (Object(), Two As B)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As A)") ' ToMinimalDisplayParts. Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Verify( SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 1"), format), "f As (One As Integer, C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As A)") Verify( SymbolDisplay.ToMinimalDisplayParts(symbol, model, text.IndexOf("offset 2"), format), "f As (One As Integer, N.C(Of (Object(), Two As NAB)), Integer, Four As Object, Integer, Object, Integer, Object, Nine As N.A)") End Sub ' A tuple type symbol that is not Microsoft.CodeAnalysis.VisualBasic.Symbols.TupleTypeSymbol. <Fact()> Public Sub NonTupleTypeSymbol() Dim source = "class C { #pragma warning disable CS0169 (int Alice, string Bob) F; (int, string) G; #pragma warning restore CS0169 }" Dim format = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim comp = CreateCSharpCompilation(GetUniqueName(), source, referencedAssemblies:={MscorlibRef, SystemRuntimeFacadeRef, ValueTupleRef}) comp.VerifyDiagnostics() Dim type = comp.GlobalNamespace.GetTypeMembers("C").Single() Verify( SymbolDisplay.ToDisplayParts(type.GetMembers("F").Single(), format), "F As (Alice As Integer, Bob As String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) Verify( SymbolDisplay.ToDisplayParts(type.GetMembers("G").Single(), format), "G As (Integer, String)", SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation) End Sub <Fact> <WorkItem(23970, "https://github.com/dotnet/roslyn/pull/23970")> Public Sub MeDisplayParts() Dim Text = <compilation> <file name="b.vb"> Class A Sub M([Me] As Integer) Me.M([Me]) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(Text) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim invocation = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.Equal("Me.M([Me])", invocation.ToString()) Dim actualThis = DirectCast(invocation.Expression, MemberAccessExpressionSyntax).Expression Assert.Equal("Me", actualThis.ToString()) Verify( ToDisplayParts(model.GetSymbolInfo(actualThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "Me As A", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName) Dim escapedThis = invocation.ArgumentList.Arguments(0).GetExpression() Assert.Equal("[Me]", escapedThis.ToString()) Verify( ToDisplayParts(model.GetSymbolInfo(escapedThis).Symbol, SymbolDisplayFormat.MinimallyQualifiedFormat), "[Me] As Integer", SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End Sub ' SymbolDisplayMemberOptions.IncludeRef is ignored in VB. <WorkItem(11356, "https://github.com/dotnet/roslyn/issues/11356")> <Fact()> Public Sub RefReturn() Dim sourceA = "public delegate ref int D(); public class C { public ref int F(ref int i) => ref i; int _p; public ref int P => ref _p; public ref int this[int i] => ref _p; }" Dim compA = CreateCSharpCompilation(GetUniqueName(), sourceA) compA.VerifyDiagnostics() Dim refA = compA.EmitToImageReference() ' From C# symbols. RefReturnInternal(compA) Dim sourceB = <compilation> <file name="b.vb"> </file> </compilation> Dim compB = CompilationUtils.CreateCompilationWithMscorlib40(sourceB, references:={refA}) compB.VerifyDiagnostics() ' From VB symbols. RefReturnInternal(compB) End Sub Private Shared Sub RefReturnInternal(comp As Compilation) Dim formatWithRef = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeParameters Or SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeRef, parameterOptions:=SymbolDisplayParameterOptions.IncludeType Or SymbolDisplayParameterOptions.IncludeParamsRefOut, propertyStyle:=SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, delegateStyle:=SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Dim [global] = comp.GlobalNamespace Dim type = [global].GetTypeMembers("C").Single() Dim method = type.GetMembers("F").Single() Dim [property] = type.GetMembers("P").Single() Dim indexer = type.GetMembers().Where(Function(m) m.Kind = SymbolKind.Property AndAlso DirectCast(m, IPropertySymbol).IsIndexer).Single() Dim [delegate] = [global].GetTypeMembers("D").Single() ' Method with IncludeRef. ' https://github.com/dotnet/roslyn/issues/14683: missing ByRef for C# parameters. If comp.Language = "C#" Then Verify( SymbolDisplay.ToDisplayParts(method, formatWithRef), "ByRef F(Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) Else Verify( SymbolDisplay.ToDisplayParts(method, formatWithRef), "ByRef F(ByRef Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End If ' Property with IncludeRef. Verify( SymbolDisplay.ToDisplayParts([property], formatWithRef), "ReadOnly ByRef P As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) ' Indexer with IncludeRef. ' https://github.com/dotnet/roslyn/issues/14684: "this[]" for C# indexer. If comp.Language = "C#" Then Verify( SymbolDisplay.ToDisplayParts(indexer, formatWithRef), "ReadOnly ByRef this[](Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) Else Verify( SymbolDisplay.ToDisplayParts(indexer, formatWithRef), "ReadOnly ByRef Item(Integer) As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End If ' Delegate with IncludeRef. Verify( SymbolDisplay.ToDisplayParts([delegate], formatWithRef), "ByRef Function D() As Integer", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword) End Sub <Fact> Public Sub AliasInSpeculativeSemanticModel() Dim text = <compilation> <file name="a.vb"> Imports A = N.M Namespace N.M Class B End Class End Namespace Class C Shared Sub M() Dim o = 1 End Sub End Class </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockBaseSyntax)().First() Dim position = methodDecl.Statements(0).SpanStart tree = VisualBasicSyntaxTree.ParseText(" Class C Shared Sub M() Dim o = 1 End Sub End Class") methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MethodBlockBaseSyntax)().First() Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(position, methodDecl, model)) Dim symbol = comp.GetMember(Of NamedTypeSymbol)("N.M.B") position = methodDecl.Statements(0).SpanStart Dim description = symbol.ToMinimalDisplayParts(model, position, SymbolDisplayFormat.MinimallyQualifiedFormat) Verify(description, "A.B", SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Operator, SymbolDisplayPartKind.ClassName) End Sub #Region "Helpers" Private Shared Sub TestSymbolDescription( text As XElement, findSymbol As Func(Of NamespaceSymbol, Symbol), format As SymbolDisplayFormat, expectedText As String, position As Integer, kinds As SymbolDisplayPartKind(), Optional minimal As Boolean = False, Optional useSpeculativeSemanticModel As Boolean = False, Optional references As IEnumerable(Of MetadataReference) = Nothing) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text) If references IsNot Nothing Then comp = comp.AddReferences(references.ToArray()) End If Dim symbol = findSymbol(comp.GlobalNamespace) Dim description As ImmutableArray(Of SymbolDisplayPart) If minimal Then Dim tree = comp.SyntaxTrees.First() Dim semanticModel As SemanticModel = comp.GetSemanticModel(tree) Dim tokenPosition = tree.GetRoot().FindToken(position).SpanStart If useSpeculativeSemanticModel Then Dim newTree = tree.WithChangedText(tree.GetText()) Dim token = newTree.GetRoot().FindToken(position) tokenPosition = token.SpanStart Dim member = token.Parent.FirstAncestorOrSelf(Of MethodBlockBaseSyntax)() Dim speculativeModel As SemanticModel = Nothing semanticModel.TryGetSpeculativeSemanticModelForMethodBody(member.BlockStatement.Span.End, member, speculativeModel) semanticModel = speculativeModel End If description = VisualBasic.SymbolDisplay.ToMinimalDisplayParts(symbol, semanticModel, tokenPosition, format) Else description = VisualBasic.SymbolDisplay.ToDisplayParts(symbol, format) End If Verify(description, expectedText, kinds) End Sub Private Shared Sub TestSymbolDescription( text As XElement, findSymbol As Func(Of NamespaceSymbol, Symbol), format As SymbolDisplayFormat, expectedText As String, ParamArray kinds As SymbolDisplayPartKind()) Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(text, references:={TestMetadata.Net40.SystemCore}) ' symbol: Dim symbol = findSymbol(comp.GlobalNamespace) Dim description = VisualBasic.SymbolDisplay.ToDisplayParts(symbol, format) Verify(description, expectedText, kinds) ' retargeted symbol: Dim retargetedAssembly = New Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting.RetargetingAssemblySymbol(comp.SourceAssembly, isLinked:=False) retargetedAssembly.SetCorLibrary(comp.SourceAssembly.CorLibrary) Dim retargetedSymbol = findSymbol(retargetedAssembly.GlobalNamespace) Dim retargetedDescription = VisualBasic.SymbolDisplay.ToDisplayParts(retargetedSymbol, format) Verify(retargetedDescription, expectedText, kinds) End Sub Private Shared Function Verify(parts As ImmutableArray(Of SymbolDisplayPart), expectedText As String, ParamArray kinds As SymbolDisplayPartKind()) As ImmutableArray(Of SymbolDisplayPart) Assert.Equal(expectedText, parts.ToDisplayString()) If (kinds.Length > 0) Then AssertEx.Equal(kinds, parts.Select(Function(p) p.Kind), itemInspector:=Function(p) $" SymbolDisplayPartKind.{p}") End If Return parts End Function Private Shared Function FindSymbol(qualifiedName As String) As Func(Of NamespaceSymbol, Symbol) Return Function([namespace]) [namespace].GetMember(qualifiedName) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/CommandLine/CommandLineArgumentsTests.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.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Public Class CommandLineArgumentsTests Inherits BasicTestBase <Fact()> <WorkItem(543297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543297")> <WorkItem(546751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546751")> Public Sub TestParseConditionalCompilationSymbols1() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text As String Dim dict As IReadOnlyDictionary(Of String, Object) text = "Nightly=1, Alpha=2, Beta=3, RC=4, Release=5, Config=Nightly, Config2=""Nightly"", Framework = 4" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(8, dict.Count) Assert.Equal(1, dict("Config")) Assert.Equal(GetType(Integer), (dict("Config")).GetType) Assert.Equal("Nightly", dict("Config2")) Assert.Equal(GetType(String), (dict("Config2")).GetType) Assert.Equal(4, dict("Framework")) Assert.Equal(GetType(Integer), (dict("Framework")).GetType) Assert.Equal(2, dict("Alpha")) Assert.Equal(GetType(Integer), (dict("Alpha")).GetType) text = "OnlyEqualsNoValue1, OnlyEqualsNoValue2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("OnlyEqualsNoValue1")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue1")).GetType) Assert.Equal(True, dict("OnlyEqualsNoValue2")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue2")).GetType) text = ",,,,,goo=bar,,,,,,,,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) text = ",,,=,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "= ^^ ^^ ")) Dim previousSymbols As New Dictionary(Of String, Object)() From {{"Goo", 1}, {"Bar", "Goo"}} text = ",,,=,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors, previousSymbols) Assert.Equal(2, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "= ^^ ^^ ")) text = "OnlyEqualsNoValue1=, Bar=goo" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "OnlyEqualsNoValue1= ^^ ^^ ")) text = "Bar=goo, OnlyEqualsNoValue1=" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "OnlyEqualsNoValue1= ^^ ^^ ")) text = """""OnlyEqualsNoValue1""""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("OnlyEqualsNoValue1")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue1")).GetType) text = "key=\""value\""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal("value", dict("key")) Assert.Equal(GetType(String), (dict("key")).GetType) text = "then=bar" ' keyword :) dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "then ^^ ^^ =bar")) text = "bar=then" ' keyword :) dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Syntax error in conditional compilation expression.", "bar= ^^ ^^ then")) text = "GOO:BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) text = "GOO::::::::BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) text = "GOO=23::,,:::BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "GOO=23:: ^^ , ^^ ,:::")) text = "GOO=23,:BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "GOO=23, ^^ : ^^ BAR")) text = "GOO::BAR,,BAZ" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(3, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) Assert.Equal(True, dict("BAZ")) Assert.Equal(GetType(Boolean), (dict("BAZ")).GetType) End Sub <Fact()> Public Sub TestParseConditionalCompilationSymbols_expressions() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text As String Dim dict As IReadOnlyDictionary(Of String, Object) text = "bar=1+2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(3, dict("bar")) text = "bar=1.2+1.0" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(2.2, dict("bar")) text = "goo=1,bar=goo+2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(3, dict("bar")) text = "bar=goo+2,goo=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(2, dict("bar")) ' goo is known, but not yet initialized ' dev 10 does not crash here, not sure what the value is text = "bar=1/0" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(0, errors.Count) Assert.Equal("A", dict("A")) Assert.Equal("B", dict("B")) Assert.Equal("ABC", dict("T")) text = "BAR0=nothing, BAR1=2#, BAR2=000.03232323@, BAR3A=True, BAR3b=BAR3A OrElse False" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(5, dict.Count) Assert.Equal(Nothing, dict("BAR0")) 'Assert.Equal(GetType(Object), (dict("BAR0")).GetType) Assert.Equal(2.0#, dict("BAR1")) Assert.Equal(GetType(Double), (dict("BAR1")).GetType) Assert.Equal(0.03232323@, dict("BAR2")) Assert.Equal(GetType(Decimal), (dict("BAR2")).GetType) Assert.Equal(True, dict("BAR3b")) Assert.Equal(GetType(Boolean), (dict("BAR3b")).GetType) text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C"",RRR=1+""3""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Conversion from 'String' to 'Double' cannot occur in a constant expression.", "RRR=1+""3"" ^^ ^^ ")) text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C"",X=IF(1,,,,,RRR=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify( Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("')' expected.", "X=IF(1,,,,,RRR=1 ^^ ^^ "), Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("'If' operator requires either two or three operands.", "X=IF(1,,,,,RRR=1 ^^ ^^ "), Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "X=IF(1,,,,,RRR=1 ^^ ^^ ")) text = "A=CHR(128)" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "A=CHR ^^ ^^ (128)")) text = "A=ASCW(""G"")" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "A=ASCW ^^ ^^ (""G"")")) text = "A=1--1,B=1 1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "B=1 ^^ ^^ 1")) text = "A=1--1,B=1 C=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "B=1 ^^ ^^ C=1")) text = "A=111111111111111111111111" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Overflow.", "A=111111111111111111111111 ^^ ^^ ")) text = "A= 2 + " + vbCrLf + "2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Syntax error in conditional compilation expression.", "A= 2 + " + vbCrLf + " ^^ ^^ 2")) text = "A= 2 + _" + vbCrLf + "2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(1, dict.Count) Assert.Equal(4, dict("A")) End Sub <Fact(), WorkItem(546034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546034"), WorkItem(780817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780817")> Public Sub TestParseConditionalCompilationCaseInsensitiveSymbols() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text = "Blah,blah" Dim dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, errors.Count) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("Blah")) Assert.Equal(True, dict("blah")) Dim source = <compilation name="TestArrayLiteralInferredType"> <file name="a.vb"> <![CDATA[ Imports System Module M1 Sub Main #if Blah Console.WriteLine("Blah") #end if #if blah Console.WriteLine("blah") #end if End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, options:=TestOptions.ReleaseExe, parseOptions:=New VisualBasicParseOptions(preprocessorSymbols:=dict.AsImmutable())) CompileAndVerify(comp, expectedOutput:=<![CDATA[ Blah blah ]]>) text = "Blah=false,blah=true" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, errors.Count) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("Blah")) Assert.Equal(True, dict("blah")) comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, options:=TestOptions.ReleaseExe, parseOptions:=New VisualBasicParseOptions(preprocessorSymbols:=dict.AsImmutable())) CompileAndVerify(comp, expectedOutput:=<![CDATA[ Blah blah ]]>) End Sub <Fact()> <WorkItem(546035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546035")> Public Sub TestParseConditionalCompilationSymbolsInSingleQuote() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text = "'Blah'" Dim dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", " ^^ 'Blah' ^^ ")) 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.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Public Class CommandLineArgumentsTests Inherits BasicTestBase <Fact()> <WorkItem(543297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543297")> <WorkItem(546751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546751")> Public Sub TestParseConditionalCompilationSymbols1() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text As String Dim dict As IReadOnlyDictionary(Of String, Object) text = "Nightly=1, Alpha=2, Beta=3, RC=4, Release=5, Config=Nightly, Config2=""Nightly"", Framework = 4" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(8, dict.Count) Assert.Equal(1, dict("Config")) Assert.Equal(GetType(Integer), (dict("Config")).GetType) Assert.Equal("Nightly", dict("Config2")) Assert.Equal(GetType(String), (dict("Config2")).GetType) Assert.Equal(4, dict("Framework")) Assert.Equal(GetType(Integer), (dict("Framework")).GetType) Assert.Equal(2, dict("Alpha")) Assert.Equal(GetType(Integer), (dict("Alpha")).GetType) text = "OnlyEqualsNoValue1, OnlyEqualsNoValue2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("OnlyEqualsNoValue1")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue1")).GetType) Assert.Equal(True, dict("OnlyEqualsNoValue2")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue2")).GetType) text = ",,,,,goo=bar,,,,,,,,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) text = ",,,=,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "= ^^ ^^ ")) Dim previousSymbols As New Dictionary(Of String, Object)() From {{"Goo", 1}, {"Bar", "Goo"}} text = ",,,=,,," dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors, previousSymbols) Assert.Equal(2, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "= ^^ ^^ ")) text = "OnlyEqualsNoValue1=, Bar=goo" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "OnlyEqualsNoValue1= ^^ ^^ ")) text = "Bar=goo, OnlyEqualsNoValue1=" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "OnlyEqualsNoValue1= ^^ ^^ ")) text = """""OnlyEqualsNoValue1""""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("OnlyEqualsNoValue1")) Assert.Equal(GetType(Boolean), (dict("OnlyEqualsNoValue1")).GetType) text = "key=\""value\""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, dict.Count) Assert.Equal("value", dict("key")) Assert.Equal(GetType(String), (dict("key")).GetType) text = "then=bar" ' keyword :) dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "then ^^ ^^ =bar")) text = "bar=then" ' keyword :) dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Syntax error in conditional compilation expression.", "bar= ^^ ^^ then")) text = "GOO:BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) text = "GOO::::::::BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(2, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) text = "GOO=23::,,:::BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "GOO=23:: ^^ , ^^ ,:::")) text = "GOO=23,:BAR" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(1, errors.Count) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "GOO=23, ^^ : ^^ BAR")) text = "GOO::BAR,,BAZ" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(3, dict.Count) Assert.Equal(True, dict("GOO")) Assert.Equal(GetType(Boolean), (dict("GOO")).GetType) Assert.Equal(True, dict("BAR")) Assert.Equal(GetType(Boolean), (dict("BAR")).GetType) Assert.Equal(True, dict("BAZ")) Assert.Equal(GetType(Boolean), (dict("BAZ")).GetType) End Sub <Fact()> Public Sub TestParseConditionalCompilationSymbols_expressions() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text As String Dim dict As IReadOnlyDictionary(Of String, Object) text = "bar=1+2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(3, dict("bar")) text = "bar=1.2+1.0" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(2.2, dict("bar")) text = "goo=1,bar=goo+2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(3, dict("bar")) text = "bar=goo+2,goo=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(2, dict("bar")) ' goo is known, but not yet initialized ' dev 10 does not crash here, not sure what the value is text = "bar=1/0" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(0, errors.Count) Assert.Equal("A", dict("A")) Assert.Equal("B", dict("B")) Assert.Equal("ABC", dict("T")) text = "BAR0=nothing, BAR1=2#, BAR2=000.03232323@, BAR3A=True, BAR3b=BAR3A OrElse False" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(5, dict.Count) Assert.Equal(Nothing, dict("BAR0")) 'Assert.Equal(GetType(Object), (dict("BAR0")).GetType) Assert.Equal(2.0#, dict("BAR1")) Assert.Equal(GetType(Double), (dict("BAR1")).GetType) Assert.Equal(0.03232323@, dict("BAR2")) Assert.Equal(GetType(Decimal), (dict("BAR2")).GetType) Assert.Equal(True, dict("BAR3b")) Assert.Equal(GetType(Boolean), (dict("BAR3b")).GetType) text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C"",RRR=1+""3""" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Conversion from 'String' to 'Double' cannot occur in a constant expression.", "RRR=1+""3"" ^^ ^^ ")) text = "A=""A"",B=""B"",T=IF(1>0, A, B)+B+""C"",X=IF(1,,,,,RRR=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify( Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("')' expected.", "X=IF(1,,,,,RRR=1 ^^ ^^ "), Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("'If' operator requires either two or three operands.", "X=IF(1,,,,,RRR=1 ^^ ^^ "), Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Expression expected.", "X=IF(1,,,,,RRR=1 ^^ ^^ ")) text = "A=CHR(128)" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "A=CHR ^^ ^^ (128)")) text = "A=ASCW(""G"")" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "A=ASCW ^^ ^^ (""G"")")) text = "A=1--1,B=1 1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "B=1 ^^ ^^ 1")) text = "A=1--1,B=1 C=1" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("End of statement expected.", "B=1 ^^ ^^ C=1")) text = "A=111111111111111111111111" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Overflow.", "A=111111111111111111111111 ^^ ^^ ")) text = "A= 2 + " + vbCrLf + "2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Syntax error in conditional compilation expression.", "A= 2 + " + vbCrLf + " ^^ ^^ 2")) text = "A= 2 + _" + vbCrLf + "2" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify() Assert.Equal(1, dict.Count) Assert.Equal(4, dict("A")) End Sub <Fact(), WorkItem(546034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546034"), WorkItem(780817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780817")> Public Sub TestParseConditionalCompilationCaseInsensitiveSymbols() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text = "Blah,blah" Dim dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, errors.Count) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("Blah")) Assert.Equal(True, dict("blah")) Dim source = <compilation name="TestArrayLiteralInferredType"> <file name="a.vb"> <![CDATA[ Imports System Module M1 Sub Main #if Blah Console.WriteLine("Blah") #end if #if blah Console.WriteLine("blah") #end if End Sub End Module ]]></file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, options:=TestOptions.ReleaseExe, parseOptions:=New VisualBasicParseOptions(preprocessorSymbols:=dict.AsImmutable())) CompileAndVerify(comp, expectedOutput:=<![CDATA[ Blah blah ]]>) text = "Blah=false,blah=true" dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) Assert.Equal(0, errors.Count) Assert.Equal(1, dict.Count) Assert.Equal(True, dict("Blah")) Assert.Equal(True, dict("blah")) comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, options:=TestOptions.ReleaseExe, parseOptions:=New VisualBasicParseOptions(preprocessorSymbols:=dict.AsImmutable())) CompileAndVerify(comp, expectedOutput:=<![CDATA[ Blah blah ]]>) End Sub <Fact()> <WorkItem(546035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546035")> Public Sub TestParseConditionalCompilationSymbolsInSingleQuote() Dim errors As IEnumerable(Of Diagnostic) = Nothing Dim text = "'Blah'" Dim dict = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(text, errors) errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", " ^^ 'Blah' ^^ ")) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedMeTests.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.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class HoistedMeTests Inherits ExpressionCompilerTestBase <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceIterator_NoCapturing() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceAsync_NoCapturing() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(""a"") End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceLambda_NoCapturing() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(1, 2) a() End Sub End Class " ' This test documents the fact that, as in dev12, "Me" ' is unavailable while stepping through the lambda. It ' would be preferable if it were. VerifyNoMe(source, "C._Closure$__._Lambda$__1-0") End Sub <Fact()> Public Sub InstanceLambda_NoCapturingExceptThis() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(Me.GetHashCode(), 2) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__1-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_CapturedMe() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact> Public Sub InstanceAsync_CapturedMe() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_DisplayClass() Const source = " Class C Private x As Integer Sub M(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_NoDisplayClass() Const source = " Class C Private x As Integer Sub M() Dim a As System.Action = Sub() Equals(x, 1) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__2-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_Generic() Const source = " Class C(Of T) Iterator Function F(Of U)() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact> Public Sub InstanceAsync_Generic() Const source = " Imports System Imports System.Threading.Tasks Class C(Of T) Async Function F(Of U)() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C(Of T).VB$StateMachine_1_F(Of U) V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_Generic() Const source = " Class C(Of T) Private x As Integer Sub M(Of U)(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T)._Closure$__2-0(Of $CLS0).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C(Of T)", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceIterator_ExplicitInterfaceImplementation() Const source = " Interface I Function F() As System.Collections.IEnumerable End Interface Class C : Implements I Iterator Function F() As System.Collections.IEnumerable Implements I.F Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceAsync_ExplicitInterfaceImplementation() Const source = " Imports System Imports System.Threading.Tasks Interface I Function F() As Task End Interface Class C : Implements I Async Function F() As Task Implements I.F Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_ExplicitInterfaceImplementation() Const source = " Interface I Sub M(y As Integer) End Interface Class C : Implements I Private x As Integer Sub M(y As Integer) Implements I.M Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact> Public Sub SharedIterator() Const source = " Module M Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub SharedAsync() Const source = " Imports System Imports System.Threading.Tasks Module M Async Function F() As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub SharedLambda() Const source = " Module M Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <Fact> Public Sub ExtensionIterator() Const source = " Module M <System.Runtime.CompilerServices.Extension> Iterator Function F(x As Integer) As System.Collections.IEnumerable Yield x End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub ExtensionAsync() Const source = " Imports System Imports System.Threading.Tasks Module M <System.Runtime.CompilerServices.Extension> Async Function F(x As Integer) As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub ExtensionLambda() Const source = " Module M <System.Runtime.CompilerServices.Extension> Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")> <Fact> Public Sub OldStyleNonCapturingLambda() Const ilSource = " .class public auto ansi C extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public instance void M() cil managed { ldnull throw } .method private specialname static int32 _Lambda$__1() cil managed { ldnull throw } } // end of class C " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef}) Dim context = CreateMethodContext(runtime, "C._Lambda$__1") VerifyNoMe(context) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_HasThis() Const source = " Imports System Class C Private _toBeCaptured As Integer Private _f As Integer = (Function(x) (Function() _toBeCaptured + x + 1)() + 1)(1) Public Sub New() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 2)() + 1)(1) End Sub Protected Overrides Sub Finalize() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 3)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() _toBeCaptured + x + 4)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() _toBeCaptured + x + 5)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 6)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 7)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 8)() + 1)(1) End RaiseEvent End Event End Class " Const expectedILTemplate = " {{ // Code size 7 (0x7) .maxstack 1 .locals init (Object V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C.{0}.$VB$Me As C"" IL_0006: ret }} " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Dim dummyComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences((<Compilation/>), {comp.EmitToImageReference()}, compOptions) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) Dim expectedIL = String.Format(expectedILTemplate, displayClassName) VerifyHasMe(context, "C", expectedIL) Next Next End Sub) End Sub <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_NoThis() Const source = " Imports System Module M Private _f As Integer = (Function(x) (Function() x + 1)() + 1)(1) Sub New() Dim l As Integer = (Function(x) (Function() x + 2)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() x + 3)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() x + 4)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 5)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 6)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() x + 7)() + 1)(1) End RaiseEvent End Event End Module " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim dummyComp As VisualBasicCompilation = MakeDummyCompilation(comp) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("M") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("M.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) VerifyNoMe(context) Next Next End Sub) End Sub Private Sub VerifyHasMe(source As String, moveNextMethodName As String, expectedType As String, expectedIL As String) Dim sourceCompilation = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(sourceCompilation, Sub(runtime) VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL) End Sub) ' Now recompile and test CompileExpression with optimized code. WithRuntimeInstance(sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release)), Sub(runtime) ' In VB, "Me" is never optimized away. VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL:=Nothing) End Sub) End Sub Private Sub VerifyHasMe(context As EvaluationContext, expectedType As String, expectedIL As String) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) Assert.NotEqual(0, assembly.Count) Dim localAndMethod = locals.Single(Function(l) l.LocalName = "Me") Dim methods = testData.GetMethodsByName() If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL) End If locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Null(errorMessage) If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains("<>m0")).Value, expectedType, expectedIL) End If End Sub Private Shared Sub VerifyMethodData(methodData As CompilationTestData.MethodData, expectedType As String, expectedIL As String) methodData.VerifyIL(expectedIL) Dim method As MethodSymbol = DirectCast(methodData.Method, MethodSymbol) VerifyTypeParameters(method) Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString()) End Sub Private Sub VerifyNoMe(source As String, moveNextMethodName As String) Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) VerifyNoMe(CreateMethodContext(runtime, moveNextMethodName)) End Sub) End Sub Private Shared Sub VerifyNoMe(context As EvaluationContext) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) AssertEx.None(locals, Function(l) l.LocalName.Contains("Me")) locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'Me' is not valid within a Module.", "error BC30043: 'Me' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyBase.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'MyBase' is not valid within a Module.", "error BC30043: 'MyBase' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyClass.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC30470: 'MyClass' cannot be used outside of a class.", "error BC32001: 'MyClass' is not valid within a Module.", "error BC30043: 'MyClass' is valid only within an instance method." }) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInIterator() Const source = " Class C Private x As Object Iterator Function F() As System.Collections.IEnumerable Yield Me.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInLambda() Const source = " Class C Private x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C.x As Object"" IL_0006: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class C Private x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInIterator() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Iterator Function F() As System.Collections.IEnumerable Yield MyBase.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, Derived.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInLambda() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""Base.x As Integer"" IL_0006: ret } ") End Sub) End Sub <Fact> Public Sub IteratorOverloading_Parameters1() Const source = " Imports System.Collections Public Class C Public Iterator Function M() As IEnumerable Yield Me End Function Public Function M(x As Integer) As IEnumerable Return Nothing End Function End Class " CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub IteratorOverloading_Parameters2() ' Same as above, but declarations reversed. Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function Public Iterator Function M() As IEnumerable Yield Me End Function End Class " ' NB: We pick the wrong overload, but it doesn't matter because ' the methods have the same characteristics. ' Also, we don't require this behavior, we're just documenting it. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 1) End Sub <Fact> Public Sub IteratorOverloading_Sharedness() Const source = " Imports System.Collections Public Class C Public Shared Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsShared) End Sub <Fact> Public Sub IteratorOverloading_MustOverrideness() Const source = " Imports System.Collections Public MustInherit Class C Public MustOverride Function M(x As Integer) As IEnumerable ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsMustOverride) End Sub <Fact> Public Sub IteratorOverloading_Arity1() Const source = " Imports System.Collections Public Class C Public Function M(Of T)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 0) End Sub <Fact> Public Sub IteratorOverloading_Arity2() Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 1) End Sub <Fact> Public Sub IteratorOverloading_Constraints1() Const source = " Imports System.Collections Public Class C Public Function M(Of T As Structure)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As Class)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.TypeParameters.Single().HasReferenceTypeConstraint) End Sub <Fact> Public Sub IteratorOverloading_Constraints2() Const source = " Imports System.Collections Imports System.Collections.Generic Public Class C ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As IEnumerable(Of U), U As Class)() As IEnumerable Yield Me End Function End Class " ' NOTE: this isn't the feature we're switching on, but it is a convenient differentiator. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub LambdaOverloading_NonGeneric() Const source = " Public Class C Public Sub M(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " ' Note: We're picking the first method with the correct generic arity, etc. CheckLambdaOverloading(source, Function(m) m.MethodKind = MethodKind.Constructor) End Sub <Fact> Public Sub LambdaOverloading_Generic() Const source = " Public Class C Public Sub M(Of T)(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " CheckLambdaOverloading(source, Function(m) m.Arity = 1) End Sub Private Shared Sub CheckIteratorOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, Function(m) m.Name = "M" AndAlso isDesiredOverload(m), Function(originalType) Dim stateMachineType = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)) Return stateMachineType.GetMember(Of MethodSymbol)("MoveNext") End Function) End Sub Private Shared Sub CheckLambdaOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, isDesiredOverload, Function(originalType) Dim displayClass As NamedTypeSymbol = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) Return displayClass.GetMembers().OfType(Of MethodSymbol).Single(AddressOf IsLambda) End Function) End Sub Private Shared Function IsLambda(method As MethodSymbol) As Boolean Return method.Name.StartsWith(GeneratedNameConstants.LambdaMethodNamePrefix, StringComparison.Ordinal) End Function Private Shared Sub CheckOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean), getSynthesizedMethod As Func(Of NamedTypeSymbol, MethodSymbol)) Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim dummyComp = MakeDummyCompilation(comp) Dim originalType = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim desiredMethod = originalType.GetMembers().OfType(Of MethodSymbol).Single(isDesiredOverload) Dim synthesizedMethod As MethodSymbol = getSynthesizedMethod(originalType) Dim guessedMethod = CompilationContext.GetSubstitutedSourceMethod(synthesizedMethod, sourceMethodMustBeInstance:=True) Assert.Equal(desiredMethod, guessedMethod.OriginalDefinition) End Sub Private Shared Function MakeDummyCompilation(comp As VisualBasicCompilation) As VisualBasicCompilation Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Return CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(<Compilation/>, {comp.EmitToImageReference()}, compOptions) 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 Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class HoistedMeTests Inherits ExpressionCompilerTestBase <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceIterator_NoCapturing() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceAsync_NoCapturing() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(""a"") End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <Fact> Public Sub InstanceLambda_NoCapturing() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(1, 2) a() End Sub End Class " ' This test documents the fact that, as in dev12, "Me" ' is unavailable while stepping through the lambda. It ' would be preferable if it were. VerifyNoMe(source, "C._Closure$__._Lambda$__1-0") End Sub <Fact()> Public Sub InstanceLambda_NoCapturingExceptThis() Const source = " Class C Sub M() Dim a As System.Action = Sub() Equals(Me.GetHashCode(), 2) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__1-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_CapturedMe() Const source = " Class C Iterator Function F() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact> Public Sub InstanceAsync_CapturedMe() Const source = " Imports System Imports System.Threading.Tasks Class C Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_DisplayClass() Const source = " Class C Private x As Integer Sub M(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_CapturedMe_NoDisplayClass() Const source = " Class C Private x As Integer Sub M() Dim a As System.Action = Sub() Equals(x, 1) a() End Sub End Class " Const expectedIL = " { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } " VerifyHasMe(source, "C._Lambda$__2-0", "C", expectedIL) End Sub <Fact> Public Sub InstanceIterator_Generic() Const source = " Class C(Of T) Iterator Function F(Of U)() As System.Collections.IEnumerable Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact> Public Sub InstanceAsync_Generic() Const source = " Imports System Imports System.Threading.Tasks Class C(Of T) Async Function F(Of U)() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C(Of T).VB$StateMachine_1_F(Of U) V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T).VB$StateMachine_1_F(Of U).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C(Of T)", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_Generic() Const source = " Class C(Of T) Private x As Integer Sub M(Of U)(y As Integer) Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C(Of T)._Closure$__2-0(Of $CLS0).$VB$Me As C(Of T)"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C(Of T)", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceIterator_ExplicitInterfaceImplementation() Const source = " Interface I Function F() As System.Collections.IEnumerable End Interface Class C : Implements I Iterator Function F() As System.Collections.IEnumerable Implements I.F Yield Me End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub ' Note: Not actually an issue in VB, since the name isn't mangled. <Fact> Public Sub InstanceAsync_ExplicitInterfaceImplementation() Const source = " Imports System Imports System.Threading.Tasks Interface I Function F() As Task End Interface Class C : Implements I Async Function F() As Task Implements I.F Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_1_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_1_F.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C.VB$StateMachine_1_F.MoveNext", "C", expectedIL) End Sub <Fact()> Public Sub InstanceLambda_ExplicitInterfaceImplementation() Const source = " Interface I Sub M(y As Integer) End Interface Class C : Implements I Private x As Integer Sub M(y As Integer) Implements I.M Dim a As System.Action = Sub() Equals(x, y) a() End Sub End Class " Const expectedIL = " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C"" IL_0006: ret } " VerifyHasMe(source, "C._Closure$__2-0._Lambda$__0", "C", expectedIL) End Sub <Fact> Public Sub SharedIterator() Const source = " Module M Iterator Function F() As System.Collections.IEnumerable Yield 1 End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub SharedAsync() Const source = " Imports System Imports System.Threading.Tasks Module M Async Function F() As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub SharedLambda() Const source = " Module M Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <Fact> Public Sub ExtensionIterator() Const source = " Module M <System.Runtime.CompilerServices.Extension> Iterator Function F(x As Integer) As System.Collections.IEnumerable Yield x End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact> Public Sub ExtensionAsync() Const source = " Imports System Imports System.Threading.Tasks Module M <System.Runtime.CompilerServices.Extension> Async Function F(x As Integer) As Task Await Console.Out.WriteLineAsync(""A"") End Function End Module " VerifyNoMe(source, "M.VB$StateMachine_0_F.MoveNext") End Sub <Fact()> Public Sub ExtensionLambda() Const source = " Module M <System.Runtime.CompilerServices.Extension> Sub M(y As Integer) Dim a As System.Action = Sub() Equals(1, y) a() End Sub End Module " VerifyNoMe(source, "M._Closure$__0-0._Lambda$__0") End Sub <WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")> <Fact> Public Sub OldStyleNonCapturingLambda() Const ilSource = " .class public auto ansi C extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public instance void M() cil managed { ldnull throw } .method private specialname static int32 _Lambda$__1() cil managed { ldnull throw } } // end of class C " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef}) Dim context = CreateMethodContext(runtime, "C._Lambda$__1") VerifyNoMe(context) End Sub <WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")> <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_HasThis() Const source = " Imports System Class C Private _toBeCaptured As Integer Private _f As Integer = (Function(x) (Function() _toBeCaptured + x + 1)() + 1)(1) Public Sub New() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 2)() + 1)(1) End Sub Protected Overrides Sub Finalize() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 3)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() _toBeCaptured + x + 4)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() _toBeCaptured + x + 5)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 6)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 7)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() _toBeCaptured + x + 8)() + 1)(1) End RaiseEvent End Event End Class " Const expectedILTemplate = " {{ // Code size 7 (0x7) .maxstack 1 .locals init (Object V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C.{0}.$VB$Me As C"" IL_0006: ret }} " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Dim dummyComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences((<Compilation/>), {comp.EmitToImageReference()}, compOptions) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) Dim expectedIL = String.Format(expectedILTemplate, displayClassName) VerifyHasMe(context, "C", expectedIL) Next Next End Sub) End Sub <WorkItem(1069554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069554")> <Fact> Public Sub LambdaLocations_NoThis() Const source = " Imports System Module M Private _f As Integer = (Function(x) (Function() x + 1)() + 1)(1) Sub New() Dim l As Integer = (Function(x) (Function() x + 2)() + 1)(1) End Sub Public Property P As Integer Get Return (Function(x) (Function() x + 3)() + 1)(1) End Get Set(value As Integer) value = (Function(x) (Function() x + 4)() + 1)(1) End Set End Property Public Custom Event E As Action AddHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 5)() + 1)(1) End AddHandler RemoveHandler(value As Action) Dim l As Integer = (Function(x) (Function() x + 6)() + 1)(1) End RemoveHandler RaiseEvent() Dim l As Integer = (Function(x) (Function() x + 7)() + 1)(1) End RaiseEvent End Event End Module " Dim comp = CreateEmptyCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, MsvbRef}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim dummyComp As VisualBasicCompilation = MakeDummyCompilation(comp) Dim typeC = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("M") Dim displayClassTypes = typeC.GetMembers().OfType(Of NamedTypeSymbol)() Assert.True(displayClassTypes.Any()) For Each displayClassType In displayClassTypes Dim displayClassName = displayClassType.Name Assert.True(displayClassName.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) For Each displayClassMethod In displayClassType.GetMembers().OfType(Of MethodSymbol)().Where(AddressOf IsLambda) Dim lambdaMethodName = String.Format("M.{0}.{1}", displayClassName, displayClassMethod.Name) Dim context = CreateMethodContext(runtime, lambdaMethodName) VerifyNoMe(context) Next Next End Sub) End Sub Private Sub VerifyHasMe(source As String, moveNextMethodName As String, expectedType As String, expectedIL As String) Dim sourceCompilation = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(sourceCompilation, Sub(runtime) VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL) End Sub) ' Now recompile and test CompileExpression with optimized code. WithRuntimeInstance(sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release)), Sub(runtime) ' In VB, "Me" is never optimized away. VerifyHasMe(CreateMethodContext(runtime, moveNextMethodName), expectedType, expectedIL:=Nothing) End Sub) End Sub Private Sub VerifyHasMe(context As EvaluationContext, expectedType As String, expectedIL As String) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) Assert.NotEqual(0, assembly.Count) Dim localAndMethod = locals.Single(Function(l) l.LocalName = "Me") Dim methods = testData.GetMethodsByName() If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL) End If locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Null(errorMessage) If expectedIL IsNot Nothing Then VerifyMethodData(methods.Single(Function(m) m.Key.Contains("<>m0")).Value, expectedType, expectedIL) End If End Sub Private Shared Sub VerifyMethodData(methodData As CompilationTestData.MethodData, expectedType As String, expectedIL As String) methodData.VerifyIL(expectedIL) Dim method As MethodSymbol = DirectCast(methodData.Method, MethodSymbol) VerifyTypeParameters(method) Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString()) End Sub Private Sub VerifyNoMe(source As String, moveNextMethodName As String) Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) VerifyNoMe(CreateMethodContext(runtime, moveNextMethodName)) End Sub) End Sub Private Shared Sub VerifyNoMe(context As EvaluationContext) Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim testData As New CompilationTestData() Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.NotNull(assembly) AssertEx.None(locals, Function(l) l.LocalName.Contains("Me")) locals.Free() Dim errorMessage As String = Nothing testData = New CompilationTestData() context.CompileExpression("Me", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'Me' is not valid within a Module.", "error BC30043: 'Me' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyBase.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC32001: 'MyBase' is not valid within a Module.", "error BC30043: 'MyBase' is valid only within an instance method." }) testData = New CompilationTestData() context.CompileExpression("MyClass.ToString()", errorMessage, testData) Assert.Contains(errorMessage, { "error BC30470: 'MyClass' cannot be used outside of a class.", "error BC32001: 'MyClass' is not valid within a Module.", "error BC30043: 'MyClass' is valid only within an instance method." }) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInIterator() Const source = " Class C Private x As Object Iterator Function F() As System.Collections.IEnumerable Yield Me.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInLambda() Const source = " Class C Private x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C.x As Object"" IL_0006: ret } ") End Sub) End Sub <WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")> <Fact> Public Sub InstanceMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class C Private x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("Me.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C"" IL_0006: ldfld ""C.x As Object"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInIterator() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Iterator Function F() As System.Collections.IEnumerable Yield MyBase.x End Function End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Boolean V_0, Integer V_1) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInAsync() Const source = " Imports System Imports System.Threading.Tasks Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Async Function F() As Task Await Console.Out.WriteLineAsync(Me.ToString()) End Function End Class " Dim comp = CreateEmptyCompilationWithReferences( {VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, MsvbRef_v4_0_30319_17929}, TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived.VB$StateMachine_2_F.MoveNext") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 12 (0xc) .maxstack 1 .locals init (Integer V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, Derived.VB$StateMachine_2_F V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""Derived.VB$StateMachine_2_F.$VB$Me As Derived"" IL_0006: ldfld ""Base.x As Integer"" IL_000b: ret } ") End Sub) End Sub <Fact> Public Sub BaseMembersInLambda() Const source = " Class Base Protected x As Integer End Class Class Derived : Inherits Base Shadows Protected x As Object Sub F() Dim a As System.Action = Sub() Me.x.ToString() a() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "Derived._Lambda$__2-0") Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression("MyBase.x", errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""Base.x As Integer"" IL_0006: ret } ") End Sub) End Sub <Fact> Public Sub IteratorOverloading_Parameters1() Const source = " Imports System.Collections Public Class C Public Iterator Function M() As IEnumerable Yield Me End Function Public Function M(x As Integer) As IEnumerable Return Nothing End Function End Class " CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub IteratorOverloading_Parameters2() ' Same as above, but declarations reversed. Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function Public Iterator Function M() As IEnumerable Yield Me End Function End Class " ' NB: We pick the wrong overload, but it doesn't matter because ' the methods have the same characteristics. ' Also, we don't require this behavior, we're just documenting it. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 1) End Sub <Fact> Public Sub IteratorOverloading_Sharedness() Const source = " Imports System.Collections Public Class C Public Shared Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsShared) End Sub <Fact> Public Sub IteratorOverloading_MustOverrideness() Const source = " Imports System.Collections Public MustInherit Class C Public MustOverride Function M(x As Integer) As IEnumerable ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) Not m.IsMustOverride) End Sub <Fact> Public Sub IteratorOverloading_Arity1() Const source = " Imports System.Collections Public Class C Public Function M(Of T)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 0) End Sub <Fact> Public Sub IteratorOverloading_Arity2() Const source = " Imports System.Collections Public Class C Public Function M(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.Arity = 1) End Sub <Fact> Public Sub IteratorOverloading_Constraints1() Const source = " Imports System.Collections Public Class C Public Function M(Of T As Structure)(x As Integer) As IEnumerable Return Nothing End Function ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As Class)() As IEnumerable Yield Me End Function End Class " CheckIteratorOverloading(source, Function(m) m.TypeParameters.Single().HasReferenceTypeConstraint) End Sub <Fact> Public Sub IteratorOverloading_Constraints2() Const source = " Imports System.Collections Imports System.Collections.Generic Public Class C ' NB: We declare the interesting overload last so we know we're not ' just picking the first one by mistake. Public Iterator Function M(Of T As IEnumerable(Of U), U As Class)() As IEnumerable Yield Me End Function End Class " ' NOTE: this isn't the feature we're switching on, but it is a convenient differentiator. CheckIteratorOverloading(source, Function(m) m.ParameterCount = 0) End Sub <Fact> Public Sub LambdaOverloading_NonGeneric() Const source = " Public Class C Public Sub M(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " ' Note: We're picking the first method with the correct generic arity, etc. CheckLambdaOverloading(source, Function(m) m.MethodKind = MethodKind.Constructor) End Sub <Fact> Public Sub LambdaOverloading_Generic() Const source = " Public Class C Public Sub M(Of T)(x As Integer) Dim a As System.Action = Sub() x.ToString() End Sub End Class " CheckLambdaOverloading(source, Function(m) m.Arity = 1) End Sub Private Shared Sub CheckIteratorOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, Function(m) m.Name = "M" AndAlso isDesiredOverload(m), Function(originalType) Dim stateMachineType = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)) Return stateMachineType.GetMember(Of MethodSymbol)("MoveNext") End Function) End Sub Private Shared Sub CheckLambdaOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean)) CheckOverloading( source, isDesiredOverload, Function(originalType) Dim displayClass As NamedTypeSymbol = originalType.GetMembers().OfType(Of NamedTypeSymbol).Single(Function(t) t.Name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal)) Return displayClass.GetMembers().OfType(Of MethodSymbol).Single(AddressOf IsLambda) End Function) End Sub Private Shared Function IsLambda(method As MethodSymbol) As Boolean Return method.Name.StartsWith(GeneratedNameConstants.LambdaMethodNamePrefix, StringComparison.Ordinal) End Function Private Shared Sub CheckOverloading(source As String, isDesiredOverload As Func(Of MethodSymbol, Boolean), getSynthesizedMethod As Func(Of NamedTypeSymbol, MethodSymbol)) Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim dummyComp = MakeDummyCompilation(comp) Dim originalType = dummyComp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim desiredMethod = originalType.GetMembers().OfType(Of MethodSymbol).Single(isDesiredOverload) Dim synthesizedMethod As MethodSymbol = getSynthesizedMethod(originalType) Dim guessedMethod = CompilationContext.GetSubstitutedSourceMethod(synthesizedMethod, sourceMethodMustBeInstance:=True) Assert.Equal(desiredMethod, guessedMethod.OriginalDefinition) End Sub Private Shared Function MakeDummyCompilation(comp As VisualBasicCompilation) As VisualBasicCompilation Dim compOptions = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All) Return CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(<Compilation/>, {comp.EmitToImageReference()}, compOptions) End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; 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.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private void GetMainDocumentAndPreviews(TestParameters parameters, TestWorkspace workspace, out Document document, out SolutionPreviewResult previews) { document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); GetMainDocumentAndPreviews(parameters, workspace, out var document, out var previews); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.Ordinal); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; 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.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private void GetMainDocumentAndPreviews(TestParameters parameters, TestWorkspace workspace, out Document document, out SolutionPreviewResult previews) { document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); GetMainDocumentAndPreviews(parameters, workspace, out var document, out var previews); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.Ordinal); } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedMyGroupCollectionPropertyAccessorSymbol.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.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a compiler "MyGroupCollection" property accessor. ''' </summary> Friend MustInherit Class SynthesizedMyGroupCollectionPropertyAccessorSymbol Inherits SynthesizedPropertyAccessorBase(Of SynthesizedMyGroupCollectionPropertySymbol) Private ReadOnly _createOrDisposeMethod As String Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, createOrDisposeMethod As String) MyBase.New(container, [property]) Debug.Assert(createOrDisposeMethod IsNot Nothing AndAlso createOrDisposeMethod.Length > 0) _createOrDisposeMethod = createOrDisposeMethod End Sub Friend Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Return PropertyOrEvent.AssociatedField End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Note, Dev11 emits DebuggerNonUserCodeAttribute, but we are using DebuggerHiddenAttribute instead. AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeDebuggerHiddenAttribute()) End Sub Private Shared Function MakeSafeName(name As String) As String If SyntaxFacts.GetKeywordKind(name) <> SyntaxKind.None Then Return "[" & name & "]" End If Return name End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out()> Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Dim containingType = DirectCast(Me.ContainingType, SourceNamedTypeSymbol) Dim containingTypeName As String = MakeSafeName(containingType.Name) Dim targetTypeName As String = PropertyOrEvent.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) Debug.Assert(targetTypeName.StartsWith("Global.", StringComparison.Ordinal)) Dim propertyName As String = MakeSafeName(PropertyOrEvent.Name) Dim fieldName As String = PropertyOrEvent.AssociatedField.Name Dim codeToParse As String = "Partial Class " & containingTypeName & vbCrLf & "Property " & propertyName & vbCrLf & GetMethodBlock(fieldName, MakeSafeName(_createOrDisposeMethod), targetTypeName) & "End Property" & vbCrLf & "End Class" & vbCrLf ' TODO: It looks like Dev11 respects project level conditional compilation here. Dim tree = VisualBasicSyntaxTree.ParseText(codeToParse) Dim attributeSyntax = PropertyOrEvent.AttributeSyntax.GetVisualBasicSyntax() Dim diagnosticLocation As Location = attributeSyntax.GetLocation() Dim root As CompilationUnitSyntax = tree.GetCompilationUnitRoot() Dim hasErrors As Boolean = False For Each diag As Diagnostic In tree.GetDiagnostics(root) Dim vbdiag = DirectCast(diag, VBDiagnostic) Debug.Assert(Not vbdiag.HasLazyInfo, "If we decide to allow lazy syntax diagnostics, we'll have to check all call sites of SyntaxTree.GetDiagnostics") diagnostics.Add(vbdiag.WithLocation(diagnosticLocation)) If diag.Severity = DiagnosticSeverity.Error Then hasErrors = True End If Next Dim classBlock = DirectCast(root.Members(0), ClassBlockSyntax) Dim propertyBlock = DirectCast(classBlock.Members(0), PropertyBlockSyntax) Dim accessorBlock As AccessorBlockSyntax = propertyBlock.Accessors(0) Dim boundStatement As BoundStatement If hasErrors Then boundStatement = New BoundBadStatement(accessorBlock, ImmutableArray(Of BoundNode).Empty) Else Dim typeBinder As Binder = BinderBuilder.CreateBinderForType(containingType.ContainingSourceModule, PropertyOrEvent.AttributeSyntax.SyntaxTree, containingType) methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(Me, accessorBlock, typeBinder) Dim bindingDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag) #If DEBUG Then ' Enable DEBUG check for ordering of simple name binding. methodBodyBinder.EnableSimpleNameBindingOrderChecks(True) #End If boundStatement = methodBodyBinder.BindStatement(accessorBlock, bindingDiagnostics) #If DEBUG Then methodBodyBinder.EnableSimpleNameBindingOrderChecks(False) #End If For Each diag As VBDiagnostic In bindingDiagnostics.DiagnosticBag.AsEnumerable() diagnostics.Add(diag.WithLocation(diagnosticLocation)) Next bindingDiagnostics.DiagnosticBag.Free() If boundStatement.Kind = BoundKind.Block Then Return DirectCast(boundStatement, BoundBlock) End If End If Return New BoundBlock(accessorBlock, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(boundStatement)) End Function Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Protected MustOverride Function GetMethodBlock(fieldName As String, createOrDisposeMethodName As String, targetTypeName As String) As String End Class Friend Class SynthesizedMyGroupCollectionPropertyGetAccessorSymbol Inherits SynthesizedMyGroupCollectionPropertyAccessorSymbol Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, createMethod As String) MyBase.New(container, [property], createMethod) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return PropertyOrEvent.Type End Get End Property Protected Overrides Function GetMethodBlock(fieldName As String, createMethodName As String, targetTypeName As String) As String ' See Bindable::GenMyGroupCollectionGetCode. ' Get ' <backingField> = <CreateMethod>(Of <TargetType>)(<backingField>) ' return <backingField> ' End Get Return "Get" & vbCrLf & fieldName & " = " & createMethodName & "(Of " & targetTypeName & ")(" & fieldName & ")" & vbCrLf & "Return " & fieldName & vbCrLf & "End Get" & vbCrLf End Function End Class Friend Class SynthesizedMyGroupCollectionPropertySetAccessorSymbol Inherits SynthesizedMyGroupCollectionPropertyAccessorSymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, disposeMethod As String) MyBase.New(container, [property], disposeMethod) Dim params() As ParameterSymbol = {SynthesizedParameterSymbol.CreateSetAccessorValueParameter(Me, [property], StringConstants.ValueParameterName)} _parameters = params.AsImmutableOrNull() End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get ' There is no reason to specially complain about missing/bad System.Void because we require presence of constructor, ' which also returns void. The error reported on the constructor is sufficient. Return ContainingAssembly.GetSpecialType(SpecialType.System_Void) End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Protected Overrides Function GetMethodBlock(fieldName As String, disposeMethodName As String, targetTypeName As String) As String ' See Bindable::GenMyGroupCollectionSetCode. ' Set(ByVal <Value> As <TargetType>) ' If <Value> Is <backingField> ' return ' End If ' If Not <Value> Is Nothing Then ' Throw New ArgumentException("Property can only be set to Nothing.") ' End If ' <DisposeMethod>(Of <TargetType>)(<backingField>) ' End Set Return "Set(ByVal " & StringConstants.ValueParameterName & " As " & targetTypeName & ")" & vbCrLf & "If " & StringConstants.ValueParameterName & " Is " & fieldName & vbCrLf & "Return" & vbCrLf & "End If" & vbCrLf & "If " & StringConstants.ValueParameterName & " IsNot Nothing Then" & vbCrLf & "Throw New Global.System.ArgumentException(""Property can only be set to Nothing"")" & vbCrLf & "End If" & vbCrLf & disposeMethodName & "(Of " & targetTypeName & ")(" & fieldName & ")" & vbCrLf & "End Set" & vbCrLf 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.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a compiler "MyGroupCollection" property accessor. ''' </summary> Friend MustInherit Class SynthesizedMyGroupCollectionPropertyAccessorSymbol Inherits SynthesizedPropertyAccessorBase(Of SynthesizedMyGroupCollectionPropertySymbol) Private ReadOnly _createOrDisposeMethod As String Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, createOrDisposeMethod As String) MyBase.New(container, [property]) Debug.Assert(createOrDisposeMethod IsNot Nothing AndAlso createOrDisposeMethod.Length > 0) _createOrDisposeMethod = createOrDisposeMethod End Sub Friend Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Return PropertyOrEvent.AssociatedField End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Note, Dev11 emits DebuggerNonUserCodeAttribute, but we are using DebuggerHiddenAttribute instead. AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeDebuggerHiddenAttribute()) End Sub Private Shared Function MakeSafeName(name As String) As String If SyntaxFacts.GetKeywordKind(name) <> SyntaxKind.None Then Return "[" & name & "]" End If Return name End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out()> Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Dim containingType = DirectCast(Me.ContainingType, SourceNamedTypeSymbol) Dim containingTypeName As String = MakeSafeName(containingType.Name) Dim targetTypeName As String = PropertyOrEvent.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) Debug.Assert(targetTypeName.StartsWith("Global.", StringComparison.Ordinal)) Dim propertyName As String = MakeSafeName(PropertyOrEvent.Name) Dim fieldName As String = PropertyOrEvent.AssociatedField.Name Dim codeToParse As String = "Partial Class " & containingTypeName & vbCrLf & "Property " & propertyName & vbCrLf & GetMethodBlock(fieldName, MakeSafeName(_createOrDisposeMethod), targetTypeName) & "End Property" & vbCrLf & "End Class" & vbCrLf ' TODO: It looks like Dev11 respects project level conditional compilation here. Dim tree = VisualBasicSyntaxTree.ParseText(codeToParse) Dim attributeSyntax = PropertyOrEvent.AttributeSyntax.GetVisualBasicSyntax() Dim diagnosticLocation As Location = attributeSyntax.GetLocation() Dim root As CompilationUnitSyntax = tree.GetCompilationUnitRoot() Dim hasErrors As Boolean = False For Each diag As Diagnostic In tree.GetDiagnostics(root) Dim vbdiag = DirectCast(diag, VBDiagnostic) Debug.Assert(Not vbdiag.HasLazyInfo, "If we decide to allow lazy syntax diagnostics, we'll have to check all call sites of SyntaxTree.GetDiagnostics") diagnostics.Add(vbdiag.WithLocation(diagnosticLocation)) If diag.Severity = DiagnosticSeverity.Error Then hasErrors = True End If Next Dim classBlock = DirectCast(root.Members(0), ClassBlockSyntax) Dim propertyBlock = DirectCast(classBlock.Members(0), PropertyBlockSyntax) Dim accessorBlock As AccessorBlockSyntax = propertyBlock.Accessors(0) Dim boundStatement As BoundStatement If hasErrors Then boundStatement = New BoundBadStatement(accessorBlock, ImmutableArray(Of BoundNode).Empty) Else Dim typeBinder As Binder = BinderBuilder.CreateBinderForType(containingType.ContainingSourceModule, PropertyOrEvent.AttributeSyntax.SyntaxTree, containingType) methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(Me, accessorBlock, typeBinder) Dim bindingDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag) #If DEBUG Then ' Enable DEBUG check for ordering of simple name binding. methodBodyBinder.EnableSimpleNameBindingOrderChecks(True) #End If boundStatement = methodBodyBinder.BindStatement(accessorBlock, bindingDiagnostics) #If DEBUG Then methodBodyBinder.EnableSimpleNameBindingOrderChecks(False) #End If For Each diag As VBDiagnostic In bindingDiagnostics.DiagnosticBag.AsEnumerable() diagnostics.Add(diag.WithLocation(diagnosticLocation)) Next bindingDiagnostics.DiagnosticBag.Free() If boundStatement.Kind = BoundKind.Block Then Return DirectCast(boundStatement, BoundBlock) End If End If Return New BoundBlock(accessorBlock, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(boundStatement)) End Function Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Protected MustOverride Function GetMethodBlock(fieldName As String, createOrDisposeMethodName As String, targetTypeName As String) As String End Class Friend Class SynthesizedMyGroupCollectionPropertyGetAccessorSymbol Inherits SynthesizedMyGroupCollectionPropertyAccessorSymbol Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, createMethod As String) MyBase.New(container, [property], createMethod) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return PropertyOrEvent.Type End Get End Property Protected Overrides Function GetMethodBlock(fieldName As String, createMethodName As String, targetTypeName As String) As String ' See Bindable::GenMyGroupCollectionGetCode. ' Get ' <backingField> = <CreateMethod>(Of <TargetType>)(<backingField>) ' return <backingField> ' End Get Return "Get" & vbCrLf & fieldName & " = " & createMethodName & "(Of " & targetTypeName & ")(" & fieldName & ")" & vbCrLf & "Return " & fieldName & vbCrLf & "End Get" & vbCrLf End Function End Class Friend Class SynthesizedMyGroupCollectionPropertySetAccessorSymbol Inherits SynthesizedMyGroupCollectionPropertyAccessorSymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New(container As SourceNamedTypeSymbol, [property] As SynthesizedMyGroupCollectionPropertySymbol, disposeMethod As String) MyBase.New(container, [property], disposeMethod) Dim params() As ParameterSymbol = {SynthesizedParameterSymbol.CreateSetAccessorValueParameter(Me, [property], StringConstants.ValueParameterName)} _parameters = params.AsImmutableOrNull() End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get ' There is no reason to specially complain about missing/bad System.Void because we require presence of constructor, ' which also returns void. The error reported on the constructor is sufficient. Return ContainingAssembly.GetSpecialType(SpecialType.System_Void) End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Protected Overrides Function GetMethodBlock(fieldName As String, disposeMethodName As String, targetTypeName As String) As String ' See Bindable::GenMyGroupCollectionSetCode. ' Set(ByVal <Value> As <TargetType>) ' If <Value> Is <backingField> ' return ' End If ' If Not <Value> Is Nothing Then ' Throw New ArgumentException("Property can only be set to Nothing.") ' End If ' <DisposeMethod>(Of <TargetType>)(<backingField>) ' End Set Return "Set(ByVal " & StringConstants.ValueParameterName & " As " & targetTypeName & ")" & vbCrLf & "If " & StringConstants.ValueParameterName & " Is " & fieldName & vbCrLf & "Return" & vbCrLf & "End If" & vbCrLf & "If " & StringConstants.ValueParameterName & " IsNot Nothing Then" & vbCrLf & "Throw New Global.System.ArgumentException(""Property can only be set to Nothing"")" & vbCrLf & "End If" & vbCrLf & disposeMethodName & "(Of " & targetTypeName & ")(" & fieldName & ")" & vbCrLf & "End Set" & vbCrLf End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_LateAddressOf.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateAddressOfOperator(node) End If Dim targetType = DirectCast(node.Type, NamedTypeSymbol) Dim lambda = BuildDelegateRelaxationLambda(node.Syntax, targetType, node.MemberAccess, node.Binder, Me._diagnostics) Return Me.VisitExpressionNode(lambda) End Function Private Shared Function BuildDelegateRelaxationLambda( syntaxNode As SyntaxNode, targetType As NamedTypeSymbol, boundMember As BoundLateMemberAccess, binder As Binder, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim delegateInvoke = targetType.DelegateInvokeMethod Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke) ' build lambda symbol parameters matching the invocation method exactly. To do this, ' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method. Dim delegateInvokeReturnType = delegateInvoke.ReturnType Dim invokeParameters = delegateInvoke.Parameters Dim invokeParameterCount = invokeParameters.Length Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol Dim addressOfLocation As Location = syntaxNode.GetLocation() For parameterIndex = 0 To invokeParameterCount - 1 Dim parameter = invokeParameters(parameterIndex) lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex), parameter.Ordinal, parameter.Type, parameter.IsByRef, syntaxNode, addressOfLocation) Next ' even if the return value is dropped, we're using the delegate's return type for ' this lambda symbol. Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.LateBoundAddressOfLambda, syntaxNode, lambdaSymbolParameters.AsImmutableOrNull, delegateInvokeReturnType, binder) ' the body of the lambda only contains a call to the target (or a return of the return value of ' the call in case of a function) ' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except ' we are implementing a zero argument relaxation. ' These parameters will be used in the method invocation as passed parameters. Dim lambdaBoundParameters(invokeParameterCount - 1) As BoundExpression For parameterIndex = 0 To lambdaSymbolParameters.Length - 1 Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex) Dim boundParameter = New BoundParameter(syntaxNode, lambdaSymbolParameter, lambdaSymbolParameter.Type) boundParameter.SetWasCompilerGenerated() lambdaBoundParameters(parameterIndex) = boundParameter Next 'The invocation of the target method must be bound in the context of the lambda 'The reason is that binding the invoke may introduce local symbols and they need 'to be properly parented to the lambda and not to the outer method. Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, binder) ' Dev10 ignores the type characters used in the operand of an AddressOf operator. ' NOTE: we suppress suppressAbstractCallDiagnostics because it ' should have been reported already Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindLateBoundInvocation(syntaxNode, Nothing, boundMember, lambdaBoundParameters.AsImmutableOrNull, Nothing, diagnostics, suppressLateBindingResolutionDiagnostics:=True) boundInvocationExpression.SetWasCompilerGenerated() ' In case of a function target that got assigned to a sub delegate, the return value will be dropped Dim statementList As ImmutableArray(Of BoundStatement) = Nothing If lambdaSymbol.IsSub Then If boundInvocationExpression.IsLateBound() Then boundInvocationExpression = boundInvocationExpression.SetLateBoundAccessKind(LateBoundAccessKind.Call) End If Dim statements(1) As BoundStatement Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression) boundStatement.SetWasCompilerGenerated() statements(0) = boundStatement boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing) boundStatement.SetWasCompilerGenerated() statements(1) = boundStatement statementList = statements.AsImmutableOrNull Else ' process conversions between the return types of the target and invoke function if needed. boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode, delegateInvokeReturnType, boundInvocationExpression, diagnostics) Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode, boundInvocationExpression, Nothing, Nothing) returnstmt.SetWasCompilerGenerated() statementList = ImmutableArray.Create(returnstmt) End If Dim lambdaBody = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, statementList) lambdaBody.SetWasCompilerGenerated() Dim boundLambda = New BoundLambda(syntaxNode, lambdaSymbol, lambdaBody, ImmutableBindingDiagnostic(Of AssemblySymbol).Empty, Nothing, ConversionKind.DelegateRelaxationLevelWidening, MethodConversionKind.Identity) boundLambda.SetWasCompilerGenerated() Dim result = New BoundDirectCast(syntaxNode, boundLambda, ConversionKind.DelegateRelaxationLevelWidening, targetType) 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateAddressOfOperator(node) End If Dim targetType = DirectCast(node.Type, NamedTypeSymbol) Dim lambda = BuildDelegateRelaxationLambda(node.Syntax, targetType, node.MemberAccess, node.Binder, Me._diagnostics) Return Me.VisitExpressionNode(lambda) End Function Private Shared Function BuildDelegateRelaxationLambda( syntaxNode As SyntaxNode, targetType As NamedTypeSymbol, boundMember As BoundLateMemberAccess, binder As Binder, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim delegateInvoke = targetType.DelegateInvokeMethod Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke) ' build lambda symbol parameters matching the invocation method exactly. To do this, ' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method. Dim delegateInvokeReturnType = delegateInvoke.ReturnType Dim invokeParameters = delegateInvoke.Parameters Dim invokeParameterCount = invokeParameters.Length Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol Dim addressOfLocation As Location = syntaxNode.GetLocation() For parameterIndex = 0 To invokeParameterCount - 1 Dim parameter = invokeParameters(parameterIndex) lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex), parameter.Ordinal, parameter.Type, parameter.IsByRef, syntaxNode, addressOfLocation) Next ' even if the return value is dropped, we're using the delegate's return type for ' this lambda symbol. Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.LateBoundAddressOfLambda, syntaxNode, lambdaSymbolParameters.AsImmutableOrNull, delegateInvokeReturnType, binder) ' the body of the lambda only contains a call to the target (or a return of the return value of ' the call in case of a function) ' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except ' we are implementing a zero argument relaxation. ' These parameters will be used in the method invocation as passed parameters. Dim lambdaBoundParameters(invokeParameterCount - 1) As BoundExpression For parameterIndex = 0 To lambdaSymbolParameters.Length - 1 Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex) Dim boundParameter = New BoundParameter(syntaxNode, lambdaSymbolParameter, lambdaSymbolParameter.Type) boundParameter.SetWasCompilerGenerated() lambdaBoundParameters(parameterIndex) = boundParameter Next 'The invocation of the target method must be bound in the context of the lambda 'The reason is that binding the invoke may introduce local symbols and they need 'to be properly parented to the lambda and not to the outer method. Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, binder) ' Dev10 ignores the type characters used in the operand of an AddressOf operator. ' NOTE: we suppress suppressAbstractCallDiagnostics because it ' should have been reported already Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindLateBoundInvocation(syntaxNode, Nothing, boundMember, lambdaBoundParameters.AsImmutableOrNull, Nothing, diagnostics, suppressLateBindingResolutionDiagnostics:=True) boundInvocationExpression.SetWasCompilerGenerated() ' In case of a function target that got assigned to a sub delegate, the return value will be dropped Dim statementList As ImmutableArray(Of BoundStatement) = Nothing If lambdaSymbol.IsSub Then If boundInvocationExpression.IsLateBound() Then boundInvocationExpression = boundInvocationExpression.SetLateBoundAccessKind(LateBoundAccessKind.Call) End If Dim statements(1) As BoundStatement Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression) boundStatement.SetWasCompilerGenerated() statements(0) = boundStatement boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing) boundStatement.SetWasCompilerGenerated() statements(1) = boundStatement statementList = statements.AsImmutableOrNull Else ' process conversions between the return types of the target and invoke function if needed. boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode, delegateInvokeReturnType, boundInvocationExpression, diagnostics) Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode, boundInvocationExpression, Nothing, Nothing) returnstmt.SetWasCompilerGenerated() statementList = ImmutableArray.Create(returnstmt) End If Dim lambdaBody = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, statementList) lambdaBody.SetWasCompilerGenerated() Dim boundLambda = New BoundLambda(syntaxNode, lambdaSymbol, lambdaBody, ImmutableBindingDiagnostic(Of AssemblySymbol).Empty, Nothing, ConversionKind.DelegateRelaxationLevelWidening, MethodConversionKind.Identity) boundLambda.SetWasCompilerGenerated() Dim result = New BoundDirectCast(syntaxNode, boundLambda, ConversionKind.DelegateRelaxationLevelWidening, targetType) Return result End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Tools/Source/CompilerGeneratorTools/.editorconfig
# Project-specific settings: [*.{cs,vb}] # Local functions are camelCase dotnet_naming_style.local_function_style.capitalization = camel_case # CSharp code style settings: [*.cs] csharp_style_var_for_built_in_types = false:none csharp_style_var_when_type_is_apparent = true:none csharp_style_var_elsewhere = false:none
# Project-specific settings: [*.{cs,vb}] # Local functions are camelCase dotnet_naming_style.local_function_style.capitalization = camel_case # CSharp code style settings: [*.cs] csharp_style_var_for_built_in_types = false:none csharp_style_var_when_type_is_apparent = true:none csharp_style_var_elsewhere = false:none
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenFieldInitTests.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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenFieldInitTests Inherits BasicTestBase <Fact> Public Sub TestInstanceFieldInitializersPartialClass() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim p As [Partial] System.Console.WriteLine("Start Partial()") p = New [Partial]() System.Console.WriteLine("p.a = {0}", p.a) System.Console.WriteLine("p.b = {0}", p.b) System.Console.WriteLine("p.c = {0}", p.c) System.Console.WriteLine("End Partial()") System.Console.WriteLine("Start Partial(int)") p = New [Partial](2) System.Console.WriteLine("p.a = {0}", p.a) System.Console.WriteLine("p.b = {0}", p.b) System.Console.WriteLine("p.c = {0}", p.c) System.Console.WriteLine("End Partial(int)") End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Partial Class [Partial] Public a As Integer = D.Init(1, "Partial.a") Public Sub New() End Sub End Class Partial Class [Partial] Public c As Integer, b As Integer = D.Init(2, "Partial.b") Public Sub New(garbage As Integer) Me.c = D.Init(3, "Partial.c") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Start Partial() Partial.a Partial.b p.a = 1 p.b = 2 p.c = 0 End Partial() Start Partial(int) Partial.a Partial.b Partial.c p.a = 1 p.b = 2 p.c = 3 End Partial(int) ]]>) End Sub <Fact> Public Sub TestInstanceFieldInitializersInheritance() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim d As New Derived2() System.Console.WriteLine("d.a = {0}", d.a) System.Console.WriteLine("d.b = {0}", d.b) System.Console.WriteLine("d.c = {0}", d.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public a As Integer = D.Init(1, "Base.a") Public Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public b As Integer = D.Init(2, "Derived.b") Public Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public c As Integer = D.Init(3, "Derived2.c") Public Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Base.a Base() Derived.b Derived() Derived2.c Derived2() d.a = 1 d.b = 2 d.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersPartialClass() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() System.Console.WriteLine("Partial.a = {0}", [Partial].a) System.Console.WriteLine("Partial.b = {0}", [Partial].b) System.Console.WriteLine("Partial.c = {0}", [Partial].c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Partial Class [Partial] Public Shared a As Integer = D.Init(1, "Partial.a") End Class Partial Class [Partial] Public Shared c As Integer, b As Integer = D.Init(2, "Partial.b") Shared Sub New() c = D.Init(3, "Partial.c") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Partial.a Partial.b Partial.c Partial.a = 1 Partial.b = 2 Partial.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance1() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As New Base() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Base.a Base() Base.a = 1 Derived.b Derived() Derived.b = 2 Derived2.c Derived2() Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance2() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As Base = New Derived() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived.b Derived() Base.a Base() Base.a = 1 Derived.b = 2 Derived2.c Derived2() Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance3() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As Base = New Derived2() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived2.c Derived2() Derived.b Derived() Base.a Base() Base.a = 1 Derived.b = 2 Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestFieldInitializersMixed() CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim d As New Derived() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("d.x = {0}", d.x) System.Console.WriteLine("d.y = {0}", d.y) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = C.Init(1, "Base.a") Public x As Integer = C.Init(3, "Base.x") Shared Sub New() System.Console.WriteLine("static Base()") End Sub Public Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = C.Init(2, "Derived.b") Public y As Integer = C.Init(4, "Derived.y") Shared Sub New() System.Console.WriteLine("static Derived()") End Sub Public Sub New() System.Console.WriteLine("Derived()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived.b static Derived() Base.a static Base() Base.x Base() Derived.y Derived() Base.a = 1 Derived.b = 2 d.x = 3 d.y = 4 ]]>) End Sub <Fact> Public Sub TestFieldInitializersConstructorInitializers() CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim a As New A() System.Console.WriteLine("a.a = {0}", a.a) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class A Public a As Integer = C.Init(1, "A.a") Public Sub New() Me.New(1) System.Console.WriteLine("A()") End Sub Public Sub New(garbage As Integer) System.Console.WriteLine("A(int)") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A.a A(int) A() a.a = 1 ]]>) End Sub <Fact> Public Sub TestFieldInitializersConstructorInitializers2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class A Protected x As Integer = 1 End Class Class B Inherits A Private y As Integer = x Public Sub New() Console.WriteLine("x = " &amp; x &amp; ", y = " &amp; y) End Sub Public Shared Sub Main() Dim a As New B() End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[x = 1, y = 1]]>) End Sub <WorkItem(540460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540460")> <Fact> Public Sub TestStaticInitializerErrors() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Class C Public Shared F = G() Shared Sub G() End Sub End Class </file> </compilation>, references:=DefaultVbReferences, options:=TestOptions.ReleaseDll) Using executableStream As New MemoryStream() Dim result = compilation.Emit(executableStream) CompilationUtils.AssertTheseDiagnostics(result.Diagnostics, <expected> BC30491: Expression does not produce a value. Public Shared F = G() ~~~ </expected>) End Using End Sub <WorkItem(540460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540460")> <Fact> Public Sub TestInstanceInitializerErrors() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Class C Public F = G() Shared Sub G() End Sub End Class </file> </compilation>, references:=DefaultVbReferences, options:=TestOptions.ReleaseDll) Using executableStream As New MemoryStream() Dim result = compilation.Emit(executableStream) CompilationUtils.AssertTheseDiagnostics(result.Diagnostics, <expected> BC30491: Expression does not produce a value. Public F = G() ~~~ </expected>) End Using End Sub <WorkItem(540467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540467")> <Fact> Public Sub TestCallNoParentheses() Dim source = <compilation> <file name="c.vb"> Class C Shared Function M() Return 1 End Function Public Shared F = M Public Shared G = M() Shared Sub Main() F = M End Sub End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:=<![CDATA[ ]]>) End Sub <WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")> <Fact> Public Sub TestLambdasInFieldInitializers() Dim source = <compilation> <file name="c.vb"> Imports System Class Class1(Of T) Dim f As Func(Of T, Integer, Integer) = Function(x, p) Dim a_outer As Integer = p * p Dim ff As Func(Of T, Integer, Integer) = Function(xx, pp) If (xx IsNot Nothing) Then Console.WriteLine(xx.GetType()) End If Console.WriteLine(p * pp) Return p End Function Return ff(x, p) End Function Public Function Goo() As Integer Return Nothing End Function Public Sub New() f(Nothing, 5) End Sub Public Sub New(p As T) f(p, 123) End Sub End Class Module Program Sub Main() Dim a As New Class1(Of DateTime) Dim b As New Class1(Of String)("abc") End Sub End Module </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:= <![CDATA[ System.DateTime 25 System.String 15129]]>) End Sub <WorkItem(540603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540603")> <Fact> Public Sub TestAsNewInitializers() Dim source = <compilation> <file name="c.vb"> Class Class1 Dim f1 As New Object() Dim f2 As Object = New Object() End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source). VerifyIL("Class1..ctor", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: newobj "Sub Object..ctor()" IL_000c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0011: stfld "Class1.f1 As Object" IL_0016: ldarg.0 IL_0017: newobj "Sub Object..ctor()" IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: stfld "Class1.f2 As Object" IL_0026: ret } ]]>) End Sub <Fact> Public Sub FieldInitializerWithBadConstantValueSameModule() Dim source = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class A Public F As Integer = B.F1 End Class Class B Public Const F1 As Integer = F2 Public Shared F2 As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source) CompilationUtils.AssertTheseDiagnostics(compilation.Emit(New MemoryStream()).Diagnostics, <expected> BC30059: Constant expression is required. Public Const F1 As Integer = F2 ~~ </expected>) End Sub <Fact> Public Sub FieldInitializerWithBadConstantValueDifferentModule() Dim source1 = <compilation name="1110a705-cc34-430b-9450-ca37031aa829"> <file name="c.vb"><![CDATA[ Option Strict On Public Class B Public Const F1 As Integer = F2 Public Shared F2 As Integer End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib40(source1) compilation1.AssertTheseDiagnostics(<expected> BC30059: Constant expression is required. Public Const F1 As Integer = F2 ~~ </expected>) Dim source2 = <compilation name="2110a705-cc34-430b-9450-ca37031aa829"> <file name="c.vb"><![CDATA[ Option Strict On Class A Public F As Object = M(B.F1) Private Shared Function M(i As Integer) As Object Return Nothing End Function End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(source2, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertTheseDiagnostics(compilation2.Emit(New MemoryStream()).Diagnostics, <expected> BC36970: Failed to emit module '2110a705-cc34-430b-9450-ca37031aa829.dll': Unable to determine specific cause of the failure. </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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenFieldInitTests Inherits BasicTestBase <Fact> Public Sub TestInstanceFieldInitializersPartialClass() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim p As [Partial] System.Console.WriteLine("Start Partial()") p = New [Partial]() System.Console.WriteLine("p.a = {0}", p.a) System.Console.WriteLine("p.b = {0}", p.b) System.Console.WriteLine("p.c = {0}", p.c) System.Console.WriteLine("End Partial()") System.Console.WriteLine("Start Partial(int)") p = New [Partial](2) System.Console.WriteLine("p.a = {0}", p.a) System.Console.WriteLine("p.b = {0}", p.b) System.Console.WriteLine("p.c = {0}", p.c) System.Console.WriteLine("End Partial(int)") End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Partial Class [Partial] Public a As Integer = D.Init(1, "Partial.a") Public Sub New() End Sub End Class Partial Class [Partial] Public c As Integer, b As Integer = D.Init(2, "Partial.b") Public Sub New(garbage As Integer) Me.c = D.Init(3, "Partial.c") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Start Partial() Partial.a Partial.b p.a = 1 p.b = 2 p.c = 0 End Partial() Start Partial(int) Partial.a Partial.b Partial.c p.a = 1 p.b = 2 p.c = 3 End Partial(int) ]]>) End Sub <Fact> Public Sub TestInstanceFieldInitializersInheritance() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim d As New Derived2() System.Console.WriteLine("d.a = {0}", d.a) System.Console.WriteLine("d.b = {0}", d.b) System.Console.WriteLine("d.c = {0}", d.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public a As Integer = D.Init(1, "Base.a") Public Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public b As Integer = D.Init(2, "Derived.b") Public Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public c As Integer = D.Init(3, "Derived2.c") Public Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Base.a Base() Derived.b Derived() Derived2.c Derived2() d.a = 1 d.b = 2 d.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersPartialClass() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() System.Console.WriteLine("Partial.a = {0}", [Partial].a) System.Console.WriteLine("Partial.b = {0}", [Partial].b) System.Console.WriteLine("Partial.c = {0}", [Partial].c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Partial Class [Partial] Public Shared a As Integer = D.Init(1, "Partial.a") End Class Partial Class [Partial] Public Shared c As Integer, b As Integer = D.Init(2, "Partial.b") Shared Sub New() c = D.Init(3, "Partial.c") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Partial.a Partial.b Partial.c Partial.a = 1 Partial.b = 2 Partial.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance1() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As New Base() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Base.a Base() Base.a = 1 Derived.b Derived() Derived.b = 2 Derived2.c Derived2() Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance2() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As Base = New Derived() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived.b Derived() Base.a Base() Base.a = 1 Derived.b = 2 Derived2.c Derived2() Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestStaticFieldInitializersInheritance3() CompileAndVerify( <compilation> <file name="a.vb"> Class D Public Shared Sub Main() Dim b As Base = New Derived2() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("Derived2.c = {0}", Derived2.c) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = D.Init(1, "Base.a") Shared Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = D.Init(2, "Derived.b") Shared Sub New() System.Console.WriteLine("Derived()") End Sub End Class Class Derived2 Inherits Derived Public Shared c As Integer = D.Init(3, "Derived2.c") Shared Sub New() System.Console.WriteLine("Derived2()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived2.c Derived2() Derived.b Derived() Base.a Base() Base.a = 1 Derived.b = 2 Derived2.c = 3 ]]>) End Sub <Fact> Public Sub TestFieldInitializersMixed() CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim d As New Derived() System.Console.WriteLine("Base.a = {0}", Base.a) System.Console.WriteLine("Derived.b = {0}", Derived.b) System.Console.WriteLine("d.x = {0}", d.x) System.Console.WriteLine("d.y = {0}", d.y) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class Base Public Shared a As Integer = C.Init(1, "Base.a") Public x As Integer = C.Init(3, "Base.x") Shared Sub New() System.Console.WriteLine("static Base()") End Sub Public Sub New() System.Console.WriteLine("Base()") End Sub End Class Class Derived Inherits Base Public Shared b As Integer = C.Init(2, "Derived.b") Public y As Integer = C.Init(4, "Derived.y") Shared Sub New() System.Console.WriteLine("static Derived()") End Sub Public Sub New() System.Console.WriteLine("Derived()") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ Derived.b static Derived() Base.a static Base() Base.x Base() Derived.y Derived() Base.a = 1 Derived.b = 2 d.x = 3 d.y = 4 ]]>) End Sub <Fact> Public Sub TestFieldInitializersConstructorInitializers() CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim a As New A() System.Console.WriteLine("a.a = {0}", a.a) End Sub Public Shared Function Init(value As Integer, message As String) As Integer System.Console.WriteLine(message) Return value End Function End Class Class A Public a As Integer = C.Init(1, "A.a") Public Sub New() Me.New(1) System.Console.WriteLine("A()") End Sub Public Sub New(garbage As Integer) System.Console.WriteLine("A(int)") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A.a A(int) A() a.a = 1 ]]>) End Sub <Fact> Public Sub TestFieldInitializersConstructorInitializers2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class A Protected x As Integer = 1 End Class Class B Inherits A Private y As Integer = x Public Sub New() Console.WriteLine("x = " &amp; x &amp; ", y = " &amp; y) End Sub Public Shared Sub Main() Dim a As New B() End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[x = 1, y = 1]]>) End Sub <WorkItem(540460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540460")> <Fact> Public Sub TestStaticInitializerErrors() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Class C Public Shared F = G() Shared Sub G() End Sub End Class </file> </compilation>, references:=DefaultVbReferences, options:=TestOptions.ReleaseDll) Using executableStream As New MemoryStream() Dim result = compilation.Emit(executableStream) CompilationUtils.AssertTheseDiagnostics(result.Diagnostics, <expected> BC30491: Expression does not produce a value. Public Shared F = G() ~~~ </expected>) End Using End Sub <WorkItem(540460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540460")> <Fact> Public Sub TestInstanceInitializerErrors() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Class C Public F = G() Shared Sub G() End Sub End Class </file> </compilation>, references:=DefaultVbReferences, options:=TestOptions.ReleaseDll) Using executableStream As New MemoryStream() Dim result = compilation.Emit(executableStream) CompilationUtils.AssertTheseDiagnostics(result.Diagnostics, <expected> BC30491: Expression does not produce a value. Public F = G() ~~~ </expected>) End Using End Sub <WorkItem(540467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540467")> <Fact> Public Sub TestCallNoParentheses() Dim source = <compilation> <file name="c.vb"> Class C Shared Function M() Return 1 End Function Public Shared F = M Public Shared G = M() Shared Sub Main() F = M End Sub End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:=<![CDATA[ ]]>) End Sub <WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")> <Fact> Public Sub TestLambdasInFieldInitializers() Dim source = <compilation> <file name="c.vb"> Imports System Class Class1(Of T) Dim f As Func(Of T, Integer, Integer) = Function(x, p) Dim a_outer As Integer = p * p Dim ff As Func(Of T, Integer, Integer) = Function(xx, pp) If (xx IsNot Nothing) Then Console.WriteLine(xx.GetType()) End If Console.WriteLine(p * pp) Return p End Function Return ff(x, p) End Function Public Function Goo() As Integer Return Nothing End Function Public Sub New() f(Nothing, 5) End Sub Public Sub New(p As T) f(p, 123) End Sub End Class Module Program Sub Main() Dim a As New Class1(Of DateTime) Dim b As New Class1(Of String)("abc") End Sub End Module </file> </compilation> Dim compilationVerifier = CompileAndVerify(source, expectedOutput:= <![CDATA[ System.DateTime 25 System.String 15129]]>) End Sub <WorkItem(540603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540603")> <Fact> Public Sub TestAsNewInitializers() Dim source = <compilation> <file name="c.vb"> Class Class1 Dim f1 As New Object() Dim f2 As Object = New Object() End Class </file> </compilation> Dim compilationVerifier = CompileAndVerify(source). VerifyIL("Class1..ctor", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: newobj "Sub Object..ctor()" IL_000c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0011: stfld "Class1.f1 As Object" IL_0016: ldarg.0 IL_0017: newobj "Sub Object..ctor()" IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: stfld "Class1.f2 As Object" IL_0026: ret } ]]>) End Sub <Fact> Public Sub FieldInitializerWithBadConstantValueSameModule() Dim source = <compilation> <file name="c.vb"><![CDATA[ Option Strict On Class A Public F As Integer = B.F1 End Class Class B Public Const F1 As Integer = F2 Public Shared F2 As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source) CompilationUtils.AssertTheseDiagnostics(compilation.Emit(New MemoryStream()).Diagnostics, <expected> BC30059: Constant expression is required. Public Const F1 As Integer = F2 ~~ </expected>) End Sub <Fact> Public Sub FieldInitializerWithBadConstantValueDifferentModule() Dim source1 = <compilation name="1110a705-cc34-430b-9450-ca37031aa829"> <file name="c.vb"><![CDATA[ Option Strict On Public Class B Public Const F1 As Integer = F2 Public Shared F2 As Integer End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib40(source1) compilation1.AssertTheseDiagnostics(<expected> BC30059: Constant expression is required. Public Const F1 As Integer = F2 ~~ </expected>) Dim source2 = <compilation name="2110a705-cc34-430b-9450-ca37031aa829"> <file name="c.vb"><![CDATA[ Option Strict On Class A Public F As Object = M(B.F1) Private Shared Function M(i As Integer) As Object Return Nothing End Function End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(source2, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertTheseDiagnostics(compilation2.Emit(New MemoryStream()).Diagnostics, <expected> BC36970: Failed to emit module '2110a705-cc34-430b-9450-ca37031aa829.dll': Unable to determine specific cause of the failure. </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableCodeFixProvider.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 System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared] internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseCoalesceExpressionForNullableCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetLanguageService<ISemanticFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); var coalesceExpression = whenPart == whenTrue ? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue)) : g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse)); if (semanticFacts.IsInExpressionTree( semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken)) { coalesceExpression = coalesceExpression.WithAdditionalAnnotations( WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime)); } return coalesceExpression; }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression)) { } } } }
// 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 System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared] internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseCoalesceExpressionForNullableCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetLanguageService<ISemanticFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); var coalesceExpression = whenPart == whenTrue ? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue)) : g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse)); if (semanticFacts.IsInExpressionTree( semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken)) { coalesceExpression = coalesceExpression.WithAdditionalAnnotations( WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime)); } return coalesceExpression; }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression)) { } } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/Core/Portable/Syntax/SyntaxRemoveOptions.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; namespace Microsoft.CodeAnalysis { [Flags] public enum SyntaxRemoveOptions { /// <summary> /// None of the trivia associated with the node or token is kept. /// </summary> KeepNoTrivia = 0x0, /// <summary> /// The leading trivia associated with the node or token is kept. /// </summary> KeepLeadingTrivia = 0x1, /// <summary> /// The trailing trivia associated with the node or token is kept. /// </summary> KeepTrailingTrivia = 0x2, /// <summary> /// The leading and trailing trivia associated with the node or token is kept. /// </summary> KeepExteriorTrivia = KeepLeadingTrivia | KeepTrailingTrivia, /// <summary> /// Any directives that would become unbalanced are kept. /// </summary> KeepUnbalancedDirectives = 0x4, /// <summary> /// All directives are kept /// </summary> KeepDirectives = 0x8, /// <summary> /// Ensure that at least one EndOfLine trivia is kept if one was present /// </summary> KeepEndOfLine = 0x10, /// <summary> /// Adds elastic marker trivia /// </summary> AddElasticMarker = 0x20 } }
// 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; namespace Microsoft.CodeAnalysis { [Flags] public enum SyntaxRemoveOptions { /// <summary> /// None of the trivia associated with the node or token is kept. /// </summary> KeepNoTrivia = 0x0, /// <summary> /// The leading trivia associated with the node or token is kept. /// </summary> KeepLeadingTrivia = 0x1, /// <summary> /// The trailing trivia associated with the node or token is kept. /// </summary> KeepTrailingTrivia = 0x2, /// <summary> /// The leading and trailing trivia associated with the node or token is kept. /// </summary> KeepExteriorTrivia = KeepLeadingTrivia | KeepTrailingTrivia, /// <summary> /// Any directives that would become unbalanced are kept. /// </summary> KeepUnbalancedDirectives = 0x4, /// <summary> /// All directives are kept /// </summary> KeepDirectives = 0x8, /// <summary> /// Ensure that at least one EndOfLine trivia is kept if one was present /// </summary> KeepEndOfLine = 0x10, /// <summary> /// Adds elastic marker trivia /// </summary> AddElasticMarker = 0x20 } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/Core/Test/Venus/ContainedDocumentTests_AdjustIndentation.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 False Then Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Text Imports Moq Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class ContainedDocumentTests_AdjustIndentation Inherits AbstractContainedDocumentTests <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub NoNewLines() Dim subjectBuffer = <Text> public class Default { void PreRender() { {|S1:[|int x = 1;|]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfIndent = subjectBuffer.IndexOf("{|S1") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, Enumerable.Empty(Of TextChange)(), LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub OnSingleLine() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| int x = 1; |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfIndent = subjectBuffer.IndexOf("{|S1") + vbCrLf.Length AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfIndent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub OnMultipleLines() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| if(true) { } |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} ' Span start computation explained: ' --------------------------------- ' Although this span start computation is ugly to look at, ' this is far better than just saying xx and is more readable. Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("true)") - "{|S1:[|".Length + "true)".Length + vbCrLf.Length Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length ' Span length computation explained: ' ---------------------------------- ' The length of the span being edited (replaced) is the indentation on the line. ' By outdenting all lines under test, we could just say 0 for span length. ' The edit for all lines except the very first line would also replace the previous newline ' So, the length of the span being replaced should be 0 for line 1 and 1 for everything else. ' Verify that all statements align with base. AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub IndentationInNestedStatements() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| if(true) { Console.WriteLine(5); } |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("(true)") - "{|S1:[|".Length + "(true)".Length + vbCrLf.Length Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length Dim startOfLine4Indent = subjectBuffer.IndexOf(");") - "{|S1:[|".Length + ");".Length + vbCrLf.Length ' Assert that the statement inside the if block is indented 4 spaces from the base which is at column 3. ' the default indentation is 4 spaces and this test isn't changing that. AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " "), New TextChange(New TextSpan(startOfLine4Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub InQuery() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("};") - "{|S1:[|".Length + "};".Length + vbCrLf.Length Dim startOfLine3Indent = subjectBuffer.IndexOf("where") - "{|S1:[|".Length Dim startOfLine4Indent = subjectBuffer.IndexOf("== 0") - "{|S1:[|".Length + "== 0".Length + vbCrLf.Length ' The where and select clauses should be right under from after applying a base indent of 3 to all of those. ' var even = from n in numbers ' where n % 2 == 0 ' select n; AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " "), New TextChange(New TextSpan(startOfLine4Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub AtEndOfSpan() Dim subjectBuffer = <Text> public class Default { void PreRender() {{|S1:[| int x = 1; |]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim expected As TextChange = New TextChange(New TextSpan(66, 0), " ") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus), WorkItem(529885)> Public Sub EndInSpan() Dim subjectBuffer = <Text> public class Default { void PreRender() { {|S1:[| int x = 1; |]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim expected = New TextChange(TextSpan.FromBounds(60, 68), " ") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp) End Sub Private Sub AssertAdjustIndentation( surfaceBufferMarkup As String, subjectBufferMarkup As String, spansToAdjust As IEnumerable(Of Integer), baseIndentations As IEnumerable(Of Integer), expectedEdits As IEnumerable(Of TextChange), language As String) Assert.Equal(spansToAdjust.Count, baseIndentations.Count) Using Workspace = GetWorkspace(subjectBufferMarkup, language) Dim projectedDocument = Workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, Workspace.Documents, language) Dim hostDocument = Workspace.Documents.Single() Dim spans = hostDocument.SelectedSpans Dim actualEdits As New List(Of TextChange) Dim textEdit As New Mock(Of ITextEdit) textEdit. Setup(Function(e) e.Replace(It.IsAny(Of Span)(), It.IsAny(Of String)())). Callback(Sub(span As Span, text As String) actualEdits.Add(New TextChange(New TextSpan(span.Start, span.Length), text))) For Each index In spansToAdjust ContainedDocument.AdjustIndentationForSpan(GetDocument(Workspace), hostDocument.GetTextBuffer().CurrentSnapshot, textEdit.Object, spans.Item(index), baseIndentations.ElementAt(index)) Next AssertEx.Equal(expectedEdits, actualEdits) End Using End Sub End Class End Namespace #End If
' 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 False Then Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Text Imports Moq Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus Public Class ContainedDocumentTests_AdjustIndentation Inherits AbstractContainedDocumentTests <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub NoNewLines() Dim subjectBuffer = <Text> public class Default { void PreRender() { {|S1:[|int x = 1;|]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfIndent = subjectBuffer.IndexOf("{|S1") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, Enumerable.Empty(Of TextChange)(), LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub OnSingleLine() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| int x = 1; |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfIndent = subjectBuffer.IndexOf("{|S1") + vbCrLf.Length AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfIndent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub OnMultipleLines() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| if(true) { } |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} ' Span start computation explained: ' --------------------------------- ' Although this span start computation is ugly to look at, ' this is far better than just saying xx and is more readable. Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("true)") - "{|S1:[|".Length + "true)".Length + vbCrLf.Length Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length ' Span length computation explained: ' ---------------------------------- ' The length of the span being edited (replaced) is the indentation on the line. ' By outdenting all lines under test, we could just say 0 for span length. ' The edit for all lines except the very first line would also replace the previous newline ' So, the length of the span being replaced should be 0 for line 1 and 1 for everything else. ' Verify that all statements align with base. AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub IndentationInNestedStatements() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| if(true) { Console.WriteLine(5); } |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("(true)") - "{|S1:[|".Length + "(true)".Length + vbCrLf.Length Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length Dim startOfLine4Indent = subjectBuffer.IndexOf(");") - "{|S1:[|".Length + ");".Length + vbCrLf.Length ' Assert that the statement inside the if block is indented 4 spaces from the base which is at column 3. ' the default indentation is 4 spaces and this test isn't changing that. AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " "), New TextChange(New TextSpan(startOfLine4Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub InQuery() Dim subjectBuffer = <Text> public class Default { void PreRender() { #line "Goo.aspx", 1{|S1:[| int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; |]|}#line hidden #line default } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length Dim startOfLine2Indent = subjectBuffer.IndexOf("};") - "{|S1:[|".Length + "};".Length + vbCrLf.Length Dim startOfLine3Indent = subjectBuffer.IndexOf("where") - "{|S1:[|".Length Dim startOfLine4Indent = subjectBuffer.IndexOf("== 0") - "{|S1:[|".Length + "== 0".Length + vbCrLf.Length ' The where and select clauses should be right under from after applying a base indent of 3 to all of those. ' var even = from n in numbers ' where n % 2 == 0 ' select n; AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfLine1Indent, 0), " "), New TextChange(New TextSpan(startOfLine2Indent, 0), " "), New TextChange(New TextSpan(startOfLine3Indent, 0), " "), New TextChange(New TextSpan(startOfLine4Indent, 0), " ")}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus)> Public Sub AtEndOfSpan() Dim subjectBuffer = <Text> public class Default { void PreRender() {{|S1:[| int x = 1; |]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim expected As TextChange = New TextChange(New TextSpan(66, 0), " ") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Venus), WorkItem(529885)> Public Sub EndInSpan() Dim subjectBuffer = <Text> public class Default { void PreRender() { {|S1:[| int x = 1; |]|} } } </Text>.NormalizedValue Dim spansToAdjust = {0} Dim baseIndentations = {3} Dim expected = New TextChange(TextSpan.FromBounds(60, 68), " ") AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp) End Sub Private Sub AssertAdjustIndentation( surfaceBufferMarkup As String, subjectBufferMarkup As String, spansToAdjust As IEnumerable(Of Integer), baseIndentations As IEnumerable(Of Integer), expectedEdits As IEnumerable(Of TextChange), language As String) Assert.Equal(spansToAdjust.Count, baseIndentations.Count) Using Workspace = GetWorkspace(subjectBufferMarkup, language) Dim projectedDocument = Workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, Workspace.Documents, language) Dim hostDocument = Workspace.Documents.Single() Dim spans = hostDocument.SelectedSpans Dim actualEdits As New List(Of TextChange) Dim textEdit As New Mock(Of ITextEdit) textEdit. Setup(Function(e) e.Replace(It.IsAny(Of Span)(), It.IsAny(Of String)())). Callback(Sub(span As Span, text As String) actualEdits.Add(New TextChange(New TextSpan(span.Start, span.Length), text))) For Each index In spansToAdjust ContainedDocument.AdjustIndentationForSpan(GetDocument(Workspace), hostDocument.GetTextBuffer().CurrentSnapshot, textEdit.Object, spans.Item(index), baseIndentations.ElementAt(index)) Next AssertEx.Equal(expectedEdits, actualEdits) End Using End Sub End Class End Namespace #End If
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpMoveDeclarationNearReferenceService.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveDeclarationNearReference; namespace Microsoft.CodeAnalysis.CSharp.MoveDeclarationNearReference { [ExportLanguageService(typeof(IMoveDeclarationNearReferenceService), LanguageNames.CSharp), Shared] internal partial class CSharpMoveDeclarationNearReferenceService : AbstractMoveDeclarationNearReferenceService< CSharpMoveDeclarationNearReferenceService, StatementSyntax, LocalDeclarationStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveDeclarationNearReferenceService() { } protected override bool IsMeaningfulBlock(SyntaxNode node) { return node is AnonymousFunctionExpressionSyntax || node is LocalFunctionStatementSyntax || node is CommonForEachStatementSyntax || node is ForStatementSyntax || node is WhileStatementSyntax || node is DoStatementSyntax || node is CheckedStatementSyntax; } protected override SyntaxNode GetVariableDeclaratorSymbolNode(VariableDeclaratorSyntax variableDeclarator) => variableDeclarator; protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => true; protected override SyntaxToken GetIdentifierOfVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => variableDeclarator.Identifier; protected override async Task<bool> TypesAreCompatibleAsync( Document document, ILocalSymbol localSymbol, LocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken) { var type = declarationStatement.Declaration.Type; if (type.IsVar) { // Type inference. Only merge if types match. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rightType = semanticModel.GetTypeInfo(right, cancellationToken); return Equals(localSymbol.Type, rightType.Type); } return true; } protected override bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock) => localSymbol.CanSafelyMoveLocalToBlock(currentBlock, destinationBlock); } }
// 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveDeclarationNearReference; namespace Microsoft.CodeAnalysis.CSharp.MoveDeclarationNearReference { [ExportLanguageService(typeof(IMoveDeclarationNearReferenceService), LanguageNames.CSharp), Shared] internal partial class CSharpMoveDeclarationNearReferenceService : AbstractMoveDeclarationNearReferenceService< CSharpMoveDeclarationNearReferenceService, StatementSyntax, LocalDeclarationStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveDeclarationNearReferenceService() { } protected override bool IsMeaningfulBlock(SyntaxNode node) { return node is AnonymousFunctionExpressionSyntax || node is LocalFunctionStatementSyntax || node is CommonForEachStatementSyntax || node is ForStatementSyntax || node is WhileStatementSyntax || node is DoStatementSyntax || node is CheckedStatementSyntax; } protected override SyntaxNode GetVariableDeclaratorSymbolNode(VariableDeclaratorSyntax variableDeclarator) => variableDeclarator; protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => true; protected override SyntaxToken GetIdentifierOfVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) => variableDeclarator.Identifier; protected override async Task<bool> TypesAreCompatibleAsync( Document document, ILocalSymbol localSymbol, LocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken) { var type = declarationStatement.Declaration.Type; if (type.IsVar) { // Type inference. Only merge if types match. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rightType = semanticModel.GetTypeInfo(right, cancellationToken); return Equals(localSymbol.Type, rightType.Type); } return true; } protected override bool CanMoveToBlock(ILocalSymbol localSymbol, SyntaxNode currentBlock, SyntaxNode destinationBlock) => localSymbol.CanSafelyMoveLocalToBlock(currentBlock, destinationBlock); } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/Test/Resources/Core/SymbolsTests/V2/MTTestModule1.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PEL N  ) @@ `@)O@  H.text  `.reloc @ @B)H` < ( *( *BSJB v4.0.30319l#~<#Strings(#US0#GUID@#BlobG %3  '`YmYYYYYK9b99)07 ALP gX ggFF%FF F+F0F#6F1:FE? FS+ FaC Fo0 F}H FM F}SFZF}bFoF}F}F F!F"F#F $F#%F1%F&F'??????7? g9g:Ag:Qg:""# '.              5<Module>mscorlibMicrosoft.VisualBasicClass1Class2Delegate1Interface1Interface2`1SystemObject.ctorMulticastDelegateTargetObjectTargetMethodIAsyncResultAsyncCallbackBeginInvokeDelegateCallbackDelegateAsyncStateEndInvokeDelegateAsyncResultInvokeMethod1Method3xMethod4get_Property1set_Property1Valueget_Property3set_Property3get_Property4set_Property4get_Indexerset_IndexeryzwActionadd_Event1objremove_Event1Action`1add_Event3remove_Event3add_Event4remove_Event4Property1Property3Property4IndexerEvent1Event3Event4TtSystem.ReflectionDefaultMemberAttributeAssemblyFileVersionAttributeSystem.Runtime.CompilerServicesAssemblyAttributesGoHereAssemblyVersionAttributeMTTestModule1.netmodule {!MG=E˽z\V4?_ :                     ((((( (   ( Indexer 2.0.0.0)) )_CorExeMainmscoree.dll% @ 9
MZ@ !L!This program cannot be run in DOS mode. $PEL N  ) @@ `@)O@  H.text  `.reloc @ @B)H` < ( *( *BSJB v4.0.30319l#~<#Strings(#US0#GUID@#BlobG %3  '`YmYYYYYK9b99)07 ALP gX ggFF%FF F+F0F#6F1:FE? FS+ FaC Fo0 F}H FM F}SFZF}bFoF}F}F F!F"F#F $F#%F1%F&F'??????7? g9g:Ag:Qg:""# '.              5<Module>mscorlibMicrosoft.VisualBasicClass1Class2Delegate1Interface1Interface2`1SystemObject.ctorMulticastDelegateTargetObjectTargetMethodIAsyncResultAsyncCallbackBeginInvokeDelegateCallbackDelegateAsyncStateEndInvokeDelegateAsyncResultInvokeMethod1Method3xMethod4get_Property1set_Property1Valueget_Property3set_Property3get_Property4set_Property4get_Indexerset_IndexeryzwActionadd_Event1objremove_Event1Action`1add_Event3remove_Event3add_Event4remove_Event4Property1Property3Property4IndexerEvent1Event3Event4TtSystem.ReflectionDefaultMemberAttributeAssemblyFileVersionAttributeSystem.Runtime.CompilerServicesAssemblyAttributesGoHereAssemblyVersionAttributeMTTestModule1.netmodule {!MG=E˽z\V4?_ :                     ((((( (   ( Indexer 2.0.0.0)) )_CorExeMainmscoree.dll% @ 9
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/CSharpTest/CodeActions/ConvertLinq/ConvertLinqQueryToForEachTests.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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertLinqQueryToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.CSharpConvertLinqQueryToForEachProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Select() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupBy01() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(1, 2, 3, 4, 5, 6, 7); var r = [|from i in c group i by i % 2|]; Console.WriteLine(r); } }"; // Group by is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupBy02() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(1, 2, 3, 4, 5, 6, 7); var r = [|from i in c group 10+i by i % 2|]; Console.WriteLine(r); } }"; // Group by is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect01() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; var r = [|from x1 in c1 join x2 in c2 on x1 equals x2/10 select x1+x2|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; IEnumerable<int> enumerable() { foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } } } var r = enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect02() { var source = @" using System.Linq; class Program { static void Main(string[] args) { var q1 = [|from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } join x1 in new int[] { 3, 4 } on num equals x1 select x1 + 5|]; } }"; var output = @" using System.Linq; class Program { static void Main(string[] args) { System.Collections.Generic.IEnumerable<int> enumerable() { var vs1 = new int[] { 1, 2 }; var vs = new int[] { 3, 4 }; foreach (var num in vs1) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in vs) { if (object.Equals(num, x1)) { yield return x1 + 5; } } } } } var q1 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect03() { var source = @" using System.Linq; class Program { static void Main(string[] args) { var q1 = [|from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } join x1 in new int[] { 3, 4 } on num equals x1 join x2 in new int[] { 7, 8 } on num equals x2 select x1 + 5|]; } }"; var output = @" using System.Linq; class Program { static void Main(string[] args) { System.Collections.Generic.IEnumerable<int> enumerable() { var vs2 = new int[] { 1, 2 }; var vs1 = new int[] { 3, 4 }; var vs = new int[] { 7, 8 }; foreach (var num in vs2) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in vs1) { if (object.Equals(num, x1)) { foreach (var x2 in vs) { if (object.Equals(num, x2)) { yield return x1 + 5; } } } } } } } var q1 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task OrderBy() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39); var r = [|from i in c orderby i/10 descending, i%10 select i|]; Console.WriteLine(r); } }"; // order by is not supported by foreach. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Let() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = ([|from int x in c1 let g = x * 10 let z = g + x*100 let a = 5 + z select x + z - a|]).ToList(); Console.WriteLine(r1); } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); } Console.WriteLine(r1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupJoin() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int> { 1, 2, 3, 4, 5, 7 }; List<int> c2 = new List<int> { 12, 34, 42, 51, 52, 66, 75 }; List<string> r1 = ([|from x1 in c1 join x2 in c2 on x1 equals x2 / 10 into g where x1 < 7 select x1 + "":"" + g.ToString()|]).ToList(); Console.WriteLine(r1); } } "; // GroupJoin is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromType01() { var source = @"using System; using System.Collections.Generic; class C { static void Main() { var q = [|from x in C select x|]; } static IEnumerable<int> Select<T>(Func<int, T> f) { return null; } }"; var output = @"using System; using System.Collections.Generic; class C { static void Main() { IEnumerable<int> enumerable() { foreach (var x in C) { yield return x; } } var q = enumerable(); } static IEnumerable<int> Select<T>(Func<int, T> f) { return null; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromType02() { var source = @"using System; using System.Collections.Generic; class C { static void Main() { var q = [|from x in C select x|]; } static Func<Func<int, object>, IEnumerable<object>> Select = null; }"; var output = @"using System; using System.Collections.Generic; class C { static void Main() { IEnumerable<object> enumerable() { foreach (var x in C) { yield return x; } } var q = enumerable(); } static Func<Func<int, object>, IEnumerable<object>> Select = null; }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task JoinClause() { var source = @" using System; using System.Linq; class Program { static void Main() { var q2 = [|from a in Enumerable.Range(1, 2) join b in Enumerable.Range(1, 13) on 4 * a equals b select a|]; foreach (var q in q2) { System.Console.Write(q); } } }"; var output = @" using System; using System.Linq; class Program { static void Main() { System.Collections.Generic.IEnumerable<int> enumerable2() { var enumerable1 = Enumerable.Range(1, 2); var enumerable = Enumerable.Range(1, 13); foreach (var a in enumerable1) { foreach (var b in enumerable) { if (object.Equals(4 * a, b)) { yield return a; } } } } var q2 = enumerable2(); foreach (var q in q2) { System.Console.Write(q); } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task WhereClause() { var source = @" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums where (x > 2) select x|]; string serializer = String.Empty; foreach (var q in q2) { serializer = serializer + q + "" ""; } System.Console.Write(serializer.Trim()); } }"; var output = @" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { if (x > 2) { yield return x; } } } var q2 = enumerable(); string serializer = String.Empty; foreach (var q in q2) { serializer = serializer + q + "" ""; } System.Console.Write(serializer.Trim()); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task WhereDefinedInType() { var source = @" using System.Collections.Generic; using System.Linq; class Y { public int Where(Func<int, bool> predicate) { return 45; } } class P { static void Main() { var src = new Y(); var query = [|from x in src where x > 0 select x|]]; Console.Write(query); } }"; // should not provide a conversion because of the custom Where. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryContinuation() { var source = @" using System; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select x into w select w|]; } }"; var output = @" using System; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { int w = x; yield return w; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectInto() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select x+1 into w select w+1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { int w = x + 1; yield return w + 1; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ComputeQueryVariableType() { var source = @" using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select 5|]; } }"; var output = @" using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { yield return 5; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task JoinIntoClause() { var source = @" using System; using System.Linq; static class Test { static void Main() { var qie = [|from x3 in new int[] { 0 } join x7 in (new int[] { 0 }) on 5 equals 5 into x8 select x8|]; } }"; // GroupJoin is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SemanticErrorInQuery() { var source = @" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = [|from num in nums let num = 3 select num|]; } }"; // Error: Range variable already being declared. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromVoid() { var source = @" using System.Linq; class Test { static void V() { } public static int Main() { var e1 = [|from i in V() select i|]; } } "; await TestMissingAsync(source); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignExpression() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q; q = [|from int n1 in nums from int n2 in nums select n1|]; N(q); } void N(IEnumerable<int> q) {} } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q; IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } q = enumerable(); N(q); } void N(IEnumerable<int> q) {} } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleAssignments() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1, q2; q1 = q2 = [|from x in nums select x + 1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1, q2; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } q1 = q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = [|from x in nums select x + 1|]; } class C { public IEnumerable<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } c.A = enumerable(); } class C { public IEnumerable<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleDeclarationsFirst() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1 = [|from x in nums select x + 1|], q2 = from x in nums select x + 1; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } IEnumerable<int> q1 = enumerable(), q2 = from x in nums select x + 1; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleDeclarationsSecond() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1 = from x in nums select x + 1, q2 = [|from x in nums select x + 1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } IEnumerable<int> q1 = from x in nums select x + 1, q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class, follow CodeGenTupleTests [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task TupleDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q = ([|from x in nums select x + 1|], from x in nums select x + 1); } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } var q = (enumerable(), from x in nums select x + 1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignAndReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; return q; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); return q; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return [|from x in _nums select x + 1|]; } } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { foreach (var x in _nums) { yield return x + 1; } yield break; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AnonymousType() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from a in nums from b in nums select new { a, b }|]; } } "; // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AnonymousTypeInternally() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from a in nums from b in nums select new { a, b } into c select c.a|]; } } "; // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task DuplicateIdentifiers() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M() { var q = [|from x in new[] { 1 } select x + 2 into x where x > 0 select 7 into y let x = ""aaa"" select x|]; } } "; // Duplicate identifiers are not allowed. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerableWithOtherReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { if (nums.Any()) { return [|from int n1 in nums from int n2 in nums select n1|]; } else { return null; } } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { if (nums.Any()) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } return enumerable(); } else { return null; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnObject() { var source = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } return enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExtraParenthesis() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return ([|from x in nums select x + 1|]); } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; foreach (var x in nums) { yield return x + 1; } yield break; } }"; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InReturningTuple() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { (IEnumerable<int>, int) M(IEnumerable<int> q) { return (([|from a in q select a * a|]), 1); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { (IEnumerable<int>, int) M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach(var a in q) { yield return a * a; } } return (enumerable(), 1); } } "; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInvocationReturningInTuple() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { (int, int) M(IEnumerable<int> q) { return (([|from a in q select a * a|]).Count(), 1); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { (int, int) M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach(var a in q) { yield return a * a; } } return (enumerable().Count(), 1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task RangeVariables() { var source = @" using System; using System.Linq; class Query { public static void Main(string[] args) { var c1 = new int[] {1, 2, 3}; var c2 = new int[] {10, 20, 30}; var c3 = new int[] {100, 200, 300}; var r1 = [|from int x in c1 from int y in c2 from int z in c3 select x + y + z|]; Console.WriteLine(r1); } }"; var output = @" using System; using System.Linq; class Query { public static void Main(string[] args) { var c1 = new int[] {1, 2, 3}; var c2 = new int[] {10, 20, 30}; var c3 = new int[] {100, 200, 300}; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { yield return x + y + z; } } } } var r1 = enumerable(); Console.WriteLine(r1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CallingMethodWithIEnumerable() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; N(q); } void N(IEnumerable<int> q) {} } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); N(q); } void N(IEnumerable<int> q) {} } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnFirstOrDefault() { var source = @" using System.Collections.Generic; using System.Linq; class C { T M<T>(IEnumerable<T> nums) { return ([|from n1 in nums from n2 in nums select n1|]).FirstOrDefault(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { T M<T>(IEnumerable<T> nums) { IEnumerable<T> enumerable() { foreach (var n1 in nums) { foreach (var n2 in nums) { yield return n1; } } } return enumerable().FirstOrDefault(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IncompleteQueryWithSyntaxErrors() { var source = @" using System.Linq; class Program { static int Main() { int [] goo = new int [] {1}; var q = [|from x in goo select x + 1 into z select z.T|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ErrorNameDoesNotExistsInContext() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return [|from int n1 in nums select n1|]; } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InArrayInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int>[] M(IEnumerable<int> q) { return new[] { [|from a in q select a * a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int>[] M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a * a; } } return new[] { enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InCollectionInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<IEnumerable<int>> M(IEnumerable<int> q) { return new List<IEnumerable<int>> { [|from a in q select a * a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<IEnumerable<int>> M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a * a; } } return new List<IEnumerable<int>> { enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InStructInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { struct X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { return new X() { P = [|from a in q select a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { struct X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a; } } return new X() { P = enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InClassInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { class X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { return new X() { P = [|from a in q select a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { class X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a; } } return new X() { P = enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InConstructor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { return new List<int>([|from a in q select a * a|]); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { IEnumerable<int> collection() { foreach (var a in q) { yield return a * a; } } return new List<int>(collection()); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInlineConstructor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) => new List<int>([|from a in q select a * a|]); } "; // No support for expression bodied constructors yet. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IninlineIf() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { if (true) return new List<int>([|from a in q select a * a|]); else return null; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { if (true) { IEnumerable<int> collection() { foreach (var a in q) { yield return a * a; } } return new List<int>(collection()); } else return null; } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task UsageInForEach() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; foreach (var b in q) { Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); foreach (var b in q) { Console.WriteLine(b); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task UsageInForEachSameVariableName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; foreach(var n1 in q) { Console.WriteLine(n1); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); foreach(var n1 in q) { Console.WriteLine(n1); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEach() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) { Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { var b = n1; Console.WriteLine(b); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachSameVariableNameNoType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var n1 in [|from int n1 in nums from int n2 in nums select n1|]) { Console.WriteLine(n1); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { Console.WriteLine(n1); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithExpressionBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) Console.WriteLine(b); } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { var b = n1; Console.WriteLine(b); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in [|from B a in nums from A c in nums select a|]) { Console.Write(a.ToString()); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { IEnumerable<B> @as() { foreach (B a in nums) { foreach (A c in nums) { yield return a; } } } foreach (A a in @as()) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in [|from A a in nums from A c in nums select a|]) { Console.Write(a.ToString()); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachVariableUsedInBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) { int n1 = 5; Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> bs() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } foreach (var b in bs()) { int n1 = 5; Console.WriteLine(b); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (int x in [|from x in new[] { 1, 2, 3, } select x|]) { Console.Write(x); } } } "; var output = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { IEnumerable<C> xes() { foreach (var x in new[] { 1, 2, 3, }) { yield return x; } } foreach (int x in xes()) { Console.Write(x); } } } "; await TestAsync(source, output, parseOptions: null); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSelectIdentifierButNotVariable() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, Action> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (int Test in [|from y in new[] { 1, 2, 3, } select Test|]) { Console.Write(Test); } } } "; var output = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, Action> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (var y in new[] { 1, 2, 3, }) { int Test = Test; Console.Write(Test); } } } "; await TestAsync(source, output, parseOptions: null); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IQueryable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums.AsQueryable() select n1|]; } }"; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums.AsQueryable() select n1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums.AsQueryable()) { yield return n1; } yield break; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q = [|from int n1 in nums.AsQueryable() select n1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> queryable() { foreach (int n1 in nums.AsQueryable()) { yield return n1; } } IEnumerable<int> q = queryable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = ([|from int n1 in nums.AsQueryable() select n1|]).Count(); } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; foreach (int n1 in nums.AsQueryable()) { c++; } } }"; await TestInRegularAndScriptAsync(source, output); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PropertyAssignmentInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = ([|from x in nums select x + 1|]).ToList(); } class C { public List<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); var list = new List<int>(); foreach (var x in nums) { list.Add(x + 1); } c.A = list; } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task NullablePropertyAssignmentInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c?.A = ([|from x in nums select x + 1|]).ToList(); } class C { public List<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); var list = new List<int>(); foreach (var x in nums) { list.Add(x + 1); } c?.A = list; } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignToListToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int>[] lists) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } lists[0] = list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListWithTypeArgument() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListToObject() { var source = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { object list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { var list1 = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list1.Add(n1); } } object list = list1; return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListWithNullableToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|])?.ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var list = enumerable()?.ToList<int>(); return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnListNameGeneration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); return ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); var list1 = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list1.Add(n1); } } return list1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = ([|from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where (x + y / 10 + z / 100) < 6 select g|]).ToList(); Console.WriteLine(r1); } } "; var output = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = ([|from int x in c1 join y in c2 on x equals y / 10 let z = x + y select z|]).ToList(); Console.WriteLine(r1); } } "; var output = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListOverloadAssignTo() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { ([|from x in new[] { 1 } select x|]).ToList() = new List<int>(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } enumerable().ToList() = new List<int>(); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListRefOverload() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { var a = ([|from x in new[] { 1 } select x|]).ToList(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } var a = enumerable().ToList(); } } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInMultipleDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int i = 0, cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } int i = 0, cnt = enumerable().Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInNonLocalDeclaration() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { for(int i = ([|from int n1 in nums from int n2 in nums select n1|]).Count(), i < 5; i++) { Console.WriteLine(i); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } for (int i = enumerable().Count(), i < 5; i++) { Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } } return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var count = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } } return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountExtraParethesis() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (([|from int n1 in nums from int n2 in nums select n1|]).Count()); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var count = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } } return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountAsArgument() { var source = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) { N(([|from int n1 in nums from int n2 in nums select n1|]).Count()); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } N(enumerable().Count()); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountAsArgumentExpressionBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) => N(([|from int n1 in nums from int n2 in nums select n1|]).Count()); } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountNameGeneration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int count = 1; return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int count = 1; var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountNameUsedAfter() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } int count = 1; return count; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } int count = 1; return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountNameUsedBefore() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { int count = 1; } return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { int count = 1; } var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountOverload() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(x => x > 2); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var cnt = enumerable().Count(x => x > 2); return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountOverloadAssignTo() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { ([|from x in new[] { 1 } select x|]).Count() = 5; } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } enumerable().Count() = 5; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountRefOverload() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { int a = ([|from x in new[] { 1 } select x|]).Count(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } int a = enumerable().Count(); } } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region Expression Bodied [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query => [|from x in _nums select x + 1|]; } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedField() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List<int> Query = ([|from x in _nums select x + 1|]).ToList(); } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Field() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query = [|from x in _nums select x + 1|]; } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedMethod() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query() => [|from x in _nums select x + 1|]; } "; // Cannot convert in expression bodied method await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedMethodUnderInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List<int> Query() => ([|from x in _nums select x + 1|]).ToList(); } "; // Cannot convert in expression bodied method await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedenumerable() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public void M() { IEnumerable<int> Query() => [|from x in _nums select x + 1|]; } } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedAccessor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query { get => [|from x in _nums select x + 1|]; } } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInlineLambda() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => [|from x in new int[] { 1 } select x|]; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } Func<IEnumerable<int>> lambda = () => enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InParameterLambda() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void N() { M([|from x in new int[] { 1 } select x|]); } void M(IEnumerable<int> nums) { } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void N() { IEnumerable<int> nums() { foreach (var x in new int[] { 1 }) { yield return x; } } M(nums()); } void M(IEnumerable<int> nums) { } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InParenthesizedLambdaWithBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InSimplifiedLambdaWithBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<int, IEnumerable<int>> lambda = n => { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<int, IEnumerable<int>> lambda = n => { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InAnonymousMethod() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> a = delegate () { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> a = delegate () { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InWhen() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { switch (nums.First()) { case 0 when (nums == [|from x in new int[] { 1 } select x|]): return; default: return; } } } "; // In when is not supported await TestMissingAsync(source); } #endregion #region Comments and Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InlineComments() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in /* comment */ nums from int n2 in nums select n1|]; } }"; // Cannot convert expressions with comments await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Comments() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums // comment from int n2 in nums select n1|]; } }"; // Cannot convert expressions with comments await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums #if (true) from int n2 in nums #endif select n1|]; } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #endregion #region Name Generation [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionDoesNotUseLocalFunctionName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; void enumerable() { } } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable1() { foreach (var i in c) { yield return i + 1; } } var r = enumerable1(); void enumerable() { } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionCanUseLocalFunctionParameterName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; void M(IEnumerable<int> enumerable) { } } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); void M(IEnumerable<int> enumerable) { } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionDoesNotUseLambdaParameterNameWithCSharpLessThan8() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; Action<int> myLambda = enumerable => { }; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable1() { foreach (var i in c) { yield return i + 1; } } var r = enumerable1(); Action<int> myLambda = enumerable => { }; } }"; await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp7_3)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionCanUseLambdaParameterNameInCSharp8() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; Action<int> myLambda = enumerable => { }; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); Action<int> myLambda = enumerable => { }; } }"; await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp8)); } #endregion #region CaretSelection [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task DeclarationSelection() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1;|] } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task LocalAssignmentSelection() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> r; [|r = from i in c select i+1;|] } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> r; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } #endregion } }
// 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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertLinqQueryToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.CSharpConvertLinqQueryToForEachProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Select() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupBy01() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(1, 2, 3, 4, 5, 6, 7); var r = [|from i in c group i by i % 2|]; Console.WriteLine(r); } }"; // Group by is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupBy02() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(1, 2, 3, 4, 5, 6, 7); var r = [|from i in c group 10+i by i % 2|]; Console.WriteLine(r); } }"; // Group by is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect01() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; var r = [|from x1 in c1 join x2 in c2 on x1 equals x2/10 select x1+x2|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; IEnumerable<int> enumerable() { foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } } } var r = enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect02() { var source = @" using System.Linq; class Program { static void Main(string[] args) { var q1 = [|from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } join x1 in new int[] { 3, 4 } on num equals x1 select x1 + 5|]; } }"; var output = @" using System.Linq; class Program { static void Main(string[] args) { System.Collections.Generic.IEnumerable<int> enumerable() { var vs1 = new int[] { 1, 2 }; var vs = new int[] { 3, 4 }; foreach (var num in vs1) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in vs) { if (object.Equals(num, x1)) { yield return x1 + 5; } } } } } var q1 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task FromJoinSelect03() { var source = @" using System.Linq; class Program { static void Main(string[] args) { var q1 = [|from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } join x1 in new int[] { 3, 4 } on num equals x1 join x2 in new int[] { 7, 8 } on num equals x2 select x1 + 5|]; } }"; var output = @" using System.Linq; class Program { static void Main(string[] args) { System.Collections.Generic.IEnumerable<int> enumerable() { var vs2 = new int[] { 1, 2 }; var vs1 = new int[] { 3, 4 }; var vs = new int[] { 7, 8 }; foreach (var num in vs2) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in vs1) { if (object.Equals(num, x1)) { foreach (var x2 in vs) { if (object.Equals(num, x2)) { yield return x1 + 5; } } } } } } } var q1 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task OrderBy() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39); var r = [|from i in c orderby i/10 descending, i%10 select i|]; Console.WriteLine(r); } }"; // order by is not supported by foreach. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Let() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = ([|from int x in c1 let g = x * 10 let z = g + x*100 let a = 5 + z select x + z - a|]).ToList(); Console.WriteLine(r1); } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); } Console.WriteLine(r1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task GroupJoin() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c1 = new List<int> { 1, 2, 3, 4, 5, 7 }; List<int> c2 = new List<int> { 12, 34, 42, 51, 52, 66, 75 }; List<string> r1 = ([|from x1 in c1 join x2 in c2 on x1 equals x2 / 10 into g where x1 < 7 select x1 + "":"" + g.ToString()|]).ToList(); Console.WriteLine(r1); } } "; // GroupJoin is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromType01() { var source = @"using System; using System.Collections.Generic; class C { static void Main() { var q = [|from x in C select x|]; } static IEnumerable<int> Select<T>(Func<int, T> f) { return null; } }"; var output = @"using System; using System.Collections.Generic; class C { static void Main() { IEnumerable<int> enumerable() { foreach (var x in C) { yield return x; } } var q = enumerable(); } static IEnumerable<int> Select<T>(Func<int, T> f) { return null; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromType02() { var source = @"using System; using System.Collections.Generic; class C { static void Main() { var q = [|from x in C select x|]; } static Func<Func<int, object>, IEnumerable<object>> Select = null; }"; var output = @"using System; using System.Collections.Generic; class C { static void Main() { IEnumerable<object> enumerable() { foreach (var x in C) { yield return x; } } var q = enumerable(); } static Func<Func<int, object>, IEnumerable<object>> Select = null; }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task JoinClause() { var source = @" using System; using System.Linq; class Program { static void Main() { var q2 = [|from a in Enumerable.Range(1, 2) join b in Enumerable.Range(1, 13) on 4 * a equals b select a|]; foreach (var q in q2) { System.Console.Write(q); } } }"; var output = @" using System; using System.Linq; class Program { static void Main() { System.Collections.Generic.IEnumerable<int> enumerable2() { var enumerable1 = Enumerable.Range(1, 2); var enumerable = Enumerable.Range(1, 13); foreach (var a in enumerable1) { foreach (var b in enumerable) { if (object.Equals(4 * a, b)) { yield return a; } } } } var q2 = enumerable2(); foreach (var q in q2) { System.Console.Write(q); } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task WhereClause() { var source = @" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums where (x > 2) select x|]; string serializer = String.Empty; foreach (var q in q2) { serializer = serializer + q + "" ""; } System.Console.Write(serializer.Trim()); } }"; var output = @" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { if (x > 2) { yield return x; } } } var q2 = enumerable(); string serializer = String.Empty; foreach (var q in q2) { serializer = serializer + q + "" ""; } System.Console.Write(serializer.Trim()); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task WhereDefinedInType() { var source = @" using System.Collections.Generic; using System.Linq; class Y { public int Where(Func<int, bool> predicate) { return 45; } } class P { static void Main() { var src = new Y(); var query = [|from x in src where x > 0 select x|]]; Console.Write(query); } }"; // should not provide a conversion because of the custom Where. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryContinuation() { var source = @" using System; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select x into w select w|]; } }"; var output = @" using System; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { int w = x; yield return w; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectInto() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select x+1 into w select w+1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { int w = x + 1; yield return w + 1; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ComputeQueryVariableType() { var source = @" using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = [|from x in nums select 5|]; } }"; var output = @" using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (var x in nums) { yield return 5; } } var q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task JoinIntoClause() { var source = @" using System; using System.Linq; static class Test { static void Main() { var qie = [|from x3 in new int[] { 0 } join x7 in (new int[] { 0 }) on 5 equals 5 into x8 select x8|]; } }"; // GroupJoin is not supported await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SemanticErrorInQuery() { var source = @" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = [|from num in nums let num = 3 select num|]; } }"; // Error: Range variable already being declared. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task SelectFromVoid() { var source = @" using System.Linq; class Test { static void V() { } public static int Main() { var e1 = [|from i in V() select i|]; } } "; await TestMissingAsync(source); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignExpression() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q; q = [|from int n1 in nums from int n2 in nums select n1|]; N(q); } void N(IEnumerable<int> q) {} } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q; IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } q = enumerable(); N(q); } void N(IEnumerable<int> q) {} } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleAssignments() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1, q2; q1 = q2 = [|from x in nums select x + 1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1, q2; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } q1 = q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = [|from x in nums select x + 1|]; } class C { public IEnumerable<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } c.A = enumerable(); } class C { public IEnumerable<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleDeclarationsFirst() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1 = [|from x in nums select x + 1|], q2 = from x in nums select x + 1; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } IEnumerable<int> q1 = enumerable(), q2 = from x in nums select x + 1; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task MultipleDeclarationsSecond() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> q1 = from x in nums select x + 1, q2 = [|from x in nums select x + 1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } IEnumerable<int> q1 = from x in nums select x + 1, q2 = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class, follow CodeGenTupleTests [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task TupleDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q = ([|from x in nums select x + 1|], from x in nums select x + 1); } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; IEnumerable<int> enumerable() { foreach (var x in nums) { yield return x + 1; } } var q = (enumerable(), from x in nums select x + 1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignAndReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; return q; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); return q; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return [|from x in _nums select x + 1|]; } } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { foreach (var x in _nums) { yield return x + 1; } yield break; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AnonymousType() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from a in nums from b in nums select new { a, b }|]; } } "; // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AnonymousTypeInternally() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from a in nums from b in nums select new { a, b } into c select c.a|]; } } "; // No conversion can be made because it expects to introduce a local function but the return type contains anonymous. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task DuplicateIdentifiers() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M() { var q = [|from x in new[] { 1 } select x + 2 into x where x > 0 select 7 into y let x = ""aaa"" select x|]; } } "; // Duplicate identifiers are not allowed. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } yield break; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnIEnumerableWithOtherReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { if (nums.Any()) { return [|from int n1 in nums from int n2 in nums select n1|]; } else { return null; } } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { if (nums.Any()) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } return enumerable(); } else { return null; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnObject() { var source = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { return [|from int n1 in nums from int n2 in nums select n1|]; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } return enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExtraParenthesis() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return ([|from x in nums select x + 1|]); } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; foreach (var x in nums) { yield return x + 1; } yield break; } }"; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InReturningTuple() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { (IEnumerable<int>, int) M(IEnumerable<int> q) { return (([|from a in q select a * a|]), 1); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { (IEnumerable<int>, int) M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach(var a in q) { yield return a * a; } } return (enumerable(), 1); } } "; await TestInRegularAndScriptAsync(source, output); } // TODO support tuples in the test class [Fact(Skip = "https://github.com/dotnet/roslyn/issues/25639"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInvocationReturningInTuple() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { (int, int) M(IEnumerable<int> q) { return (([|from a in q select a * a|]).Count(), 1); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { (int, int) M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach(var a in q) { yield return a * a; } } return (enumerable().Count(), 1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task RangeVariables() { var source = @" using System; using System.Linq; class Query { public static void Main(string[] args) { var c1 = new int[] {1, 2, 3}; var c2 = new int[] {10, 20, 30}; var c3 = new int[] {100, 200, 300}; var r1 = [|from int x in c1 from int y in c2 from int z in c3 select x + y + z|]; Console.WriteLine(r1); } }"; var output = @" using System; using System.Linq; class Query { public static void Main(string[] args) { var c1 = new int[] {1, 2, 3}; var c2 = new int[] {10, 20, 30}; var c3 = new int[] {100, 200, 300}; System.Collections.Generic.IEnumerable<int> enumerable() { foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { yield return x + y + z; } } } } var r1 = enumerable(); Console.WriteLine(r1); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CallingMethodWithIEnumerable() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; N(q); } void N(IEnumerable<int> q) {} } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); N(q); } void N(IEnumerable<int> q) {} } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnFirstOrDefault() { var source = @" using System.Collections.Generic; using System.Linq; class C { T M<T>(IEnumerable<T> nums) { return ([|from n1 in nums from n2 in nums select n1|]).FirstOrDefault(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { T M<T>(IEnumerable<T> nums) { IEnumerable<T> enumerable() { foreach (var n1 in nums) { foreach (var n2 in nums) { yield return n1; } } } return enumerable().FirstOrDefault(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IncompleteQueryWithSyntaxErrors() { var source = @" using System.Linq; class Program { static int Main() { int [] goo = new int [] {1}; var q = [|from x in goo select x + 1 into z select z.T|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ErrorNameDoesNotExistsInContext() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return [|from int n1 in nums select n1|]; } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InArrayInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int>[] M(IEnumerable<int> q) { return new[] { [|from a in q select a * a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { IEnumerable<int>[] M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a * a; } } return new[] { enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InCollectionInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<IEnumerable<int>> M(IEnumerable<int> q) { return new List<IEnumerable<int>> { [|from a in q select a * a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<IEnumerable<int>> M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a * a; } } return new List<IEnumerable<int>> { enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InStructInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { struct X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { return new X() { P = [|from a in q select a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { struct X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a; } } return new X() { P = enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InClassInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { class X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { return new X() { P = [|from a in q select a|] }; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { class X { public IEnumerable<int> P; } X M(IEnumerable<int> q) { IEnumerable<int> enumerable() { foreach (var a in q) { yield return a; } } return new X() { P = enumerable() }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InConstructor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { return new List<int>([|from a in q select a * a|]); } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { IEnumerable<int> collection() { foreach (var a in q) { yield return a * a; } } return new List<int>(collection()); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInlineConstructor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) => new List<int>([|from a in q select a * a|]); } "; // No support for expression bodied constructors yet. await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IninlineIf() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { if (true) return new List<int>([|from a in q select a * a|]); else return null; } } "; var output = @" using System.Collections.Generic; using System.Linq; public class Test { List<int> M(IEnumerable<int> q) { if (true) { IEnumerable<int> collection() { foreach (var a in q) { yield return a * a; } } return new List<int>(collection()); } else return null; } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task UsageInForEach() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; foreach (var b in q) { Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); foreach (var b in q) { Console.WriteLine(b); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task UsageInForEachSameVariableName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var q = [|from int n1 in nums from int n2 in nums select n1|]; foreach(var n1 in q) { Console.WriteLine(n1); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var q = enumerable(); foreach(var n1 in q) { Console.WriteLine(n1); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEach() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) { Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { var b = n1; Console.WriteLine(b); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachSameVariableNameNoType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var n1 in [|from int n1 in nums from int n2 in nums select n1|]) { Console.WriteLine(n1); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { Console.WriteLine(n1); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithExpressionBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) Console.WriteLine(b); } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (int n1 in nums) { foreach (int n2 in nums) { var b = n1; Console.WriteLine(b); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in [|from B a in nums from A c in nums select a|]) { Console.Write(a.ToString()); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { IEnumerable<B> @as() { foreach (B a in nums) { foreach (A c in nums) { yield return a; } } } foreach (A a in @as()) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in [|from A a in nums from A c in nums select a|]) { Console.Write(a.ToString()); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class A { } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachVariableUsedInBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach(var b in [|from int n1 in nums from int n2 in nums select n1|]) { int n1 = 5; Console.WriteLine(b); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> bs() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } foreach (var b in bs()) { int n1 = 5; Console.WriteLine(b); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (int x in [|from x in new[] { 1, 2, 3, } select x|]) { Console.Write(x); } } } "; var output = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { IEnumerable<C> xes() { foreach (var x in new[] { 1, 2, 3, }) { yield return x; } } foreach (int x in xes()) { Console.Write(x); } } } "; await TestAsync(source, output, parseOptions: null); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task QueryInForEachWithSelectIdentifierButNotVariable() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, Action> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (int Test in [|from y in new[] { 1, 2, 3, } select Test|]) { Console.Write(Test); } } } "; var output = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, Action> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } void Test() { foreach (var y in new[] { 1, 2, 3, }) { int Test = Test; Console.Write(Test); } } } "; await TestAsync(source, output, parseOptions: null); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IQueryable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums.AsQueryable() select n1|]; } }"; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums.AsQueryable() select n1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { foreach (int n1 in nums.AsQueryable()) { yield return n1; } yield break; } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> q = [|from int n1 in nums.AsQueryable() select n1|]; } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> queryable() { foreach (int n1 in nums.AsQueryable()) { yield return n1; } } IEnumerable<int> q = queryable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task IQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = ([|from int n1 in nums.AsQueryable() select n1|]).Count(); } }"; var output = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; foreach (int n1 in nums.AsQueryable()) { c++; } } }"; await TestInRegularAndScriptAsync(source, output); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PropertyAssignmentInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = ([|from x in nums select x + 1|]).ToList(); } class C { public List<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); var list = new List<int>(); foreach (var x in nums) { list.Add(x + 1); } c.A = list; } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task NullablePropertyAssignmentInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c?.A = ([|from x in nums select x + 1|]).ToList(); } class C { public List<int> A { get; set; } } }"; var output = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); var list = new List<int>(); foreach (var x in nums) { list.Add(x + 1); } c?.A = list; } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignToListToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int>[] lists) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } lists[0] = list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListWithTypeArgument() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListToObject() { var source = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { object list = ([|from int n1 in nums from int n2 in nums select n1|]).ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { object M(IEnumerable<int> nums) { var list1 = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list1.Add(n1); } } object list = list1; return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task AssignListWithNullableToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = ([|from int n1 in nums from int n2 in nums select n1|])?.ToList<int>(); return list; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var list = enumerable()?.ToList<int>(); return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } } return list; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnListNameGeneration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); return ([|from int n1 in nums from int n2 in nums select n1|]).ToList(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); var list1 = new List<int>(); foreach (int n1 in nums) { foreach (int n2 in nums) { list1.Add(n1); } } return list1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = ([|from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where (x + y / 10 + z / 100) < 6 select g|]).ToList(); Console.WriteLine(r1); } } "; var output = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = ([|from int x in c1 join y in c2 on x equals y / 10 let z = x + y select z|]).ToList(); Console.WriteLine(r1); } } "; var output = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListOverloadAssignTo() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { ([|from x in new[] { 1 } select x|]).ToList() = new List<int>(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } enumerable().ToList() = new List<int>(); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ToListRefOverload() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { var a = ([|from x in new[] { 1 } select x|]).ToList(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref List<int> ToList(this IEnumerable<int> enumerable) => ref enumerable.ToList(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } var a = enumerable().ToList(); } } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInMultipleDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int i = 0, cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } int i = 0, cnt = enumerable().Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInNonLocalDeclaration() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { for(int i = ([|from int n1 in nums from int n2 in nums select n1|]).Count(), i < 5; i++) { Console.WriteLine(i); } } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } for (int i = enumerable().Count(), i < 5; i++) { Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountInDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } } return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var count = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } } return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountExtraParethesis() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (([|from int n1 in nums from int n2 in nums select n1|]).Count()); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var count = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } } return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountAsArgument() { var source = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) { N(([|from int n1 in nums from int n2 in nums select n1|]).Count()); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } N(enumerable().Count()); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountAsArgumentExpressionBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void N(int value) { } void M(IEnumerable<int> nums) => N(([|from int n1 in nums from int n2 in nums select n1|]).Count()); } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountNameGeneration() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int count = 1; return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int count = 1; var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountNameUsedAfter() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } int count = 1; return count; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } int count = 1; return count; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ReturnCountNameUsedBefore() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { int count = 1; } return ([|from int n1 in nums from int n2 in nums select n1|]).Count(); } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { if (true) { int count = 1; } var count1 = 0; foreach (int n1 in nums) { foreach (int n2 in nums) { count1++; } } return count1; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountOverload() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = ([|from int n1 in nums from int n2 in nums select n1|]).Count(x => x > 2); return cnt; } } "; var output = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } } } var cnt = enumerable().Count(x => x > 2); return cnt; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountOverloadAssignTo() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { ([|from x in new[] { 1 } select x|]).Count() = 5; } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } enumerable().Count() = 5; } } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task CountRefOverload() { var source = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { int a = ([|from x in new[] { 1 } select x|]).Count(); } } } "; var output = @" using System.Collections.Generic; using System.Linq; namespace Test { static class Extensions { public static ref int Count(this IEnumerable<int> enumerable) => ref enumerable.Count(); } class Test { void M() { IEnumerable<int> enumerable() { foreach (var x in new[] { 1 }) { yield return x; } } int a = enumerable().Count(); } } } "; await TestInRegularAndScriptAsync(source, output); } #endregion #region Expression Bodied [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query => [|from x in _nums select x + 1|]; } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedField() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List<int> Query = ([|from x in _nums select x + 1|]).ToList(); } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Field() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private static readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query = [|from x in _nums select x + 1|]; } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedMethod() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query() => [|from x in _nums select x + 1|]; } "; // Cannot convert in expression bodied method await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedMethodUnderInvocation() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public List<int> Query() => ([|from x in _nums select x + 1|]).ToList(); } "; // Cannot convert in expression bodied method await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedenumerable() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public void M() { IEnumerable<int> Query() => [|from x in _nums select x + 1|]; } } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task ExpressionBodiedAccessor() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query { get => [|from x in _nums select x + 1|]; } } "; // Cannot convert in expression bodied property await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InInlineLambda() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => [|from x in new int[] { 1 } select x|]; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } Func<IEnumerable<int>> lambda = () => enumerable(); } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InParameterLambda() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void N() { M([|from x in new int[] { 1 } select x|]); } void M(IEnumerable<int> nums) { } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void N() { IEnumerable<int> nums() { foreach (var x in new int[] { 1 }) { yield return x; } } M(nums()); } void M(IEnumerable<int> nums) { } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InParenthesizedLambdaWithBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> lambda = () => { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InSimplifiedLambdaWithBody() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<int, IEnumerable<int>> lambda = n => { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<int, IEnumerable<int>> lambda = n => { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InAnonymousMethod() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> a = delegate () { return [|from x in new int[] { 1 } select x|]; }; } } "; var output = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { Func<IEnumerable<int>> a = delegate () { IEnumerable<int> enumerable() { foreach (var x in new int[] { 1 }) { yield return x; } } return enumerable(); }; } } "; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InWhen() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { switch (nums.First()) { case 0 when (nums == [|from x in new int[] { 1 } select x|]): return; default: return; } } } "; // In when is not supported await TestMissingAsync(source); } #endregion #region Comments and Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task InlineComments() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in /* comment */ nums from int n2 in nums select n1|]; } }"; // Cannot convert expressions with comments await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task Comments() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums // comment from int n2 in nums select n1|]; } }"; // Cannot convert expressions with comments await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task PreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return [|from int n1 in nums #if (true) from int n2 in nums #endif select n1|]; } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #endregion #region Name Generation [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionDoesNotUseLocalFunctionName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; void enumerable() { } } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable1() { foreach (var i in c) { yield return i + 1; } } var r = enumerable1(); void enumerable() { } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionCanUseLocalFunctionParameterName() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; void M(IEnumerable<int> enumerable) { } } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); void M(IEnumerable<int> enumerable) { } } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionDoesNotUseLambdaParameterNameWithCSharpLessThan8() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; Action<int> myLambda = enumerable => { }; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable1() { foreach (var i in c) { yield return i + 1; } } var r = enumerable1(); Action<int> myLambda = enumerable => { }; } }"; await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp7_3)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] public async Task EnumerableFunctionCanUseLambdaParameterNameInCSharp8() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1|]; Action<int> myLambda = enumerable => { }; } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); Action<int> myLambda = enumerable => { }; } }"; await TestInRegularAndScriptAsync(source, output, parseOptions: new CSharpParseOptions(CodeAnalysis.CSharp.LanguageVersion.CSharp8)); } #endregion #region CaretSelection [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task DeclarationSelection() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; var r = [|from i in c select i+1;|] } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } var r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertQueryToForEach)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task LocalAssignmentSelection() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> r; [|r = from i in c select i+1;|] } }"; var output = @" using System; using System.Collections.Generic; using System.Linq; class Query { public static void Main(string[] args) { List<int> c = new List<int>{ 1, 2, 3, 4, 5, 6, 7 }; IEnumerable<int> r; IEnumerable<int> enumerable() { foreach (var i in c) { yield return i + 1; } } r = enumerable(); } }"; await TestInRegularAndScriptAsync(source, output); } #endregion } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.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 Roslyn.Utilities; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> internal sealed partial class PointerTypeSymbol : TypeSymbol { private readonly TypeWithAnnotations _pointedAtType; /// <summary> /// Create a new PointerTypeSymbol. /// </summary> /// <param name="pointedAtType">The type being pointed at.</param> internal PointerTypeSymbol(TypeWithAnnotations pointedAtType) { Debug.Assert(pointedAtType.HasType); _pointedAtType = pointedAtType; } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public override bool IsStatic { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to, along with its annotations. /// </summary> public TypeWithAnnotations PointedAtTypeWithAnnotations { get { return _pointedAtType; } } /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> public TypeSymbol PointedAtType => PointedAtTypeWithAnnotations.Type; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get { // Pointers do not support boxing, so they really have no base type. return null; } } internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { // Pointers do not support boxing, so they really have no interfaces return ImmutableArray<NamedTypeSymbol>.Empty; } public override bool IsReferenceType { get { return false; } } public override bool IsValueType { get { return true; } } internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Unmanaged; public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<Symbol> GetMembers(string name) { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override SymbolKind Kind { get { return SymbolKind.PointerType; } } public override TypeKind TypeKind { get { return TypeKind.Pointer; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitPointerType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitPointerType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitPointerType(this); } public override int GetHashCode() { // We don't want to blow the stack if we have a type like T***************...***, // so we do not recurse until we have a non-array. int indirections = 0; TypeSymbol current = this; while (current.TypeKind == TypeKind.Pointer) { indirections += 1; current = ((PointerTypeSymbol)current).PointedAtType; } return Hash.Combine(current, indirections); } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return this.Equals(t2 as PointerTypeSymbol, comparison); } private bool Equals(PointerTypeSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { return true; } if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison)) { return false; } return true; } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { PointedAtTypeWithAnnotations.AddNullableTransforms(transforms); } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { TypeWithAnnotations oldPointedAtType = PointedAtTypeWithAnnotations; TypeWithAnnotations newPointedAtType; if (!oldPointedAtType.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newPointedAtType)) { result = this; return false; } result = WithPointedAtType(newPointedAtType); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return WithPointedAtType(transform(PointedAtTypeWithAnnotations)); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); TypeWithAnnotations pointedAtType = PointedAtTypeWithAnnotations.MergeEquivalentTypes(((PointerTypeSymbol)other).PointedAtTypeWithAnnotations, VarianceKind.None); return WithPointedAtType(pointedAtType); } internal PointerTypeSymbol WithPointedAtType(TypeWithAnnotations newPointedAtType) { return PointedAtTypeWithAnnotations.IsSameAs(newPointedAtType) ? this : new PointerTypeSymbol(newPointedAtType); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = default; // Check type, custom modifiers DeriveUseSiteInfoFromType(ref result, this.PointedAtTypeWithAnnotations, AllowedRequiredModifierType.None); return result; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return this.PointedAtTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); } protected override ISymbol CreateISymbol() { return new PublicModel.PointerTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.PointerTypeSymbol(this, nullableAnnotation); } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
// 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 Roslyn.Utilities; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> internal sealed partial class PointerTypeSymbol : TypeSymbol { private readonly TypeWithAnnotations _pointedAtType; /// <summary> /// Create a new PointerTypeSymbol. /// </summary> /// <param name="pointedAtType">The type being pointed at.</param> internal PointerTypeSymbol(TypeWithAnnotations pointedAtType) { Debug.Assert(pointedAtType.HasType); _pointedAtType = pointedAtType; } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public override bool IsStatic { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to, along with its annotations. /// </summary> public TypeWithAnnotations PointedAtTypeWithAnnotations { get { return _pointedAtType; } } /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> public TypeSymbol PointedAtType => PointedAtTypeWithAnnotations.Type; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get { // Pointers do not support boxing, so they really have no base type. return null; } } internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { // Pointers do not support boxing, so they really have no interfaces return ImmutableArray<NamedTypeSymbol>.Empty; } public override bool IsReferenceType { get { return false; } } public override bool IsValueType { get { return true; } } internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Unmanaged; public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<Symbol> GetMembers(string name) { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override SymbolKind Kind { get { return SymbolKind.PointerType; } } public override TypeKind TypeKind { get { return TypeKind.Pointer; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitPointerType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitPointerType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitPointerType(this); } public override int GetHashCode() { // We don't want to blow the stack if we have a type like T***************...***, // so we do not recurse until we have a non-array. int indirections = 0; TypeSymbol current = this; while (current.TypeKind == TypeKind.Pointer) { indirections += 1; current = ((PointerTypeSymbol)current).PointedAtType; } return Hash.Combine(current, indirections); } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return this.Equals(t2 as PointerTypeSymbol, comparison); } private bool Equals(PointerTypeSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { return true; } if ((object)other == null || !other._pointedAtType.Equals(_pointedAtType, comparison)) { return false; } return true; } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { PointedAtTypeWithAnnotations.AddNullableTransforms(transforms); } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { TypeWithAnnotations oldPointedAtType = PointedAtTypeWithAnnotations; TypeWithAnnotations newPointedAtType; if (!oldPointedAtType.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newPointedAtType)) { result = this; return false; } result = WithPointedAtType(newPointedAtType); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return WithPointedAtType(transform(PointedAtTypeWithAnnotations)); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); TypeWithAnnotations pointedAtType = PointedAtTypeWithAnnotations.MergeEquivalentTypes(((PointerTypeSymbol)other).PointedAtTypeWithAnnotations, VarianceKind.None); return WithPointedAtType(pointedAtType); } internal PointerTypeSymbol WithPointedAtType(TypeWithAnnotations newPointedAtType) { return PointedAtTypeWithAnnotations.IsSameAs(newPointedAtType) ? this : new PointerTypeSymbol(newPointedAtType); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = default; // Check type, custom modifiers DeriveUseSiteInfoFromType(ref result, this.PointedAtTypeWithAnnotations, AllowedRequiredModifierType.None); return result; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return this.PointedAtTypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); } protected override ISymbol CreateISymbol() { return new PublicModel.PointerTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.PointerTypeSymbol(this, nullableAnnotation); } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/CSharp/Portable/Symbols/Source/ExplicitInterfaceHelpers.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.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class ExplicitInterfaceHelpers { public static string GetMemberName( Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name) { TypeSymbol discardedExplicitInterfaceType; string discardedAliasOpt; string methodName = GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifierOpt, name, BindingDiagnosticBag.Discarded, out discardedExplicitInterfaceType, out discardedAliasOpt); return methodName; } public static string GetMemberNameAndInterfaceSymbol( Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name, BindingDiagnosticBag diagnostics, out TypeSymbol explicitInterfaceTypeOpt, out string aliasQualifierOpt) { if (explicitInterfaceSpecifierOpt == null) { explicitInterfaceTypeOpt = null; aliasQualifierOpt = null; return name; } // Avoid checking constraints context when binding explicit interface type since // that might result in a recursive attempt to bind the containing class. binder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); NameSyntax explicitInterfaceName = explicitInterfaceSpecifierOpt.Name; explicitInterfaceTypeOpt = binder.BindType(explicitInterfaceName, diagnostics).Type; aliasQualifierOpt = explicitInterfaceName.GetAliasQualifierOpt(); return GetMemberName(name, explicitInterfaceTypeOpt, aliasQualifierOpt); } public static string GetMemberName(string name, TypeSymbol explicitInterfaceTypeOpt, string aliasQualifierOpt) { if ((object)explicitInterfaceTypeOpt == null) { return name; } // TODO: Revisit how explicit interface implementations are named. // CONSIDER (vladres): we should never generate identical names for different methods. string interfaceName = explicitInterfaceTypeOpt.ToDisplayString(SymbolDisplayFormat.ExplicitInterfaceImplementationFormat); PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringBuilder builder = pooled.Builder; if (!string.IsNullOrEmpty(aliasQualifierOpt)) { builder.Append(aliasQualifierOpt); builder.Append("::"); } foreach (char ch in interfaceName) { // trim spaces to match metadata name (more closely - could still be truncated) if (ch != ' ') { builder.Append(ch); } } builder.Append("."); builder.Append(name); return pooled.ToStringAndFree(); } public static string GetMethodNameWithoutInterfaceName(this MethodSymbol method) { if (method.MethodKind != MethodKind.ExplicitInterfaceImplementation) { return method.Name; } return GetMemberNameWithoutInterfaceName(method.Name); } public static string GetMemberNameWithoutInterfaceName(string fullName) { var idx = fullName.LastIndexOf('.'); Debug.Assert(idx < fullName.Length); return (idx > 0) ? fullName.Substring(idx + 1) : fullName; //don't consider leading dots } #nullable enable public static ImmutableArray<T> SubstituteExplicitInterfaceImplementations<T>(ImmutableArray<T> unsubstitutedExplicitInterfaceImplementations, TypeMap map) where T : Symbol { var builder = ArrayBuilder<T>.GetInstance(); foreach (var unsubstitutedPropertyImplemented in unsubstitutedExplicitInterfaceImplementations) { builder.Add(SubstituteExplicitInterfaceImplementation(unsubstitutedPropertyImplemented, map)); } return builder.ToImmutableAndFree(); } public static T SubstituteExplicitInterfaceImplementation<T>(T unsubstitutedPropertyImplemented, TypeMap map) where T : Symbol { var unsubstitutedInterfaceType = unsubstitutedPropertyImplemented.ContainingType; Debug.Assert((object)unsubstitutedInterfaceType != null); var explicitInterfaceType = map.SubstituteNamedType(unsubstitutedInterfaceType); Debug.Assert((object)explicitInterfaceType != null); var name = unsubstitutedPropertyImplemented.Name; //should already be unqualified foreach (var candidateMember in explicitInterfaceType.GetMembers(name)) { if (candidateMember.OriginalDefinition == unsubstitutedPropertyImplemented.OriginalDefinition) { return (T)candidateMember; } } throw ExceptionUtilities.Unreachable; } #nullable disable internal static MethodSymbol FindExplicitlyImplementedMethod( this MethodSymbol implementingMethod, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMethodName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (MethodSymbol)FindExplicitlyImplementedMember(implementingMethod, isOperator, explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifierSyntax, diagnostics); } internal static PropertySymbol FindExplicitlyImplementedProperty( this PropertySymbol implementingProperty, TypeSymbol explicitInterfaceType, string interfacePropertyName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (PropertySymbol)FindExplicitlyImplementedMember(implementingProperty, isOperator: false, explicitInterfaceType, interfacePropertyName, explicitInterfaceSpecifierSyntax, diagnostics); } internal static EventSymbol FindExplicitlyImplementedEvent( this EventSymbol implementingEvent, TypeSymbol explicitInterfaceType, string interfaceEventName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (EventSymbol)FindExplicitlyImplementedMember(implementingEvent, isOperator: false, explicitInterfaceType, interfaceEventName, explicitInterfaceSpecifierSyntax, diagnostics); } private static Symbol FindExplicitlyImplementedMember( Symbol implementingMember, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMemberName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { if ((object)explicitInterfaceType == null) { return null; } var memberLocation = implementingMember.Locations[0]; var containingType = implementingMember.ContainingType; switch (containingType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: break; default: diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, memberLocation, implementingMember); return null; } if (!explicitInterfaceType.IsInterfaceType()) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, location, explicitInterfaceType); return null; } var explicitInterfaceNamedType = (NamedTypeSymbol)explicitInterfaceType; // 13.4.1: "For an explicit interface member implementation to be valid, the class or struct must name an // interface in its base class list that contains a member ..." MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[explicitInterfaceNamedType]; int setCount = set.Count; if (setCount == 0 || !set.Contains(explicitInterfaceNamedType, Symbols.SymbolEqualityComparer.ObliviousNullableModifierMatchesAny)) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); if (setCount > 0 && set.Contains(explicitInterfaceNamedType, Symbols.SymbolEqualityComparer.IgnoringNullable)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, location); } else { diagnostics.Add(ErrorCode.ERR_ClassDoesntImplementInterface, location, implementingMember, explicitInterfaceNamedType); } //do a lookup anyway } // Setting this flag to true does not imply that an interface member has been successfully implemented. // It just indicates that a corresponding interface member has been found (there may still be errors). var foundMatchingMember = false; Symbol implementedMember = null; if (!implementingMember.IsStatic || !containingType.IsInterface) { // Do not look in itself if (containingType == (object)explicitInterfaceNamedType.OriginalDefinition) { // An error will be reported elsewhere. // Either the interface is not implemented, or it causes a cycle in the interface hierarchy. return null; } var hasParamsParam = implementingMember.HasParamsParameter(); foreach (Symbol interfaceMember in explicitInterfaceNamedType.GetMembers(interfaceMemberName)) { // At this point, we know that explicitInterfaceNamedType is an interface. // However, metadata interface members can be static - we ignore them, as does Dev10. if (interfaceMember.Kind != implementingMember.Kind || !interfaceMember.IsImplementableInterfaceMember()) { continue; } if (interfaceMember is MethodSymbol interfaceMethod && (interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator) { continue; } if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementingMember, interfaceMember)) { foundMatchingMember = true; // Cannot implement accessor directly unless // the accessor is from an indexed property. if (interfaceMember.IsAccessor() && !((MethodSymbol)interfaceMember).IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_ExplicitMethodImplAccessor, memberLocation, implementingMember, interfaceMember); } else { if (interfaceMember.MustCallMethodsDirectly()) { diagnostics.Add(ErrorCode.ERR_BogusExplicitImpl, memberLocation, implementingMember, interfaceMember); } else if (hasParamsParam && !interfaceMember.HasParamsParameter()) { // Note: no error for !hasParamsParam && interfaceMethod.HasParamsParameter() // Still counts as an implementation. diagnostics.Add(ErrorCode.ERR_ExplicitImplParams, memberLocation, implementingMember, interfaceMember); } implementedMember = interfaceMember; break; } } } } if (!foundMatchingMember) { // CONSIDER: we may wish to suppress this error in the event that another error // has been reported about the signature. diagnostics.Add(ErrorCode.ERR_InterfaceMemberNotFound, memberLocation, implementingMember); } // Make sure implemented member is accessible if ((object)implementedMember != null) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, implementingMember.ContainingAssembly); if (!AccessCheck.IsSymbolAccessible(implementedMember, implementingMember.ContainingType, ref useSiteInfo, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, implementedMember); } else { switch (implementedMember.Kind) { case SymbolKind.Property: var propertySymbol = (PropertySymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(propertySymbol.GetMethod); checkAccessorIsAccessibleIfImplementable(propertySymbol.SetMethod); break; case SymbolKind.Event: var eventSymbol = (EventSymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(eventSymbol.AddMethod); checkAccessorIsAccessibleIfImplementable(eventSymbol.RemoveMethod); break; } void checkAccessorIsAccessibleIfImplementable(MethodSymbol accessor) { if (accessor.IsImplementable() && !AccessCheck.IsSymbolAccessible(accessor, implementingMember.ContainingType, ref useSiteInfo, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, accessor); } } } diagnostics.Add(memberLocation, useSiteInfo); } return implementedMember; } internal static void FindExplicitlyImplementedMemberVerification( this Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) { if ((object)implementedMember == null) { return; } if (implementingMember.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implementingMember, implementedMember)) { // it is ok to explicitly implement with no tuple names, for compatibility with C# 6, but otherwise names should match var memberLocation = implementingMember.Locations[0]; diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, memberLocation, implementingMember, implementedMember); } // In constructed types, it is possible that two method signatures could differ by only ref/out // after substitution. We look for this as part of explicit implementation because, if someone // tried to implement the ambiguous interface implicitly, we would separately raise an error about // the implicit implementation methods differing by only ref/out. FindExplicitImplementationCollisions(implementingMember, implementedMember, diagnostics); if (implementedMember.IsStatic && !implementingMember.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, implementingMember.Locations[0]); } } /// <summary> /// Given a member, look for other members contained in the same type with signatures that will /// not be distinguishable by the runtime. /// </summary> private static void FindExplicitImplementationCollisions(Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) { if ((object)implementedMember == null) { return; } NamedTypeSymbol explicitInterfaceType = implementedMember.ContainingType; bool explicitInterfaceTypeIsDefinition = explicitInterfaceType.IsDefinition; //no runtime ref/out ambiguities if this is true foreach (Symbol collisionCandidateMember in explicitInterfaceType.GetMembers(implementedMember.Name)) { if (collisionCandidateMember.Kind == implementingMember.Kind && implementedMember != collisionCandidateMember) { // NOTE: we are more precise than Dev10 - we will not generate a diagnostic if the return types differ // because that is enough to distinguish them in the runtime. if (!explicitInterfaceTypeIsDefinition && MemberSignatureComparer.RuntimeSignatureComparer.Equals(implementedMember, collisionCandidateMember)) { bool foundMismatchedRefKind = false; ImmutableArray<ParameterSymbol> implementedMemberParameters = implementedMember.GetParameters(); ImmutableArray<ParameterSymbol> collisionCandidateParameters = collisionCandidateMember.GetParameters(); int numParams = implementedMemberParameters.Length; for (int i = 0; i < numParams; i++) { if (implementedMemberParameters[i].RefKind != collisionCandidateParameters[i].RefKind) { foundMismatchedRefKind = true; break; } } if (foundMismatchedRefKind) { diagnostics.Add(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, explicitInterfaceType.Locations[0], explicitInterfaceType, implementedMember); } else { //UNDONE: related locations for conflicting members - keep iterating to find others? diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.Locations[0], implementingMember); } break; } else { if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementedMember, collisionCandidateMember)) { // NOTE: this is different from the same error code above. Above, the diagnostic means that // the runtime behavior is ambiguous because the runtime cannot distinguish between two or // more interface members. This diagnostic means that *C#* cannot distinguish between two // or more interface members (because of custom modifiers). diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.Locations[0], implementingMember); } } } } } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class ExplicitInterfaceHelpers { public static string GetMemberName( Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name) { TypeSymbol discardedExplicitInterfaceType; string discardedAliasOpt; string methodName = GetMemberNameAndInterfaceSymbol(binder, explicitInterfaceSpecifierOpt, name, BindingDiagnosticBag.Discarded, out discardedExplicitInterfaceType, out discardedAliasOpt); return methodName; } public static string GetMemberNameAndInterfaceSymbol( Binder binder, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string name, BindingDiagnosticBag diagnostics, out TypeSymbol explicitInterfaceTypeOpt, out string aliasQualifierOpt) { if (explicitInterfaceSpecifierOpt == null) { explicitInterfaceTypeOpt = null; aliasQualifierOpt = null; return name; } // Avoid checking constraints context when binding explicit interface type since // that might result in a recursive attempt to bind the containing class. binder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); NameSyntax explicitInterfaceName = explicitInterfaceSpecifierOpt.Name; explicitInterfaceTypeOpt = binder.BindType(explicitInterfaceName, diagnostics).Type; aliasQualifierOpt = explicitInterfaceName.GetAliasQualifierOpt(); return GetMemberName(name, explicitInterfaceTypeOpt, aliasQualifierOpt); } public static string GetMemberName(string name, TypeSymbol explicitInterfaceTypeOpt, string aliasQualifierOpt) { if ((object)explicitInterfaceTypeOpt == null) { return name; } // TODO: Revisit how explicit interface implementations are named. // CONSIDER (vladres): we should never generate identical names for different methods. string interfaceName = explicitInterfaceTypeOpt.ToDisplayString(SymbolDisplayFormat.ExplicitInterfaceImplementationFormat); PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringBuilder builder = pooled.Builder; if (!string.IsNullOrEmpty(aliasQualifierOpt)) { builder.Append(aliasQualifierOpt); builder.Append("::"); } foreach (char ch in interfaceName) { // trim spaces to match metadata name (more closely - could still be truncated) if (ch != ' ') { builder.Append(ch); } } builder.Append("."); builder.Append(name); return pooled.ToStringAndFree(); } public static string GetMethodNameWithoutInterfaceName(this MethodSymbol method) { if (method.MethodKind != MethodKind.ExplicitInterfaceImplementation) { return method.Name; } return GetMemberNameWithoutInterfaceName(method.Name); } public static string GetMemberNameWithoutInterfaceName(string fullName) { var idx = fullName.LastIndexOf('.'); Debug.Assert(idx < fullName.Length); return (idx > 0) ? fullName.Substring(idx + 1) : fullName; //don't consider leading dots } #nullable enable public static ImmutableArray<T> SubstituteExplicitInterfaceImplementations<T>(ImmutableArray<T> unsubstitutedExplicitInterfaceImplementations, TypeMap map) where T : Symbol { var builder = ArrayBuilder<T>.GetInstance(); foreach (var unsubstitutedPropertyImplemented in unsubstitutedExplicitInterfaceImplementations) { builder.Add(SubstituteExplicitInterfaceImplementation(unsubstitutedPropertyImplemented, map)); } return builder.ToImmutableAndFree(); } public static T SubstituteExplicitInterfaceImplementation<T>(T unsubstitutedPropertyImplemented, TypeMap map) where T : Symbol { var unsubstitutedInterfaceType = unsubstitutedPropertyImplemented.ContainingType; Debug.Assert((object)unsubstitutedInterfaceType != null); var explicitInterfaceType = map.SubstituteNamedType(unsubstitutedInterfaceType); Debug.Assert((object)explicitInterfaceType != null); var name = unsubstitutedPropertyImplemented.Name; //should already be unqualified foreach (var candidateMember in explicitInterfaceType.GetMembers(name)) { if (candidateMember.OriginalDefinition == unsubstitutedPropertyImplemented.OriginalDefinition) { return (T)candidateMember; } } throw ExceptionUtilities.Unreachable; } #nullable disable internal static MethodSymbol FindExplicitlyImplementedMethod( this MethodSymbol implementingMethod, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMethodName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (MethodSymbol)FindExplicitlyImplementedMember(implementingMethod, isOperator, explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifierSyntax, diagnostics); } internal static PropertySymbol FindExplicitlyImplementedProperty( this PropertySymbol implementingProperty, TypeSymbol explicitInterfaceType, string interfacePropertyName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (PropertySymbol)FindExplicitlyImplementedMember(implementingProperty, isOperator: false, explicitInterfaceType, interfacePropertyName, explicitInterfaceSpecifierSyntax, diagnostics); } internal static EventSymbol FindExplicitlyImplementedEvent( this EventSymbol implementingEvent, TypeSymbol explicitInterfaceType, string interfaceEventName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { return (EventSymbol)FindExplicitlyImplementedMember(implementingEvent, isOperator: false, explicitInterfaceType, interfaceEventName, explicitInterfaceSpecifierSyntax, diagnostics); } private static Symbol FindExplicitlyImplementedMember( Symbol implementingMember, bool isOperator, TypeSymbol explicitInterfaceType, string interfaceMemberName, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierSyntax, BindingDiagnosticBag diagnostics) { if ((object)explicitInterfaceType == null) { return null; } var memberLocation = implementingMember.Locations[0]; var containingType = implementingMember.ContainingType; switch (containingType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: break; default: diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, memberLocation, implementingMember); return null; } if (!explicitInterfaceType.IsInterfaceType()) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); diagnostics.Add(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, location, explicitInterfaceType); return null; } var explicitInterfaceNamedType = (NamedTypeSymbol)explicitInterfaceType; // 13.4.1: "For an explicit interface member implementation to be valid, the class or struct must name an // interface in its base class list that contains a member ..." MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[explicitInterfaceNamedType]; int setCount = set.Count; if (setCount == 0 || !set.Contains(explicitInterfaceNamedType, Symbols.SymbolEqualityComparer.ObliviousNullableModifierMatchesAny)) { //we'd like to highlight just the type part of the name var explicitInterfaceSyntax = explicitInterfaceSpecifierSyntax.Name; var location = new SourceLocation(explicitInterfaceSyntax); if (setCount > 0 && set.Contains(explicitInterfaceNamedType, Symbols.SymbolEqualityComparer.IgnoringNullable)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, location); } else { diagnostics.Add(ErrorCode.ERR_ClassDoesntImplementInterface, location, implementingMember, explicitInterfaceNamedType); } //do a lookup anyway } // Setting this flag to true does not imply that an interface member has been successfully implemented. // It just indicates that a corresponding interface member has been found (there may still be errors). var foundMatchingMember = false; Symbol implementedMember = null; if (!implementingMember.IsStatic || !containingType.IsInterface) { // Do not look in itself if (containingType == (object)explicitInterfaceNamedType.OriginalDefinition) { // An error will be reported elsewhere. // Either the interface is not implemented, or it causes a cycle in the interface hierarchy. return null; } var hasParamsParam = implementingMember.HasParamsParameter(); foreach (Symbol interfaceMember in explicitInterfaceNamedType.GetMembers(interfaceMemberName)) { // At this point, we know that explicitInterfaceNamedType is an interface. // However, metadata interface members can be static - we ignore them, as does Dev10. if (interfaceMember.Kind != implementingMember.Kind || !interfaceMember.IsImplementableInterfaceMember()) { continue; } if (interfaceMember is MethodSymbol interfaceMethod && (interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator) { continue; } if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementingMember, interfaceMember)) { foundMatchingMember = true; // Cannot implement accessor directly unless // the accessor is from an indexed property. if (interfaceMember.IsAccessor() && !((MethodSymbol)interfaceMember).IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_ExplicitMethodImplAccessor, memberLocation, implementingMember, interfaceMember); } else { if (interfaceMember.MustCallMethodsDirectly()) { diagnostics.Add(ErrorCode.ERR_BogusExplicitImpl, memberLocation, implementingMember, interfaceMember); } else if (hasParamsParam && !interfaceMember.HasParamsParameter()) { // Note: no error for !hasParamsParam && interfaceMethod.HasParamsParameter() // Still counts as an implementation. diagnostics.Add(ErrorCode.ERR_ExplicitImplParams, memberLocation, implementingMember, interfaceMember); } implementedMember = interfaceMember; break; } } } } if (!foundMatchingMember) { // CONSIDER: we may wish to suppress this error in the event that another error // has been reported about the signature. diagnostics.Add(ErrorCode.ERR_InterfaceMemberNotFound, memberLocation, implementingMember); } // Make sure implemented member is accessible if ((object)implementedMember != null) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, implementingMember.ContainingAssembly); if (!AccessCheck.IsSymbolAccessible(implementedMember, implementingMember.ContainingType, ref useSiteInfo, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, implementedMember); } else { switch (implementedMember.Kind) { case SymbolKind.Property: var propertySymbol = (PropertySymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(propertySymbol.GetMethod); checkAccessorIsAccessibleIfImplementable(propertySymbol.SetMethod); break; case SymbolKind.Event: var eventSymbol = (EventSymbol)implementedMember; checkAccessorIsAccessibleIfImplementable(eventSymbol.AddMethod); checkAccessorIsAccessibleIfImplementable(eventSymbol.RemoveMethod); break; } void checkAccessorIsAccessibleIfImplementable(MethodSymbol accessor) { if (accessor.IsImplementable() && !AccessCheck.IsSymbolAccessible(accessor, implementingMember.ContainingType, ref useSiteInfo, throughTypeOpt: null)) { diagnostics.Add(ErrorCode.ERR_BadAccess, memberLocation, accessor); } } } diagnostics.Add(memberLocation, useSiteInfo); } return implementedMember; } internal static void FindExplicitlyImplementedMemberVerification( this Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) { if ((object)implementedMember == null) { return; } if (implementingMember.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implementingMember, implementedMember)) { // it is ok to explicitly implement with no tuple names, for compatibility with C# 6, but otherwise names should match var memberLocation = implementingMember.Locations[0]; diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, memberLocation, implementingMember, implementedMember); } // In constructed types, it is possible that two method signatures could differ by only ref/out // after substitution. We look for this as part of explicit implementation because, if someone // tried to implement the ambiguous interface implicitly, we would separately raise an error about // the implicit implementation methods differing by only ref/out. FindExplicitImplementationCollisions(implementingMember, implementedMember, diagnostics); if (implementedMember.IsStatic && !implementingMember.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, implementingMember.Locations[0]); } } /// <summary> /// Given a member, look for other members contained in the same type with signatures that will /// not be distinguishable by the runtime. /// </summary> private static void FindExplicitImplementationCollisions(Symbol implementingMember, Symbol implementedMember, BindingDiagnosticBag diagnostics) { if ((object)implementedMember == null) { return; } NamedTypeSymbol explicitInterfaceType = implementedMember.ContainingType; bool explicitInterfaceTypeIsDefinition = explicitInterfaceType.IsDefinition; //no runtime ref/out ambiguities if this is true foreach (Symbol collisionCandidateMember in explicitInterfaceType.GetMembers(implementedMember.Name)) { if (collisionCandidateMember.Kind == implementingMember.Kind && implementedMember != collisionCandidateMember) { // NOTE: we are more precise than Dev10 - we will not generate a diagnostic if the return types differ // because that is enough to distinguish them in the runtime. if (!explicitInterfaceTypeIsDefinition && MemberSignatureComparer.RuntimeSignatureComparer.Equals(implementedMember, collisionCandidateMember)) { bool foundMismatchedRefKind = false; ImmutableArray<ParameterSymbol> implementedMemberParameters = implementedMember.GetParameters(); ImmutableArray<ParameterSymbol> collisionCandidateParameters = collisionCandidateMember.GetParameters(); int numParams = implementedMemberParameters.Length; for (int i = 0; i < numParams; i++) { if (implementedMemberParameters[i].RefKind != collisionCandidateParameters[i].RefKind) { foundMismatchedRefKind = true; break; } } if (foundMismatchedRefKind) { diagnostics.Add(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, explicitInterfaceType.Locations[0], explicitInterfaceType, implementedMember); } else { //UNDONE: related locations for conflicting members - keep iterating to find others? diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.Locations[0], implementingMember); } break; } else { if (MemberSignatureComparer.ExplicitImplementationComparer.Equals(implementedMember, collisionCandidateMember)) { // NOTE: this is different from the same error code above. Above, the diagnostic means that // the runtime behavior is ambiguous because the runtime cannot distinguish between two or // more interface members. This diagnostic means that *C#* cannot distinguish between two // or more interface members (because of custom modifiers). diagnostics.Add(ErrorCode.WRN_ExplicitImplCollision, implementingMember.Locations[0], implementingMember); } } } } } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <RootNamespace></RootNamespace> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\VisualStudio\VisualBasic\Impl\Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Editor" Version="$(MicrosoftVisualStudioEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to insure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Editor" /> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Roslyn.Test.Utilities" /> <Import Include="System.Threading.Tasks"/> <Import Include="System.Xml.Linq" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <RootNamespace></RootNamespace> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\VisualStudio\VisualBasic\Impl\Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Editor" Version="$(MicrosoftVisualStudioEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to insure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Editor" /> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Roslyn.Test.Utilities" /> <Import Include="System.Threading.Tasks"/> <Import Include="System.Xml.Linq" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageStrings.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.Editor.ColorSchemes; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal static class AdvancedOptionPageStrings { public static string Option_Analysis => ServicesVSResources.Analysis; public static string Option_Background_analysis_scope => ServicesVSResources.Background_analysis_scope_colon; public static string Option_Background_Analysis_Scope_Active_File => ServicesVSResources.Current_document; public static string Option_Background_Analysis_Scope_Open_Files_And_Projects => ServicesVSResources.Open_documents; public static string Option_Background_Analysis_Scope_Full_Solution => ServicesVSResources.Entire_solution; public static string Option_Enable_navigation_to_decompiled_sources => ServicesVSResources.Enable_navigation_to_decompiled_sources; public static string Option_Enable_pull_diagnostics_experimental_requires_restart => ServicesVSResources.Enable_pull_diagnostics_experimental_requires_restart; public static string Option_Enable_Razor_pull_diagnostics_experimental_requires_restart => ServicesVSResources.Enable_Razor_pull_diagnostics_experimental_requires_restart; public static string Option_run_code_analysis_in_separate_process => ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart; public static string Option_Inline_Hints_experimental => ServicesVSResources.Inline_Hints_experimental; public static string Option_Display_all_hints_while_pressing_Alt_F1 => ServicesVSResources.Display_all_hints_while_pressing_Alt_F1; public static string Option_Color_hints => ServicesVSResources.Color_hints; public static string Option_Display_inline_parameter_name_hints => ServicesVSResources.Display_inline_parameter_name_hints; public static string Option_Show_hints_for_literals => ServicesVSResources.Show_hints_for_literals; public static string Option_Show_hints_for_new_expressions => CSharpVSResources.Show_hints_for_new_expressions; public static string Option_Show_hints_for_everything_else => ServicesVSResources.Show_hints_for_everything_else; public static string Option_Show_hints_for_indexers => ServicesVSResources.Show_hints_for_indexers; public static string Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent => ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent; public static string Option_Suppress_hints_when_parameter_names_differ_only_by_suffix => ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix; public static string Option_Display_inline_type_hints => ServicesVSResources.Display_inline_type_hints; public static string Option_Show_hints_for_variables_with_inferred_types => ServicesVSResources.Show_hints_for_variables_with_inferred_types; public static string Option_Show_hints_for_lambda_parameter_types => ServicesVSResources.Show_hints_for_lambda_parameter_types; public static string Option_Show_hints_for_implicit_object_creation => ServicesVSResources.Show_hints_for_implicit_object_creation; public static string Option_RenameTrackingPreview => CSharpVSResources.Show_preview_for_rename_tracking; public static string Option_Split_string_literals_on_enter => CSharpVSResources.Split_string_literals_on_enter; public static string Option_DisplayLineSeparators => CSharpVSResources.Show_procedure_line_separators; public static string Option_Underline_reassigned_variables => ServicesVSResources.Underline_reassigned_variables; public static string Option_DontPutOutOrRefOnStruct => CSharpVSResources.Don_t_put_ref_or_out_on_custom_struct; public static string Option_EditorHelp => CSharpVSResources.Editor_Help; public static string Option_EnableHighlightKeywords { get { return CSharpVSResources.Highlight_related_keywords_under_cursor; } } public static string Option_EnableHighlightReferences { get { return CSharpVSResources.Highlight_references_to_symbol_under_cursor; } } public static string Option_EnterOutliningMode => CSharpVSResources.Enter_outlining_mode_when_files_open; public static string Option_ExtractMethod => CSharpVSResources.Extract_Method; public static string Option_Implement_Interface_or_Abstract_Class => ServicesVSResources.Implement_Interface_or_Abstract_Class; public static string Option_When_inserting_properties_events_and_methods_place_them => ServicesVSResources.When_inserting_properties_events_and_methods_place_them; public static string Option_with_other_members_of_the_same_kind => ServicesVSResources.with_other_members_of_the_same_kind; public static string Option_at_the_end => ServicesVSResources.at_the_end; public static string Option_When_generating_properties => ServicesVSResources.When_generating_properties; public static string Option_prefer_auto_properties => ServicesVSResources.codegen_prefer_auto_properties; public static string Option_prefer_throwing_properties => ServicesVSResources.prefer_throwing_properties; public static string Option_Comments => ServicesVSResources.Comments; public static string Option_GenerateXmlDocCommentsForTripleSlash => CSharpVSResources.Generate_XML_documentation_comments_for; public static string Option_InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments => CSharpVSResources.Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments; public static string Option_InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments => CSharpVSResources.Insert_at_the_start_of_new_lines_when_writing_comments; public static string Option_ShowRemarksInQuickInfo => CSharpVSResources.Show_remarks_in_Quick_Info; public static string Option_Highlighting { get { return CSharpVSResources.Highlighting; } } public static string Option_OptimizeForSolutionSize { get { return CSharpVSResources.Optimize_for_solution_size; } } public static string Option_OptimizeForSolutionSize_Large => CSharpVSResources.Large; public static string Option_OptimizeForSolutionSize_Regular => CSharpVSResources.Regular; public static string Option_OptimizeForSolutionSize_Small => CSharpVSResources.Small; public static string Option_Quick_Actions => ServicesVSResources.Quick_Actions; public static string Option_Compute_Quick_Actions_asynchronously_experimental => ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental; public static string Option_Outlining => ServicesVSResources.Outlining; public static string Option_Show_outlining_for_declaration_level_constructs => ServicesVSResources.Show_outlining_for_declaration_level_constructs; public static string Option_Show_outlining_for_code_level_constructs => ServicesVSResources.Show_outlining_for_code_level_constructs; public static string Option_Show_outlining_for_comments_and_preprocessor_regions => ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions; public static string Option_Collapse_regions_when_collapsing_to_definitions => ServicesVSResources.Collapse_regions_when_collapsing_to_definitions; public static string Option_Block_Structure_Guides => ServicesVSResources.Block_Structure_Guides; public static string Option_Show_guides_for_declaration_level_constructs => ServicesVSResources.Show_guides_for_declaration_level_constructs; public static string Option_Show_guides_for_code_level_constructs => ServicesVSResources.Show_guides_for_code_level_constructs; public static string Option_Fading => ServicesVSResources.Fading; public static string Option_Fade_out_unused_usings => CSharpVSResources.Fade_out_unused_usings; public static string Option_Fade_out_unreachable_code => ServicesVSResources.Fade_out_unreachable_code; public static string Option_Performance => CSharpVSResources.Performance; public static string Option_PlaceSystemNamespaceFirst => CSharpVSResources.Place_System_directives_first_when_sorting_usings; public static string Option_SeparateImportGroups => CSharpVSResources.Separate_using_directive_groups; public static string Option_Using_Directives => CSharpVSResources.Using_Directives; public static string Option_Suggest_usings_for_types_in_reference_assemblies => CSharpVSResources.Suggest_usings_for_types_in_dotnet_framework_assemblies; public static string Option_Suggest_usings_for_types_in_NuGet_packages => CSharpVSResources.Suggest_usings_for_types_in_NuGet_packages; public static string Option_Add_missing_using_directives_on_paste => CSharpVSResources.Add_missing_using_directives_on_paste; public static string Option_Report_invalid_placeholders_in_string_dot_format_calls => CSharpVSResources.Report_invalid_placeholders_in_string_dot_format_calls; public static string Option_Regular_Expressions => ServicesVSResources.Regular_Expressions; public static string Option_Colorize_regular_expressions => ServicesVSResources.Colorize_regular_expressions; public static string Option_Report_invalid_regular_expressions => ServicesVSResources.Report_invalid_regular_expressions; public static string Option_Highlight_related_components_under_cursor => ServicesVSResources.Highlight_related_components_under_cursor; public static string Option_Show_completion_list => ServicesVSResources.Show_completion_list; public static string Option_Editor_Color_Scheme => ServicesVSResources.Editor_Color_Scheme; public static string Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page => ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page; public static string Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations => ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations; public static string Edit_color_scheme => ServicesVSResources.Editor_Color_Scheme; public static string Option_Color_Scheme_VisualStudio2019 => ServicesVSResources.Visual_Studio_2019; public static string Option_Color_Scheme_VisualStudio2017 => ServicesVSResources.Visual_Studio_2017; public static SchemeName Color_Scheme_VisualStudio2019_Tag => SchemeName.VisualStudio2019; public static SchemeName Color_Scheme_VisualStudio2017_Tag => SchemeName.VisualStudio2017; public static string Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental => ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental; public static string Enable_all_features_in_opened_files_from_source_generators_experimental => ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental; public static string Option_Enable_file_logging_for_diagnostics => ServicesVSResources.Enable_file_logging_for_diagnostics; public static string Option_Skip_analyzers_for_implicitly_triggered_builds => ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds; public static string Show_inheritance_margin => ServicesVSResources.Show_inheritance_margin; public static string Inheritance_Margin_experimental => ServicesVSResources.Inheritance_Margin_experimental; } }
// 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.Editor.ColorSchemes; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal static class AdvancedOptionPageStrings { public static string Option_Analysis => ServicesVSResources.Analysis; public static string Option_Background_analysis_scope => ServicesVSResources.Background_analysis_scope_colon; public static string Option_Background_Analysis_Scope_Active_File => ServicesVSResources.Current_document; public static string Option_Background_Analysis_Scope_Open_Files_And_Projects => ServicesVSResources.Open_documents; public static string Option_Background_Analysis_Scope_Full_Solution => ServicesVSResources.Entire_solution; public static string Option_Enable_navigation_to_decompiled_sources => ServicesVSResources.Enable_navigation_to_decompiled_sources; public static string Option_Enable_pull_diagnostics_experimental_requires_restart => ServicesVSResources.Enable_pull_diagnostics_experimental_requires_restart; public static string Option_Enable_Razor_pull_diagnostics_experimental_requires_restart => ServicesVSResources.Enable_Razor_pull_diagnostics_experimental_requires_restart; public static string Option_run_code_analysis_in_separate_process => ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart; public static string Option_Inline_Hints_experimental => ServicesVSResources.Inline_Hints_experimental; public static string Option_Display_all_hints_while_pressing_Alt_F1 => ServicesVSResources.Display_all_hints_while_pressing_Alt_F1; public static string Option_Color_hints => ServicesVSResources.Color_hints; public static string Option_Display_inline_parameter_name_hints => ServicesVSResources.Display_inline_parameter_name_hints; public static string Option_Show_hints_for_literals => ServicesVSResources.Show_hints_for_literals; public static string Option_Show_hints_for_new_expressions => CSharpVSResources.Show_hints_for_new_expressions; public static string Option_Show_hints_for_everything_else => ServicesVSResources.Show_hints_for_everything_else; public static string Option_Show_hints_for_indexers => ServicesVSResources.Show_hints_for_indexers; public static string Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent => ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent; public static string Option_Suppress_hints_when_parameter_names_differ_only_by_suffix => ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix; public static string Option_Display_inline_type_hints => ServicesVSResources.Display_inline_type_hints; public static string Option_Show_hints_for_variables_with_inferred_types => ServicesVSResources.Show_hints_for_variables_with_inferred_types; public static string Option_Show_hints_for_lambda_parameter_types => ServicesVSResources.Show_hints_for_lambda_parameter_types; public static string Option_Show_hints_for_implicit_object_creation => ServicesVSResources.Show_hints_for_implicit_object_creation; public static string Option_RenameTrackingPreview => CSharpVSResources.Show_preview_for_rename_tracking; public static string Option_Split_string_literals_on_enter => CSharpVSResources.Split_string_literals_on_enter; public static string Option_DisplayLineSeparators => CSharpVSResources.Show_procedure_line_separators; public static string Option_Underline_reassigned_variables => ServicesVSResources.Underline_reassigned_variables; public static string Option_DontPutOutOrRefOnStruct => CSharpVSResources.Don_t_put_ref_or_out_on_custom_struct; public static string Option_EditorHelp => CSharpVSResources.Editor_Help; public static string Option_EnableHighlightKeywords { get { return CSharpVSResources.Highlight_related_keywords_under_cursor; } } public static string Option_EnableHighlightReferences { get { return CSharpVSResources.Highlight_references_to_symbol_under_cursor; } } public static string Option_EnterOutliningMode => CSharpVSResources.Enter_outlining_mode_when_files_open; public static string Option_ExtractMethod => CSharpVSResources.Extract_Method; public static string Option_Implement_Interface_or_Abstract_Class => ServicesVSResources.Implement_Interface_or_Abstract_Class; public static string Option_When_inserting_properties_events_and_methods_place_them => ServicesVSResources.When_inserting_properties_events_and_methods_place_them; public static string Option_with_other_members_of_the_same_kind => ServicesVSResources.with_other_members_of_the_same_kind; public static string Option_at_the_end => ServicesVSResources.at_the_end; public static string Option_When_generating_properties => ServicesVSResources.When_generating_properties; public static string Option_prefer_auto_properties => ServicesVSResources.codegen_prefer_auto_properties; public static string Option_prefer_throwing_properties => ServicesVSResources.prefer_throwing_properties; public static string Option_Comments => ServicesVSResources.Comments; public static string Option_GenerateXmlDocCommentsForTripleSlash => CSharpVSResources.Generate_XML_documentation_comments_for; public static string Option_InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments => CSharpVSResources.Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments; public static string Option_InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments => CSharpVSResources.Insert_at_the_start_of_new_lines_when_writing_comments; public static string Option_ShowRemarksInQuickInfo => CSharpVSResources.Show_remarks_in_Quick_Info; public static string Option_Highlighting { get { return CSharpVSResources.Highlighting; } } public static string Option_OptimizeForSolutionSize { get { return CSharpVSResources.Optimize_for_solution_size; } } public static string Option_OptimizeForSolutionSize_Large => CSharpVSResources.Large; public static string Option_OptimizeForSolutionSize_Regular => CSharpVSResources.Regular; public static string Option_OptimizeForSolutionSize_Small => CSharpVSResources.Small; public static string Option_Quick_Actions => ServicesVSResources.Quick_Actions; public static string Option_Compute_Quick_Actions_asynchronously_experimental => ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental; public static string Option_Outlining => ServicesVSResources.Outlining; public static string Option_Show_outlining_for_declaration_level_constructs => ServicesVSResources.Show_outlining_for_declaration_level_constructs; public static string Option_Show_outlining_for_code_level_constructs => ServicesVSResources.Show_outlining_for_code_level_constructs; public static string Option_Show_outlining_for_comments_and_preprocessor_regions => ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions; public static string Option_Collapse_regions_when_collapsing_to_definitions => ServicesVSResources.Collapse_regions_when_collapsing_to_definitions; public static string Option_Block_Structure_Guides => ServicesVSResources.Block_Structure_Guides; public static string Option_Show_guides_for_declaration_level_constructs => ServicesVSResources.Show_guides_for_declaration_level_constructs; public static string Option_Show_guides_for_code_level_constructs => ServicesVSResources.Show_guides_for_code_level_constructs; public static string Option_Fading => ServicesVSResources.Fading; public static string Option_Fade_out_unused_usings => CSharpVSResources.Fade_out_unused_usings; public static string Option_Fade_out_unreachable_code => ServicesVSResources.Fade_out_unreachable_code; public static string Option_Performance => CSharpVSResources.Performance; public static string Option_PlaceSystemNamespaceFirst => CSharpVSResources.Place_System_directives_first_when_sorting_usings; public static string Option_SeparateImportGroups => CSharpVSResources.Separate_using_directive_groups; public static string Option_Using_Directives => CSharpVSResources.Using_Directives; public static string Option_Suggest_usings_for_types_in_reference_assemblies => CSharpVSResources.Suggest_usings_for_types_in_dotnet_framework_assemblies; public static string Option_Suggest_usings_for_types_in_NuGet_packages => CSharpVSResources.Suggest_usings_for_types_in_NuGet_packages; public static string Option_Add_missing_using_directives_on_paste => CSharpVSResources.Add_missing_using_directives_on_paste; public static string Option_Report_invalid_placeholders_in_string_dot_format_calls => CSharpVSResources.Report_invalid_placeholders_in_string_dot_format_calls; public static string Option_Regular_Expressions => ServicesVSResources.Regular_Expressions; public static string Option_Colorize_regular_expressions => ServicesVSResources.Colorize_regular_expressions; public static string Option_Report_invalid_regular_expressions => ServicesVSResources.Report_invalid_regular_expressions; public static string Option_Highlight_related_components_under_cursor => ServicesVSResources.Highlight_related_components_under_cursor; public static string Option_Show_completion_list => ServicesVSResources.Show_completion_list; public static string Option_Editor_Color_Scheme => ServicesVSResources.Editor_Color_Scheme; public static string Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page => ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page; public static string Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations => ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations; public static string Edit_color_scheme => ServicesVSResources.Editor_Color_Scheme; public static string Option_Color_Scheme_VisualStudio2019 => ServicesVSResources.Visual_Studio_2019; public static string Option_Color_Scheme_VisualStudio2017 => ServicesVSResources.Visual_Studio_2017; public static SchemeName Color_Scheme_VisualStudio2019_Tag => SchemeName.VisualStudio2019; public static SchemeName Color_Scheme_VisualStudio2017_Tag => SchemeName.VisualStudio2017; public static string Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental => ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental; public static string Enable_all_features_in_opened_files_from_source_generators_experimental => ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental; public static string Option_Enable_file_logging_for_diagnostics => ServicesVSResources.Enable_file_logging_for_diagnostics; public static string Option_Skip_analyzers_for_implicitly_triggered_builds => ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds; public static string Show_inheritance_margin => ServicesVSResources.Show_inheritance_margin; public static string Inheritance_Margin_experimental => ServicesVSResources.Inheritance_Margin_experimental; } }
-1