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,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Portable/Lowering/SynthesizedSubmissionFields.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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <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>
internal class SynthesizedSubmissionFields
{
private readonly NamedTypeSymbol _declaringSubmissionClass;
private readonly CSharpCompilation _compilation;
private FieldSymbol _hostObjectField;
private Dictionary<ImplicitNamedTypeSymbol, FieldSymbol> _previousSubmissionFieldMap;
public SynthesizedSubmissionFields(CSharpCompilation compilation, NamedTypeSymbol submissionClass)
{
Debug.Assert(compilation != null);
Debug.Assert(submissionClass.IsSubmissionClass);
_declaringSubmissionClass = submissionClass;
_compilation = compilation;
}
internal int Count
{
get
{
return _previousSubmissionFieldMap == null ? 0 : _previousSubmissionFieldMap.Count;
}
}
internal IEnumerable<FieldSymbol> FieldSymbols
{
get
{
return _previousSubmissionFieldMap == null ? Array.Empty<FieldSymbol>() : (IEnumerable<FieldSymbol>)_previousSubmissionFieldMap.Values;
}
}
internal FieldSymbol GetHostObjectField()
{
if ((object)_hostObjectField != null)
{
return _hostObjectField;
}
var hostObjectTypeSymbol = _compilation.GetHostObjectTypeSymbol();
if ((object)hostObjectTypeSymbol != null && hostObjectTypeSymbol.Kind != SymbolKind.ErrorType)
{
return _hostObjectField = new SynthesizedFieldSymbol(
_declaringSubmissionClass, hostObjectTypeSymbol, "<host-object>", isPublic: false, isReadOnly: true, isStatic: false);
}
return null;
}
internal FieldSymbol GetOrMakeField(ImplicitNamedTypeSymbol previousSubmissionType)
{
if (_previousSubmissionFieldMap == null)
{
_previousSubmissionFieldMap = new Dictionary<ImplicitNamedTypeSymbol, FieldSymbol>();
}
FieldSymbol previousSubmissionField;
if (!_previousSubmissionFieldMap.TryGetValue(previousSubmissionType, out previousSubmissionField))
{
// TODO: generate better name?
previousSubmissionField = new SynthesizedFieldSymbol(
_declaringSubmissionClass,
previousSubmissionType,
"<" + previousSubmissionType.Name + ">",
isReadOnly: true);
_previousSubmissionFieldMap.Add(previousSubmissionType, previousSubmissionField);
}
return previousSubmissionField;
}
internal void AddToType(NamedTypeSymbol containingType, PEModuleBuilder moduleBeingBuilt)
{
foreach (var field in FieldSymbols)
{
moduleBeingBuilt.AddSynthesizedDefinition(containingType, field.GetCciAdapter());
}
FieldSymbol hostObjectField = GetHostObjectField();
if ((object)hostObjectField != null)
{
moduleBeingBuilt.AddSynthesizedDefinition(containingType, hostObjectField.GetCciAdapter());
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <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>
internal class SynthesizedSubmissionFields
{
private readonly NamedTypeSymbol _declaringSubmissionClass;
private readonly CSharpCompilation _compilation;
private FieldSymbol _hostObjectField;
private Dictionary<ImplicitNamedTypeSymbol, FieldSymbol> _previousSubmissionFieldMap;
public SynthesizedSubmissionFields(CSharpCompilation compilation, NamedTypeSymbol submissionClass)
{
Debug.Assert(compilation != null);
Debug.Assert(submissionClass.IsSubmissionClass);
_declaringSubmissionClass = submissionClass;
_compilation = compilation;
}
internal int Count
{
get
{
return _previousSubmissionFieldMap == null ? 0 : _previousSubmissionFieldMap.Count;
}
}
internal IEnumerable<FieldSymbol> FieldSymbols
{
get
{
return _previousSubmissionFieldMap == null ? Array.Empty<FieldSymbol>() : (IEnumerable<FieldSymbol>)_previousSubmissionFieldMap.Values;
}
}
internal FieldSymbol GetHostObjectField()
{
if ((object)_hostObjectField != null)
{
return _hostObjectField;
}
var hostObjectTypeSymbol = _compilation.GetHostObjectTypeSymbol();
if ((object)hostObjectTypeSymbol != null && hostObjectTypeSymbol.Kind != SymbolKind.ErrorType)
{
return _hostObjectField = new SynthesizedFieldSymbol(
_declaringSubmissionClass, hostObjectTypeSymbol, "<host-object>", isPublic: false, isReadOnly: true, isStatic: false);
}
return null;
}
internal FieldSymbol GetOrMakeField(ImplicitNamedTypeSymbol previousSubmissionType)
{
if (_previousSubmissionFieldMap == null)
{
_previousSubmissionFieldMap = new Dictionary<ImplicitNamedTypeSymbol, FieldSymbol>();
}
FieldSymbol previousSubmissionField;
if (!_previousSubmissionFieldMap.TryGetValue(previousSubmissionType, out previousSubmissionField))
{
// TODO: generate better name?
previousSubmissionField = new SynthesizedFieldSymbol(
_declaringSubmissionClass,
previousSubmissionType,
"<" + previousSubmissionType.Name + ">",
isReadOnly: true);
_previousSubmissionFieldMap.Add(previousSubmissionType, previousSubmissionField);
}
return previousSubmissionField;
}
internal void AddToType(NamedTypeSymbol containingType, PEModuleBuilder moduleBeingBuilt)
{
foreach (var field in FieldSymbols)
{
moduleBeingBuilt.AddSynthesizedDefinition(containingType, field.GetCciAdapter());
}
FieldSymbol hostObjectField = GetHostObjectField();
if ((object)hostObjectField != null)
{
moduleBeingBuilt.AddSynthesizedDefinition(containingType, hostObjectField.GetCciAdapter());
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.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.Analyzers.SimplifyInterpolation;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.SimplifyInterpolation;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer<
InterpolationSyntax, ExpressionSyntax>
{
protected override IVirtualCharService GetVirtualCharService()
=> CSharpVirtualCharService.Instance;
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance;
}
}
| // Licensed to the .NET Foundation under one or more 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.Analyzers.SimplifyInterpolation;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.SimplifyInterpolation;
namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer<
InterpolationSyntax, ExpressionSyntax>
{
protected override IVirtualCharService GetVirtualCharService()
=> CSharpVirtualCharService.Instance;
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance;
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/Core/Portable/PasteTracking/IPasteTrackingService.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.Text;
namespace Microsoft.CodeAnalysis.PasteTracking
{
internal interface IPasteTrackingService
{
bool TryGetPastedTextSpan(SourceTextContainer sourceTextContainer, out TextSpan textSpan);
}
}
| // Licensed to the .NET Foundation under one or more 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.Text;
namespace Microsoft.CodeAnalysis.PasteTracking
{
internal interface IPasteTrackingService
{
bool TryGetPastedTextSpan(SourceTextContainer sourceTextContainer, out TextSpan textSpan);
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/CSharp/Portable/CodeRefactorings/ExtractClass/CSharpExtractClassCodeRefactoringProvider.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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractClass;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ExtractClass), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ExtractInterface)]
internal class CSharpExtractClassCodeRefactoringProvider : AbstractExtractClassRefactoringProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpExtractClassCodeRefactoringProvider()
: base(null)
{
}
/// <summary>
/// Test purpose only.
/// </summary>
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
internal CSharpExtractClassCodeRefactoringProvider(IExtractClassOptionsService optionsService)
: base(optionsService)
{
}
protected override async Task<SyntaxNode?> GetSelectedClassDeclarationAsync(CodeRefactoringContext context)
{
var relaventNodes = await context.GetRelevantNodesAsync<ClassDeclarationSyntax>().ConfigureAwait(false);
return relaventNodes.FirstOrDefault();
}
protected override Task<SyntaxNode?> GetSelectedNodeAsync(CodeRefactoringContext context)
=> NodeSelectionHelpers.GetSelectedDeclarationOrVariableAsync(context);
}
}
| // Licensed to the .NET Foundation under one or more 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractClass;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ExtractClass), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ExtractInterface)]
internal class CSharpExtractClassCodeRefactoringProvider : AbstractExtractClassRefactoringProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpExtractClassCodeRefactoringProvider()
: base(null)
{
}
/// <summary>
/// Test purpose only.
/// </summary>
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
internal CSharpExtractClassCodeRefactoringProvider(IExtractClassOptionsService optionsService)
: base(optionsService)
{
}
protected override async Task<SyntaxNode?> GetSelectedClassDeclarationAsync(CodeRefactoringContext context)
{
var relaventNodes = await context.GetRelevantNodesAsync<ClassDeclarationSyntax>().ConfigureAwait(false);
return relaventNodes.FirstOrDefault();
}
protected override Task<SyntaxNode?> GetSelectedNodeAsync(CodeRefactoringContext context)
=> NodeSelectionHelpers.GetSelectedDeclarationOrVariableAsync(context);
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/Portable/InternalUtilities/Debug.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.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynDebug
{
/// <inheritdoc cref="Debug.Assert(bool)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b) => Debug.Assert(b);
/// <inheritdoc cref="Debug.Assert(bool, string)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b, string message)
=> Debug.Assert(b, message);
[Conditional("DEBUG")]
public static void AssertNotNull<T>([NotNull] T value)
{
Assert(value is object, "Unexpected null reference");
}
/// <summary>
/// Generally <see cref="Debug.Assert(bool)"/> is a sufficient method for enforcing DEBUG
/// only invariants in our code. When it triggers that providse a nice stack trace for
/// investigation. Generally that is enough.
///
/// <para>There are cases for which a stack is not enough and we need a full heap dump to
/// investigate the failure. This method takes care of that. The behavior is that when running
/// in our CI environment if the assert triggers we will rudely crash the process and
/// produce a heap dump for investigation.</para>
/// </summary>
[Conditional("DEBUG")]
internal static void AssertOrFailFast([DoesNotReturnIf(false)] bool condition, string? message = null)
{
#if NET20 || NETSTANDARD1_3
Debug.Assert(condition);
#else
if (!condition)
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX_DUMP_FOLDER")))
{
message ??= $"{nameof(AssertOrFailFast)} failed";
var stackTrace = new StackTrace();
Console.WriteLine(message);
Console.WriteLine(stackTrace);
// Use FailFast so that the process fails rudely and goes through
// windows error reporting (on Windows at least). This will allow our
// Helix environment to capture crash dumps for future investigation
Environment.FailFast(message);
}
else
{
Debug.Assert(false, message);
}
}
#endif
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynDebug
{
/// <inheritdoc cref="Debug.Assert(bool)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b) => Debug.Assert(b);
/// <inheritdoc cref="Debug.Assert(bool, string)"/>
[Conditional("DEBUG")]
public static void Assert([DoesNotReturnIf(false)] bool b, string message)
=> Debug.Assert(b, message);
[Conditional("DEBUG")]
public static void AssertNotNull<T>([NotNull] T value)
{
Assert(value is object, "Unexpected null reference");
}
/// <summary>
/// Generally <see cref="Debug.Assert(bool)"/> is a sufficient method for enforcing DEBUG
/// only invariants in our code. When it triggers that providse a nice stack trace for
/// investigation. Generally that is enough.
///
/// <para>There are cases for which a stack is not enough and we need a full heap dump to
/// investigate the failure. This method takes care of that. The behavior is that when running
/// in our CI environment if the assert triggers we will rudely crash the process and
/// produce a heap dump for investigation.</para>
/// </summary>
[Conditional("DEBUG")]
internal static void AssertOrFailFast([DoesNotReturnIf(false)] bool condition, string? message = null)
{
#if NET20 || NETSTANDARD1_3
Debug.Assert(condition);
#else
if (!condition)
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX_DUMP_FOLDER")))
{
message ??= $"{nameof(AssertOrFailFast)} failed";
var stackTrace = new StackTrace();
Console.WriteLine(message);
Console.WriteLine(stackTrace);
// Use FailFast so that the process fails rudely and goes through
// windows error reporting (on Windows at least). This will allow our
// Helix environment to capture crash dumps for future investigation
Environment.FailFast(message);
}
else
{
Debug.Assert(false, message);
}
}
#endif
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.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.Threading;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Structure
{
internal class BlockSpanCollector
{
private readonly BlockStructureOptionProvider _optionProvider;
private readonly ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> _nodeProviderMap;
private readonly ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> _triviaProviderMap;
private readonly CancellationToken _cancellationToken;
private BlockSpanCollector(
BlockStructureOptionProvider optionProvider,
ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap,
ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap,
CancellationToken cancellationToken)
{
_optionProvider = optionProvider;
_nodeProviderMap = nodeOutlinerMap;
_triviaProviderMap = triviaOutlinerMap;
_cancellationToken = cancellationToken;
}
public static void CollectBlockSpans(
SyntaxNode syntaxRoot,
BlockStructureOptionProvider optionProvider,
ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap,
ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap,
ref TemporaryArray<BlockSpan> spans,
CancellationToken cancellationToken)
{
var collector = new BlockSpanCollector(optionProvider, nodeOutlinerMap, triviaOutlinerMap, cancellationToken);
collector.Collect(syntaxRoot, ref spans);
}
private void Collect(SyntaxNode root, ref TemporaryArray<BlockSpan> spans)
{
_cancellationToken.ThrowIfCancellationRequested();
SyntaxToken previousToken = default;
foreach (var nodeOrToken in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true))
{
if (nodeOrToken.IsNode)
{
GetBlockSpans(previousToken, nodeOrToken.AsNode()!, ref spans);
}
else
{
GetBlockSpans(nodeOrToken.AsToken(), ref spans);
previousToken = nodeOrToken.AsToken();
}
}
}
private void GetBlockSpans(SyntaxToken previousToken, SyntaxNode node, ref TemporaryArray<BlockSpan> spans)
{
if (_nodeProviderMap.TryGetValue(node.GetType(), out var providers))
{
foreach (var provider in providers)
{
_cancellationToken.ThrowIfCancellationRequested();
provider.CollectBlockSpans(previousToken, node, ref spans, _optionProvider, _cancellationToken);
}
}
}
private void GetBlockSpans(SyntaxToken token, ref TemporaryArray<BlockSpan> spans)
{
GetOutliningSpans(token.LeadingTrivia, ref spans);
GetOutliningSpans(token.TrailingTrivia, ref spans);
}
private void GetOutliningSpans(SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans)
{
foreach (var trivia in triviaList)
{
_cancellationToken.ThrowIfCancellationRequested();
if (_triviaProviderMap.TryGetValue(trivia.RawKind, out var providers))
{
foreach (var provider in providers)
{
_cancellationToken.ThrowIfCancellationRequested();
provider.CollectBlockSpans(trivia, ref spans, _optionProvider, _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;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Structure
{
internal class BlockSpanCollector
{
private readonly BlockStructureOptionProvider _optionProvider;
private readonly ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> _nodeProviderMap;
private readonly ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> _triviaProviderMap;
private readonly CancellationToken _cancellationToken;
private BlockSpanCollector(
BlockStructureOptionProvider optionProvider,
ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap,
ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap,
CancellationToken cancellationToken)
{
_optionProvider = optionProvider;
_nodeProviderMap = nodeOutlinerMap;
_triviaProviderMap = triviaOutlinerMap;
_cancellationToken = cancellationToken;
}
public static void CollectBlockSpans(
SyntaxNode syntaxRoot,
BlockStructureOptionProvider optionProvider,
ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap,
ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap,
ref TemporaryArray<BlockSpan> spans,
CancellationToken cancellationToken)
{
var collector = new BlockSpanCollector(optionProvider, nodeOutlinerMap, triviaOutlinerMap, cancellationToken);
collector.Collect(syntaxRoot, ref spans);
}
private void Collect(SyntaxNode root, ref TemporaryArray<BlockSpan> spans)
{
_cancellationToken.ThrowIfCancellationRequested();
SyntaxToken previousToken = default;
foreach (var nodeOrToken in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true))
{
if (nodeOrToken.IsNode)
{
GetBlockSpans(previousToken, nodeOrToken.AsNode()!, ref spans);
}
else
{
GetBlockSpans(nodeOrToken.AsToken(), ref spans);
previousToken = nodeOrToken.AsToken();
}
}
}
private void GetBlockSpans(SyntaxToken previousToken, SyntaxNode node, ref TemporaryArray<BlockSpan> spans)
{
if (_nodeProviderMap.TryGetValue(node.GetType(), out var providers))
{
foreach (var provider in providers)
{
_cancellationToken.ThrowIfCancellationRequested();
provider.CollectBlockSpans(previousToken, node, ref spans, _optionProvider, _cancellationToken);
}
}
}
private void GetBlockSpans(SyntaxToken token, ref TemporaryArray<BlockSpan> spans)
{
GetOutliningSpans(token.LeadingTrivia, ref spans);
GetOutliningSpans(token.TrailingTrivia, ref spans);
}
private void GetOutliningSpans(SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans)
{
foreach (var trivia in triviaList)
{
_cancellationToken.ThrowIfCancellationRequested();
if (_triviaProviderMap.TryGetValue(trivia.RawKind, out var providers))
{
foreach (var provider in providers)
{
_cancellationToken.ThrowIfCancellationRequested();
provider.CollectBlockSpans(trivia, ref spans, _optionProvider, _cancellationToken);
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.SimplifyBooleanExpression
{
using static SimplifyBooleanExpressionConstants;
internal abstract class AbstractSimplifyConditionalDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TConditionalExpressionSyntax> :
AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
{
private static readonly ImmutableDictionary<string, string> s_takeCondition
= ImmutableDictionary<string, string>.Empty;
private static readonly ImmutableDictionary<string, string> s_negateCondition
= s_takeCondition.Add(Negate, Negate);
private static readonly ImmutableDictionary<string, string> s_takeConditionOrWhenFalse
= s_takeCondition.Add(Or, Or).Add(WhenFalse, WhenFalse);
private static readonly ImmutableDictionary<string, string> s_negateConditionAndWhenFalse
= s_negateCondition.Add(And, And).Add(WhenFalse, WhenFalse);
private static readonly ImmutableDictionary<string, string> s_negateConditionOrWhenTrue
= s_negateCondition.Add(Or, Or).Add(WhenTrue, WhenTrue);
private static readonly ImmutableDictionary<string, string> s_takeConditionAndWhenTrue
= s_takeCondition.Add(And, And).Add(WhenTrue, WhenTrue);
private static readonly ImmutableDictionary<string, string> s_takeConditionAndWhenFalse
= s_takeCondition.Add(And, And).Add(WhenFalse, WhenFalse);
protected AbstractSimplifyConditionalDiagnosticAnalyzer()
: base(IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId,
EnforceOnBuildValues.SimplifyConditionalExpression,
CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Conditional_expression_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract CommonConversion GetConversion(SemanticModel semanticModel, TExpressionSyntax node, CancellationToken cancellationToken);
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected sealed override void InitializeWorker(AnalysisContext context)
{
var syntaxKinds = SyntaxFacts.SyntaxKinds;
context.RegisterSyntaxNodeAction(
AnalyzeConditionalExpression, syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ConditionalExpression));
}
private void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext context)
{
var semanticModel = context.SemanticModel;
var syntaxTree = semanticModel.SyntaxTree;
var options = context.Options;
var cancellationToken = context.CancellationToken;
var styleOption = options.GetOption(
CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
semanticModel.Language, syntaxTree, cancellationToken);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
SyntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var conditionNode, out var whenTrueNode, out var whenFalseNode);
var condition = (TExpressionSyntax)conditionNode;
var whenTrue = (TExpressionSyntax)whenTrueNode;
var whenFalse = (TExpressionSyntax)whenFalseNode;
// Only offer when everything is a basic boolean type. That way we don't have to worry
// about any sort of subtle cases with implicit or bool conversions.
if (!IsSimpleBooleanType(condition) ||
!IsSimpleBooleanType(whenTrue) ||
!IsSimpleBooleanType(whenFalse))
{
return;
}
var whenTrue_isTrue = IsTrue(whenTrue);
var whenTrue_isFalse = IsFalse(whenTrue);
var whenFalse_isTrue = IsTrue(whenFalse);
var whenFalse_isFalse = IsFalse(whenFalse);
if (whenTrue_isTrue && whenFalse_isFalse)
{
// c ? true : false => c
ReportDiagnostic(s_takeCondition);
}
else if (whenTrue_isFalse && whenFalse_isTrue)
{
// c ? false : true => !c
ReportDiagnostic(s_negateCondition);
}
else if (whenTrue_isFalse && whenFalse_isFalse)
{
// c ? false : false => c && false
// Note: this is a slight optimization over the when `c ? false : wf`
// case below. It allows to generate `c && false` instead of `!c && false`
ReportDiagnostic(s_takeConditionAndWhenFalse);
}
else if (whenTrue_isTrue)
{
// c ? true : wf => c || wf
ReportDiagnostic(s_takeConditionOrWhenFalse);
}
else if (whenTrue_isFalse)
{
// c ? false : wf => !c && wf
ReportDiagnostic(s_negateConditionAndWhenFalse);
}
else if (whenFalse_isTrue)
{
// c ? wt : true => !c or wt
ReportDiagnostic(s_negateConditionOrWhenTrue);
}
else if (whenFalse_isFalse)
{
// c ? wt : false => c && wt
ReportDiagnostic(s_takeConditionAndWhenTrue);
}
return;
// local functions
void ReportDiagnostic(ImmutableDictionary<string, string> properties)
=> context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
conditionalExpression.GetLocation(),
styleOption.Notification.Severity,
additionalLocations: null,
properties));
bool IsSimpleBooleanType(TExpressionSyntax node)
{
var typeInfo = semanticModel.GetTypeInfo(node, cancellationToken);
var conversion = GetConversion(semanticModel, node, cancellationToken);
return
conversion.MethodSymbol == null &&
typeInfo.Type?.SpecialType == SpecialType.System_Boolean &&
typeInfo.ConvertedType?.SpecialType == SpecialType.System_Boolean;
}
bool IsTrue(TExpressionSyntax node) => IsBoolValue(node, true);
bool IsFalse(TExpressionSyntax node) => IsBoolValue(node, false);
bool IsBoolValue(TExpressionSyntax node, bool value)
{
var constantValue = semanticModel.GetConstantValue(node, cancellationToken);
return constantValue.HasValue && constantValue.Value is bool b && b == 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 System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.SimplifyBooleanExpression
{
using static SimplifyBooleanExpressionConstants;
internal abstract class AbstractSimplifyConditionalDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TConditionalExpressionSyntax> :
AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
{
private static readonly ImmutableDictionary<string, string> s_takeCondition
= ImmutableDictionary<string, string>.Empty;
private static readonly ImmutableDictionary<string, string> s_negateCondition
= s_takeCondition.Add(Negate, Negate);
private static readonly ImmutableDictionary<string, string> s_takeConditionOrWhenFalse
= s_takeCondition.Add(Or, Or).Add(WhenFalse, WhenFalse);
private static readonly ImmutableDictionary<string, string> s_negateConditionAndWhenFalse
= s_negateCondition.Add(And, And).Add(WhenFalse, WhenFalse);
private static readonly ImmutableDictionary<string, string> s_negateConditionOrWhenTrue
= s_negateCondition.Add(Or, Or).Add(WhenTrue, WhenTrue);
private static readonly ImmutableDictionary<string, string> s_takeConditionAndWhenTrue
= s_takeCondition.Add(And, And).Add(WhenTrue, WhenTrue);
private static readonly ImmutableDictionary<string, string> s_takeConditionAndWhenFalse
= s_takeCondition.Add(And, And).Add(WhenFalse, WhenFalse);
protected AbstractSimplifyConditionalDiagnosticAnalyzer()
: base(IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId,
EnforceOnBuildValues.SimplifyConditionalExpression,
CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Conditional_expression_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract CommonConversion GetConversion(SemanticModel semanticModel, TExpressionSyntax node, CancellationToken cancellationToken);
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected sealed override void InitializeWorker(AnalysisContext context)
{
var syntaxKinds = SyntaxFacts.SyntaxKinds;
context.RegisterSyntaxNodeAction(
AnalyzeConditionalExpression, syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ConditionalExpression));
}
private void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext context)
{
var semanticModel = context.SemanticModel;
var syntaxTree = semanticModel.SyntaxTree;
var options = context.Options;
var cancellationToken = context.CancellationToken;
var styleOption = options.GetOption(
CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
semanticModel.Language, syntaxTree, cancellationToken);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
SyntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var conditionNode, out var whenTrueNode, out var whenFalseNode);
var condition = (TExpressionSyntax)conditionNode;
var whenTrue = (TExpressionSyntax)whenTrueNode;
var whenFalse = (TExpressionSyntax)whenFalseNode;
// Only offer when everything is a basic boolean type. That way we don't have to worry
// about any sort of subtle cases with implicit or bool conversions.
if (!IsSimpleBooleanType(condition) ||
!IsSimpleBooleanType(whenTrue) ||
!IsSimpleBooleanType(whenFalse))
{
return;
}
var whenTrue_isTrue = IsTrue(whenTrue);
var whenTrue_isFalse = IsFalse(whenTrue);
var whenFalse_isTrue = IsTrue(whenFalse);
var whenFalse_isFalse = IsFalse(whenFalse);
if (whenTrue_isTrue && whenFalse_isFalse)
{
// c ? true : false => c
ReportDiagnostic(s_takeCondition);
}
else if (whenTrue_isFalse && whenFalse_isTrue)
{
// c ? false : true => !c
ReportDiagnostic(s_negateCondition);
}
else if (whenTrue_isFalse && whenFalse_isFalse)
{
// c ? false : false => c && false
// Note: this is a slight optimization over the when `c ? false : wf`
// case below. It allows to generate `c && false` instead of `!c && false`
ReportDiagnostic(s_takeConditionAndWhenFalse);
}
else if (whenTrue_isTrue)
{
// c ? true : wf => c || wf
ReportDiagnostic(s_takeConditionOrWhenFalse);
}
else if (whenTrue_isFalse)
{
// c ? false : wf => !c && wf
ReportDiagnostic(s_negateConditionAndWhenFalse);
}
else if (whenFalse_isTrue)
{
// c ? wt : true => !c or wt
ReportDiagnostic(s_negateConditionOrWhenTrue);
}
else if (whenFalse_isFalse)
{
// c ? wt : false => c && wt
ReportDiagnostic(s_takeConditionAndWhenTrue);
}
return;
// local functions
void ReportDiagnostic(ImmutableDictionary<string, string> properties)
=> context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
conditionalExpression.GetLocation(),
styleOption.Notification.Severity,
additionalLocations: null,
properties));
bool IsSimpleBooleanType(TExpressionSyntax node)
{
var typeInfo = semanticModel.GetTypeInfo(node, cancellationToken);
var conversion = GetConversion(semanticModel, node, cancellationToken);
return
conversion.MethodSymbol == null &&
typeInfo.Type?.SpecialType == SpecialType.System_Boolean &&
typeInfo.ConvertedType?.SpecialType == SpecialType.System_Boolean;
}
bool IsTrue(TExpressionSyntax node) => IsBoolValue(node, true);
bool IsFalse(TExpressionSyntax node) => IsBoolValue(node, false);
bool IsBoolValue(TExpressionSyntax node, bool value)
{
var constantValue = semanticModel.GetConstantValue(node, cancellationToken);
return constantValue.HasValue && constantValue.Value is bool b && b == value;
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class BlockSyntaxExtensions
{
public static bool TryConvertToExpressionBody(
this BlockSyntax block,
ParseOptions options, ExpressionBodyPreference preference,
out ExpressionSyntax expression,
out SyntaxToken semicolonToken)
{
if (preference != ExpressionBodyPreference.Never &&
block != null && block.Statements.Count == 1)
{
var firstStatement = block.Statements[0];
var version = ((CSharpParseOptions)options).LanguageVersion;
if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) &&
MatchesPreference(expression, preference))
{
// The close brace of the block may have important trivia on it (like
// comments or directives). Preserve them on the semicolon when we
// convert to an expression body.
semicolonToken = semicolonToken.WithAppendedTrailingTrivia(
block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine()));
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
public static bool TryConvertToArrowExpressionBody(
this BlockSyntax block, SyntaxKind declarationKind,
ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
var version = ((CSharpParseOptions)options).LanguageVersion;
// We can always use arrow-expression bodies in C# 7 or above.
// We can also use them in C# 6, but only a select set of member kinds.
var acceptableVersion =
version >= LanguageVersion.CSharp7 ||
(version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));
if (!acceptableVersion ||
!block.TryConvertToExpressionBody(
options, preference,
out var expression, out semicolonToken))
{
arrowExpression = null;
semicolonToken = default;
return false;
}
arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);
return true;
}
private static bool IsSupportedInCSharp6(SyntaxKind declarationKind)
{
switch (declarationKind)
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
return false;
}
return true;
}
public static bool MatchesPreference(
ExpressionSyntax expression, ExpressionBodyPreference preference)
{
if (preference == ExpressionBodyPreference.WhenPossible)
{
return true;
}
Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine);
return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false);
}
private static bool TryGetExpression(
LanguageVersion version, StatementSyntax firstStatement,
out ExpressionSyntax expression, out SyntaxToken semicolonToken)
{
if (firstStatement is ExpressionStatementSyntax exprStatement)
{
expression = exprStatement.Expression;
semicolonToken = exprStatement.SemicolonToken;
return true;
}
else if (firstStatement is ReturnStatementSyntax returnStatement)
{
if (returnStatement.Expression != null)
{
// If there are any comments or directives on the return keyword, move them to
// the expression.
expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment())
? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia())
: returnStatement.Expression;
semicolonToken = returnStatement.SemicolonToken;
return true;
}
}
else if (firstStatement is ThrowStatementSyntax throwStatement)
{
if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null)
{
expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
semicolonToken = throwStatement.SemicolonToken;
return true;
}
}
expression = null;
semicolonToken = default;
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.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class BlockSyntaxExtensions
{
public static bool TryConvertToExpressionBody(
this BlockSyntax block,
ParseOptions options, ExpressionBodyPreference preference,
out ExpressionSyntax expression,
out SyntaxToken semicolonToken)
{
if (preference != ExpressionBodyPreference.Never &&
block != null && block.Statements.Count == 1)
{
var firstStatement = block.Statements[0];
var version = ((CSharpParseOptions)options).LanguageVersion;
if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) &&
MatchesPreference(expression, preference))
{
// The close brace of the block may have important trivia on it (like
// comments or directives). Preserve them on the semicolon when we
// convert to an expression body.
semicolonToken = semicolonToken.WithAppendedTrailingTrivia(
block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine()));
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
public static bool TryConvertToArrowExpressionBody(
this BlockSyntax block, SyntaxKind declarationKind,
ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
var version = ((CSharpParseOptions)options).LanguageVersion;
// We can always use arrow-expression bodies in C# 7 or above.
// We can also use them in C# 6, but only a select set of member kinds.
var acceptableVersion =
version >= LanguageVersion.CSharp7 ||
(version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));
if (!acceptableVersion ||
!block.TryConvertToExpressionBody(
options, preference,
out var expression, out semicolonToken))
{
arrowExpression = null;
semicolonToken = default;
return false;
}
arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);
return true;
}
private static bool IsSupportedInCSharp6(SyntaxKind declarationKind)
{
switch (declarationKind)
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
return false;
}
return true;
}
public static bool MatchesPreference(
ExpressionSyntax expression, ExpressionBodyPreference preference)
{
if (preference == ExpressionBodyPreference.WhenPossible)
{
return true;
}
Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine);
return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false);
}
private static bool TryGetExpression(
LanguageVersion version, StatementSyntax firstStatement,
out ExpressionSyntax expression, out SyntaxToken semicolonToken)
{
if (firstStatement is ExpressionStatementSyntax exprStatement)
{
expression = exprStatement.Expression;
semicolonToken = exprStatement.SemicolonToken;
return true;
}
else if (firstStatement is ReturnStatementSyntax returnStatement)
{
if (returnStatement.Expression != null)
{
// If there are any comments or directives on the return keyword, move them to
// the expression.
expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment())
? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia())
: returnStatement.Expression;
semicolonToken = returnStatement.SemicolonToken;
return true;
}
}
else if (firstStatement is ThrowStatementSyntax throwStatement)
{
if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null)
{
expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
semicolonToken = throwStatement.SemicolonToken;
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IConstructorBodyOperation.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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests_IConstructorBodyOperation : SemanticModelTestBase
{
[Fact]
public void ConstructorBody_01()
{
string source = @"
class C
{
public C()
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// file.cs(4,15): error CS1002: ; expected
// public C()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15),
// file.cs(4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
Assert.Null(model.GetOperation(node1));
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_02()
{
// No body, initializer without declarations
string source = @"
class C
{
public C() : base()
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,24): error CS1002: ; expected
// public C() : base()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 24),
// (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C() : base()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'public C() : base()')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
null
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_03()
{
// Block body, initializer without declarations
string source = @"
class C
{
public C() : base()
{ throw null; }
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... row null; }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_04()
{
// Expression body, initializer without declarations
string source = @"
class C
{
public C() : base()
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... throw null;')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
null
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_05()
{
// Block body, no initializer
string source = @"
class C
{
public C()
{ throw null; }
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... row null; }')
Initializer:
null
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_06()
{
// Expression body, no initializer
string source = @"
class C
{
public C()
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... throw null;')
Initializer:
null
BlockBody:
null
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_07()
{
// Block and expression body, no initializer
string source = @"
class C
{
public C()
{ throw null; }
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C()
{ throw null; }
=> throw null;").WithLocation(4, 5)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'public C() ... throw null;')
Initializer:
null
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
.erroneous body {R1}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
}
Block[B3] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[Fact]
public void ConstructorBody_08()
{
// No body, no initializer
string source = @"
class C
{
public C();
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// file.cs(4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C();
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
Assert.Null(model.GetOperation(node1));
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_09()
{
// Block and expression body, initializer without declarations
string source = @"
class C
{
public C(int i1, int i2, int j1, int j2) : base()
{ i1 = i2; }
=> j1 = j2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C(int i1, int i2, int j1, int j2) : base()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C(int i1, int i2, int j1, int j2) : base()
{ i1 = i2; }
=> j1 = j2;").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = i2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = i2')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
Right:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
Next (Regular) Block[B3]
.erroneous body {R1}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j1 = j2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j1 = j2')
Left:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1')
Right:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_10()
{
// Verify block body with a return statement, followed by throw in expression body.
// This caught an assert when attempting to link current basic block which was already linked to exit.
string source = @"
class C
{
public C()
{ return; }
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C()
{ return; }
=> throw null;").WithLocation(4, 5)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
.erroneous body {R1}
{
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
}
Block[B2] - Exit
Predecessors: [B0]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_11()
{
// Block body, initializer with declarations
string source = @"
class C : Base
{
C(int p) : base(out var i)
{
p = i;
}
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = i;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = i')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_12()
{
// Expression body, initializer with declarations
string source = @"
class C : Base
{
C(int p) : base(out var i)
=> p = i;
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'p = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = i')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_13()
{
// No body, initializer with declarations
string source = @"
class C : Base
{
C() : base(out var i)
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,26): error CS1002: ; expected
// C() : base(out var i)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 26),
// (4,5): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// C() : base(out var i)
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsInvalid, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_14()
{
// Block and expression body, initializer with declarations
string source = @"
class C : Base
{
C(int j1, int j2) : base(out var i1, out var i2)
{ i1 = j1; }
=> j2 = i2;
}
class Base
{
protected Base(out int i1, out int i2)
{
i1 = 1;
i2 = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// C(int j1, int j2) : base(out var i1, out var i2)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"C(int j1, int j2) : base(out var i1, out var i2)
{ i1 = j1; }
=> j2 = i2;").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base(out ... out var i2)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i1, out System.Int32 i2)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base(out ... out var i2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsInvalid, IsImplicit) (Syntax: ': base(out ... out var i2)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = j1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = j1')
Left:
ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
Right:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1')
Next (Regular) Block[B3]
Leaving: {R1}
.erroneous body {R2}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j2 = i2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j2 = i2')
Left:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2')
Right:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_15()
{
// Verify "this" initializer with control flow in initializer.
string source = @"
class C
{
C(int? i, int j, int k, int p) : this(i ?? j)
{
p = k;
}
C(int i)
{
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
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: ': this(i ?? j)')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(i ?? j)')
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: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(i ?? j)')
Expression:
IInvocationOperation ( C..ctor(System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(i ?? j)')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: ': this(i ?? j)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i ?? j')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = k;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = k')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
IParameterReferenceOperation: k (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'k')
Next (Regular) Block[B7]
Block[B7] - Exit
Predecessors: [B6]
Statements (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.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests_IConstructorBodyOperation : SemanticModelTestBase
{
[Fact]
public void ConstructorBody_01()
{
string source = @"
class C
{
public C()
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// file.cs(4,15): error CS1002: ; expected
// public C()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15),
// file.cs(4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
Assert.Null(model.GetOperation(node1));
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_02()
{
// No body, initializer without declarations
string source = @"
class C
{
public C() : base()
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,24): error CS1002: ; expected
// public C() : base()
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 24),
// (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C() : base()
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'public C() : base()')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
null
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_03()
{
// Block body, initializer without declarations
string source = @"
class C
{
public C() : base()
{ throw null; }
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... row null; }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_04()
{
// Expression body, initializer without declarations
string source = @"
class C
{
public C() : base()
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... throw null;')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
BlockBody:
null
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsImplicit) (Syntax: ': base()')
Arguments(0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_05()
{
// Block body, no initializer
string source = @"
class C
{
public C()
{ throw null; }
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... row null; }')
Initializer:
null
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ExpressionBody:
null
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_06()
{
// Expression body, no initializer
string source = @"
class C
{
public C()
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'public C() ... throw null;')
Initializer:
null
BlockBody:
null
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_07()
{
// Block and expression body, no initializer
string source = @"
class C
{
public C()
{ throw null; }
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C()
{ throw null; }
=> throw null;").WithLocation(4, 5)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
compilation.VerifyOperationTree(node1, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'public C() ... throw null;')
Initializer:
null
BlockBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ throw null; }')
IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null;')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ExpressionBody:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> throw null')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw null')
Expression:
IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
");
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
.erroneous body {R1}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
}
Block[B3] - Exit [UnReachable]
Predecessors (0)
Statements (0)
");
}
[Fact]
public void ConstructorBody_08()
{
// No body, no initializer
string source = @"
class C
{
public C();
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// file.cs(4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// public C();
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
Assert.Null(model.GetOperation(node1));
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_09()
{
// Block and expression body, initializer without declarations
string source = @"
class C
{
public C(int i1, int i2, int j1, int j2) : base()
{ i1 = i2; }
=> j1 = j2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C(int i1, int i2, int j1, int j2) : base()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C(int i1, int i2, int j1, int j2) : base()
{ i1 = i2; }
=> j1 = j2;").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base()')
Expression:
IInvocationOperation ( System.Object..ctor()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: ': base()')
Arguments(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = i2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = i2')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
Right:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
Next (Regular) Block[B3]
.erroneous body {R1}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j1 = j2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j1 = j2')
Left:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1')
Right:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_10()
{
// Verify block body with a return statement, followed by throw in expression body.
// This caught an assert when attempting to link current basic block which was already linked to exit.
string source = @"
class C
{
public C()
{ return; }
=> throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// public C()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public C()
{ return; }
=> throw null;").WithLocation(4, 5)
);
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
.erroneous body {R1}
{
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
}
Block[B2] - Exit
Predecessors: [B0]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_11()
{
// Block body, initializer with declarations
string source = @"
class C : Base
{
C(int p) : base(out var i)
{
p = i;
}
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = i;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = i')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_12()
{
// Expression body, initializer with declarations
string source = @"
class C : Base
{
C(int p) : base(out var i)
=> p = i;
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'p = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = i')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_13()
{
// No body, initializer with declarations
string source = @"
class C : Base
{
C() : base(out var i)
}
class Base
{
protected Base(out int i)
{
i = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,26): error CS1002: ; expected
// C() : base(out var i)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 26),
// (4,5): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial
// C() : base(out var i)
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base(out var i)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base(out var i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsInvalid, IsImplicit) (Syntax: ': base(out var i)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_14()
{
// Block and expression body, initializer with declarations
string source = @"
class C : Base
{
C(int j1, int j2) : base(out var i1, out var i2)
{ i1 = j1; }
=> j2 = i2;
}
class Base
{
protected Base(out int i1, out int i2)
{
i1 = 1;
i2 = 1;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,5): error CS8057: Block bodies and expression bodies cannot both be provided.
// C(int j1, int j2) : base(out var i1, out var i2)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"C(int j1, int j2) : base(out var i1, out var i2)
{ i1 = j1; }
=> j2 = i2;").WithLocation(4, 5));
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': base(out ... out var i2)')
Expression:
IInvocationOperation ( Base..ctor(out System.Int32 i1, out System.Int32 i2)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': base(out ... out var i2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsInvalid, IsImplicit) (Syntax: ': base(out ... out var i2)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i1 = j1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i1 = j1')
Left:
ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i1')
Right:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j1')
Next (Regular) Block[B3]
Leaving: {R1}
.erroneous body {R2}
{
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j2 = i2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j2 = i2')
Left:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j2')
Right:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'i2')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
");
}
[CompilerTrait(CompilerFeature.Dataflow)]
[Fact]
public void ConstructorBody_15()
{
// Verify "this" initializer with control flow in initializer.
string source = @"
class C
{
C(int? i, int j, int k, int p) : this(i ?? j)
{
p = k;
}
C(int i)
{
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node1 = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
VerifyFlowGraph(compilation, node1, expectedFlowGraph:
@"
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: ': this(i ?? j)')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(i ?? j)')
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: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(i ?? j)')
Expression:
IInvocationOperation ( C..ctor(System.Int32 i)) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(i ?? j)')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: ': this(i ?? j)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i ?? j')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = k;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = k')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
Right:
IParameterReferenceOperation: k (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'k')
Next (Regular) Block[B7]
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
");
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/VisualBasic/Portable/Symbols/HandledEvent.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' represents a single item in Handles list.
''' </summary>
Public NotInheritable Class HandledEvent
Friend Sub New(kind As HandledEventKind,
eventSymbol As EventSymbol,
withEventsContainerOpt As PropertySymbol,
withEventsSourcePropertyOpt As PropertySymbol,
delegateCreation As BoundExpression,
hookupMethod As MethodSymbol)
Me._kind = kind
Debug.Assert(eventSymbol IsNot Nothing)
Me._eventSymbol = eventSymbol
Debug.Assert((withEventsContainerOpt Is Nothing) Or kind = HandledEventKind.WithEvents)
Me._WithEventsContainerOpt = withEventsContainerOpt
Me._WithEventsSourcePropertyOpt = withEventsSourcePropertyOpt
Me.delegateCreation = delegateCreation
Me.hookupMethod = hookupMethod
End Sub
' kind of Handles
Private ReadOnly _kind As HandledEventKind
' E1 in "Handles obj.E1"
Private ReadOnly _eventSymbol As EventSymbol
' obj in "Handles obj.E1"
' only makes sense when kind is WithEvents.
Private ReadOnly _WithEventsContainerOpt As PropertySymbol
' P1 in "Handles obj.P1.E1"
' only makes sense when kind is WithEvents.
Private ReadOnly _WithEventsSourcePropertyOpt As PropertySymbol
''' <summary>
''' Kind of Handles event container. (Me, MyBase, MyClass or a WithEvents variable)
''' </summary>
Public ReadOnly Property HandlesKind As HandledEventKind
Get
Return _kind
End Get
End Property
''' <summary>
''' Symbol for the event handled in current Handles item.
''' </summary>
Public ReadOnly Property EventSymbol As IEventSymbol
Get
Return _eventSymbol
End Get
End Property
Public ReadOnly Property EventContainer As IPropertySymbol
Get
Return _WithEventsContainerOpt
End Get
End Property
Public ReadOnly Property WithEventsSourceProperty As IPropertySymbol
Get
Return _WithEventsSourcePropertyOpt
End Get
End Property
' delegate creation expression used to hook/unhook handlers
' note that it may contain relaxation lambdas and will need to be injected
' into the host method before lowering.
' Used in rewriter.
Friend ReadOnly delegateCreation As BoundExpression
' this is the host method into which hookups will be injected
' Used in rewriter.
Friend ReadOnly hookupMethod As MethodSymbol
End Class
''' <summary>
''' Kind of a Handles item represented by a HandledEvent
''' </summary>
Public Enum HandledEventKind
''' <summary>
''' Handles Me.Event1
''' </summary>
[Me] = 0
''' <summary>
''' Handles MyClass.Event1
''' </summary>
[MyClass] = 1
''' <summary>
''' Handles MyBase.Event1
''' </summary>
[MyBase] = 2
''' <summary>
''' Handles SomeWithEventsVariable.Event1
''' </summary>
[WithEvents] = 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.Generic
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' represents a single item in Handles list.
''' </summary>
Public NotInheritable Class HandledEvent
Friend Sub New(kind As HandledEventKind,
eventSymbol As EventSymbol,
withEventsContainerOpt As PropertySymbol,
withEventsSourcePropertyOpt As PropertySymbol,
delegateCreation As BoundExpression,
hookupMethod As MethodSymbol)
Me._kind = kind
Debug.Assert(eventSymbol IsNot Nothing)
Me._eventSymbol = eventSymbol
Debug.Assert((withEventsContainerOpt Is Nothing) Or kind = HandledEventKind.WithEvents)
Me._WithEventsContainerOpt = withEventsContainerOpt
Me._WithEventsSourcePropertyOpt = withEventsSourcePropertyOpt
Me.delegateCreation = delegateCreation
Me.hookupMethod = hookupMethod
End Sub
' kind of Handles
Private ReadOnly _kind As HandledEventKind
' E1 in "Handles obj.E1"
Private ReadOnly _eventSymbol As EventSymbol
' obj in "Handles obj.E1"
' only makes sense when kind is WithEvents.
Private ReadOnly _WithEventsContainerOpt As PropertySymbol
' P1 in "Handles obj.P1.E1"
' only makes sense when kind is WithEvents.
Private ReadOnly _WithEventsSourcePropertyOpt As PropertySymbol
''' <summary>
''' Kind of Handles event container. (Me, MyBase, MyClass or a WithEvents variable)
''' </summary>
Public ReadOnly Property HandlesKind As HandledEventKind
Get
Return _kind
End Get
End Property
''' <summary>
''' Symbol for the event handled in current Handles item.
''' </summary>
Public ReadOnly Property EventSymbol As IEventSymbol
Get
Return _eventSymbol
End Get
End Property
Public ReadOnly Property EventContainer As IPropertySymbol
Get
Return _WithEventsContainerOpt
End Get
End Property
Public ReadOnly Property WithEventsSourceProperty As IPropertySymbol
Get
Return _WithEventsSourcePropertyOpt
End Get
End Property
' delegate creation expression used to hook/unhook handlers
' note that it may contain relaxation lambdas and will need to be injected
' into the host method before lowering.
' Used in rewriter.
Friend ReadOnly delegateCreation As BoundExpression
' this is the host method into which hookups will be injected
' Used in rewriter.
Friend ReadOnly hookupMethod As MethodSymbol
End Class
''' <summary>
''' Kind of a Handles item represented by a HandledEvent
''' </summary>
Public Enum HandledEventKind
''' <summary>
''' Handles Me.Event1
''' </summary>
[Me] = 0
''' <summary>
''' Handles MyClass.Event1
''' </summary>
[MyClass] = 1
''' <summary>
''' Handles MyBase.Event1
''' </summary>
[MyBase] = 2
''' <summary>
''' Handles SomeWithEventsVariable.Event1
''' </summary>
[WithEvents] = 3
End Enum
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/Portable/SourceFileResolver.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.IO;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Resolves references to source files specified in source code.
/// </summary>
public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver>
{
public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null);
private readonly string? _baseDirectory;
private readonly ImmutableArray<string> _searchPaths;
private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap;
public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory)
: this(searchPaths.AsImmutableOrNull(), baseDirectory)
{
}
public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory)
: this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty)
{
}
public SourceFileResolver(
ImmutableArray<string> searchPaths,
string? baseDirectory,
ImmutableArray<KeyValuePair<string, string>> pathMap)
{
if (searchPaths.IsDefault)
{
throw new ArgumentNullException(nameof(searchPaths));
}
if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute)
{
throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory));
}
_baseDirectory = baseDirectory;
_searchPaths = searchPaths;
// The previous public API required paths to not end with a path separator.
// This broke handling of root paths (e.g. "/" cannot be represented), so
// the new requirement is for paths to always end with a path separator.
// However, because this is a public API, both conventions must be allowed,
// so normalize the paths here (instead of enforcing end-with-sep).
if (!pathMap.IsDefaultOrEmpty)
{
var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length);
foreach (var (key, value) in pathMap)
{
if (key == null || key.Length == 0)
{
throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap));
}
if (value == null)
{
throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap));
}
var normalizedKey = PathUtilities.EnsureTrailingSeparator(key);
var normalizedValue = PathUtilities.EnsureTrailingSeparator(value);
pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue));
}
_pathMap = pathMapBuilder.ToImmutableAndFree();
}
else
{
_pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty;
}
}
public string? BaseDirectory => _baseDirectory;
public ImmutableArray<string> SearchPaths => _searchPaths;
public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap;
public override string? NormalizePath(string path, string? baseFilePath)
{
string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory);
return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap);
}
public override string? ResolveReference(string path, string? baseFilePath)
{
string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists);
if (resolvedPath == null)
{
return null;
}
return FileUtilities.TryNormalizeAbsolutePath(resolvedPath);
}
public override Stream OpenRead(string resolvedPath)
{
CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath));
return FileUtilities.OpenRead(resolvedPath);
}
protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath)
{
return File.Exists(resolvedPath);
}
public override bool Equals(object? obj)
{
// Explicitly check that we're not comparing against a derived type
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals((SourceFileResolver)obj);
}
public bool Equals(SourceFileResolver? other)
{
if (other is null)
{
return false;
}
return
string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) &&
_searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) &&
_pathMap.SequenceEqual(other._pathMap);
}
public override int GetHashCode()
{
return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0,
Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal),
Hash.CombineValues(_pathMap)));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.IO;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Resolves references to source files specified in source code.
/// </summary>
public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver>
{
public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null);
private readonly string? _baseDirectory;
private readonly ImmutableArray<string> _searchPaths;
private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap;
public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory)
: this(searchPaths.AsImmutableOrNull(), baseDirectory)
{
}
public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory)
: this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty)
{
}
public SourceFileResolver(
ImmutableArray<string> searchPaths,
string? baseDirectory,
ImmutableArray<KeyValuePair<string, string>> pathMap)
{
if (searchPaths.IsDefault)
{
throw new ArgumentNullException(nameof(searchPaths));
}
if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute)
{
throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory));
}
_baseDirectory = baseDirectory;
_searchPaths = searchPaths;
// The previous public API required paths to not end with a path separator.
// This broke handling of root paths (e.g. "/" cannot be represented), so
// the new requirement is for paths to always end with a path separator.
// However, because this is a public API, both conventions must be allowed,
// so normalize the paths here (instead of enforcing end-with-sep).
if (!pathMap.IsDefaultOrEmpty)
{
var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length);
foreach (var (key, value) in pathMap)
{
if (key == null || key.Length == 0)
{
throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap));
}
if (value == null)
{
throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap));
}
var normalizedKey = PathUtilities.EnsureTrailingSeparator(key);
var normalizedValue = PathUtilities.EnsureTrailingSeparator(value);
pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue));
}
_pathMap = pathMapBuilder.ToImmutableAndFree();
}
else
{
_pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty;
}
}
public string? BaseDirectory => _baseDirectory;
public ImmutableArray<string> SearchPaths => _searchPaths;
public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap;
public override string? NormalizePath(string path, string? baseFilePath)
{
string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory);
return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap);
}
public override string? ResolveReference(string path, string? baseFilePath)
{
string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists);
if (resolvedPath == null)
{
return null;
}
return FileUtilities.TryNormalizeAbsolutePath(resolvedPath);
}
public override Stream OpenRead(string resolvedPath)
{
CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath));
return FileUtilities.OpenRead(resolvedPath);
}
protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath)
{
return File.Exists(resolvedPath);
}
public override bool Equals(object? obj)
{
// Explicitly check that we're not comparing against a derived type
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals((SourceFileResolver)obj);
}
public bool Equals(SourceFileResolver? other)
{
if (other is null)
{
return false;
}
return
string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) &&
_searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) &&
_pathMap.SequenceEqual(other._pathMap);
}
public override int GetHashCode()
{
return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0,
Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal),
Hash.CombineValues(_pathMap)));
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionIdOptions.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.Concurrent;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal static class FunctionIdOptions
{
private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options =
new();
private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption;
private static Option2<bool> CreateOption(FunctionId id)
{
var name = Enum.GetName(typeof(FunctionId), id) ?? throw ExceptionUtilities.UnexpectedValue(id);
return new Option2<bool>(nameof(FunctionIdOptions), name, defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name));
}
public static Option2<bool> GetOption(FunctionId id)
=> s_options.GetOrAdd(id, s_optionCreator);
}
}
| // Licensed to the .NET Foundation under one or more 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.Concurrent;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal static class FunctionIdOptions
{
private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options =
new();
private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption;
private static Option2<bool> CreateOption(FunctionId id)
{
var name = Enum.GetName(typeof(FunctionId), id) ?? throw ExceptionUtilities.UnexpectedValue(id);
return new Option2<bool>(nameof(FunctionIdOptions), name, defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name));
}
public static Option2<bool> GetOption(FunctionId id)
=> s_options.GetOrAdd(id, s_optionCreator);
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/EditorConfigSeverityStrings.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.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
internal static class EditorConfigSeverityStrings
{
public const string None = "none";
public const string Refactoring = "refactoring";
public const string Silent = "silent";
public const string Suggestion = "suggestion";
public const string Warning = "warning";
public const string Error = "error";
public static bool TryParse(string editorconfigSeverityString, out ReportDiagnostic reportDiagnostic)
{
switch (editorconfigSeverityString)
{
case None:
reportDiagnostic = ReportDiagnostic.Suppress;
return true;
case Refactoring:
case Silent:
reportDiagnostic = ReportDiagnostic.Hidden;
return true;
case Suggestion:
reportDiagnostic = ReportDiagnostic.Info;
return true;
case Warning:
reportDiagnostic = ReportDiagnostic.Warn;
return true;
case Error:
reportDiagnostic = ReportDiagnostic.Error;
return true;
default:
reportDiagnostic = default;
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.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
internal static class EditorConfigSeverityStrings
{
public const string None = "none";
public const string Refactoring = "refactoring";
public const string Silent = "silent";
public const string Suggestion = "suggestion";
public const string Warning = "warning";
public const string Error = "error";
public static bool TryParse(string editorconfigSeverityString, out ReportDiagnostic reportDiagnostic)
{
switch (editorconfigSeverityString)
{
case None:
reportDiagnostic = ReportDiagnostic.Suppress;
return true;
case Refactoring:
case Silent:
reportDiagnostic = ReportDiagnostic.Hidden;
return true;
case Suggestion:
reportDiagnostic = ReportDiagnostic.Info;
return true;
case Warning:
reportDiagnostic = ReportDiagnostic.Warn;
return true;
case Error:
reportDiagnostic = ReportDiagnostic.Error;
return true;
default:
reportDiagnostic = default;
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/VisualBasicTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.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.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.ArgumentProviders
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Class DefaultArgumentProviderTests
Inherits AbstractVisualBasicArgumentProviderTests
Friend Overrides Function GetArgumentProviderType() As Type
Return GetType(DefaultArgumentProvider)
End Function
<Theory>
<InlineData("String")>
<InlineData("Integer?")>
Public Async Function TestDefaultValueIsNothing(type As String) As Task
Dim markup = $"
Class C
Sub Method()
Me.Target($$)
End Sub
Sub Target(arg As {type})
End Sub
End Class
"
Await VerifyDefaultValueAsync(markup, "Nothing")
Await VerifyDefaultValueAsync(markup, expectedDefaultValue:="prior", previousDefaultValue:="prior")
End Function
<Theory>
<InlineData("Boolean", "False")>
<InlineData("System.Boolean", "False")>
<InlineData("Single", "0.0F")>
<InlineData("System.Single", "0.0F")>
<InlineData("Double", "0.0")>
<InlineData("System.Double", "0.0")>
<InlineData("Decimal", "0.0D")>
<InlineData("System.Decimal", "0.0D")>
<InlineData("Char", "Chr(0)")>
<InlineData("System.Char", "Chr(0)")>
<InlineData("Byte", "CByte(0)")>
<InlineData("System.Byte", "CByte(0)")>
<InlineData("SByte", "CSByte(0)")>
<InlineData("System.SByte", "CSByte(0)")>
<InlineData("Short", "0S")>
<InlineData("System.Int16", "0S")>
<InlineData("UShort", "0US")>
<InlineData("System.UInt16", "0US")>
<InlineData("Integer", "0")>
<InlineData("System.Int32", "0")>
<InlineData("UInteger", "0U")>
<InlineData("System.UInt32", "0U")>
<InlineData("Long", "0L")>
<InlineData("System.Int64", "0L")>
<InlineData("ULong", "0UL")>
<InlineData("System.UInt64", "0UL")>
Public Async Function TestDefaultValueIsZero(type As String, literalZero As String) As Task
Dim markup = $"
Class C
Sub Method()
Me.Target($$)
End Sub
Sub Target(arg As {type})
End Sub
End Class
"
Await VerifyDefaultValueAsync(markup, literalZero)
Await VerifyDefaultValueAsync(markup, expectedDefaultValue:="prior", previousDefaultValue:="prior")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.ArgumentProviders
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Class DefaultArgumentProviderTests
Inherits AbstractVisualBasicArgumentProviderTests
Friend Overrides Function GetArgumentProviderType() As Type
Return GetType(DefaultArgumentProvider)
End Function
<Theory>
<InlineData("String")>
<InlineData("Integer?")>
Public Async Function TestDefaultValueIsNothing(type As String) As Task
Dim markup = $"
Class C
Sub Method()
Me.Target($$)
End Sub
Sub Target(arg As {type})
End Sub
End Class
"
Await VerifyDefaultValueAsync(markup, "Nothing")
Await VerifyDefaultValueAsync(markup, expectedDefaultValue:="prior", previousDefaultValue:="prior")
End Function
<Theory>
<InlineData("Boolean", "False")>
<InlineData("System.Boolean", "False")>
<InlineData("Single", "0.0F")>
<InlineData("System.Single", "0.0F")>
<InlineData("Double", "0.0")>
<InlineData("System.Double", "0.0")>
<InlineData("Decimal", "0.0D")>
<InlineData("System.Decimal", "0.0D")>
<InlineData("Char", "Chr(0)")>
<InlineData("System.Char", "Chr(0)")>
<InlineData("Byte", "CByte(0)")>
<InlineData("System.Byte", "CByte(0)")>
<InlineData("SByte", "CSByte(0)")>
<InlineData("System.SByte", "CSByte(0)")>
<InlineData("Short", "0S")>
<InlineData("System.Int16", "0S")>
<InlineData("UShort", "0US")>
<InlineData("System.UInt16", "0US")>
<InlineData("Integer", "0")>
<InlineData("System.Int32", "0")>
<InlineData("UInteger", "0U")>
<InlineData("System.UInt32", "0U")>
<InlineData("Long", "0L")>
<InlineData("System.Int64", "0L")>
<InlineData("ULong", "0UL")>
<InlineData("System.UInt64", "0UL")>
Public Async Function TestDefaultValueIsZero(type As String, literalZero As String) As Task
Dim markup = $"
Class C
Sub Method()
Me.Target($$)
End Sub
Sub Target(arg As {type})
End Sub
End Class
"
Await VerifyDefaultValueAsync(markup, literalZero)
Await VerifyDefaultValueAsync(markup, expectedDefaultValue:="prior", previousDefaultValue:="prior")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InstantiatingGenerics.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.CompilerServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Friend Module InstantiatingGenericsExtensions
' Check generic instantiation invariants.
<Extension()>
Public Sub VerifyGenericInstantiationInvariants(instantiation As Symbol)
If instantiation.IsDefinition Then
Return
End If
Dim originalDefinition As Symbol = instantiation.OriginalDefinition
Dim constructedFrom As Symbol
Dim constructedFromConstructedFrom As Symbol
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim typeArguments As ImmutableArray(Of TypeSymbol)
Dim constructedFromTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim constructedFromTypeArguments As ImmutableArray(Of TypeSymbol)
Dim originalDefinitionTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim type = TryCast(instantiation, NamedTypeSymbol)
Dim method As MethodSymbol = Nothing
If type IsNot Nothing Then
typeParameters = type.TypeParameters
typeArguments = type.TypeArguments
constructedFrom = type.ConstructedFrom
constructedFromTypeParameters = type.ConstructedFrom.TypeParameters
constructedFromTypeArguments = type.ConstructedFrom.TypeArguments
originalDefinitionTypeParameters = type.OriginalDefinition.TypeParameters
constructedFromConstructedFrom = type.ConstructedFrom.ConstructedFrom
Else
method = DirectCast(instantiation, MethodSymbol)
typeParameters = method.TypeParameters
typeArguments = method.TypeArguments
constructedFrom = method.ConstructedFrom
constructedFromTypeParameters = method.ConstructedFrom.TypeParameters
constructedFromTypeArguments = method.ConstructedFrom.TypeArguments
originalDefinitionTypeParameters = method.OriginalDefinition.TypeParameters
constructedFromConstructedFrom = method.ConstructedFrom.ConstructedFrom
End If
Assert.Equal(instantiation.DeclaringCompilation, originalDefinition.DeclaringCompilation)
Assert.True(originalDefinition.IsDefinition)
' Check ConstructedFrom invariants.
Assert.Same(originalDefinition, constructedFrom.OriginalDefinition)
Assert.Same(constructedFrom, constructedFromConstructedFrom)
Assert.Same(instantiation.ContainingSymbol, constructedFrom.ContainingSymbol)
Assert.True(constructedFromTypeArguments.SequenceEqual(constructedFromTypeParameters, ReferenceEqualityComparer.Instance))
Assert.Equal(constructedFrom.Name, originalDefinition.Name)
Assert.Equal(constructedFrom.Kind, originalDefinition.Kind)
Assert.Equal(constructedFrom.DeclaredAccessibility, originalDefinition.DeclaredAccessibility)
Assert.Equal(constructedFrom.IsShared, originalDefinition.IsShared)
For Each typeParam In constructedFromTypeParameters
Assert.Same(constructedFrom, typeParam.ContainingSymbol)
Next
Dim constructedFromIsDefinition As Boolean = constructedFrom.IsDefinition
For Each typeParam In constructedFromTypeParameters
Assert.Equal(constructedFromIsDefinition, typeParam.IsDefinition)
Assert.Same(originalDefinitionTypeParameters(typeParam.Ordinal), typeParam.OriginalDefinition)
Next
' Check instantiation invariants.
Assert.True(typeParameters.SequenceEqual(constructedFromTypeParameters, ReferenceEqualityComparer.Instance))
Assert.True(instantiation Is constructedFrom OrElse Not typeArguments.SequenceEqual(typeParameters), String.Format("Constructed symbol {0} uses its own type parameters as type arguments", instantiation.ToTestDisplayString()))
Assert.Equal(instantiation Is constructedFrom, typeArguments.SequenceEqual(typeParameters, ReferenceEqualityComparer.Instance))
Assert.Equal(instantiation.Name, constructedFrom.Name)
Assert.Equal(instantiation.Kind, originalDefinition.Kind)
Assert.Equal(instantiation.DeclaredAccessibility, originalDefinition.DeclaredAccessibility)
Assert.Equal(instantiation.IsShared, originalDefinition.IsShared)
' TODO: Check constraints and other TypeParameter's properties.
If type IsNot Nothing Then
Assert.Equal(type.ConstructedFrom.Arity, type.OriginalDefinition.Arity)
Assert.Equal(type.Arity, type.ConstructedFrom.Arity)
Assert.False(type.OriginalDefinition.IsUnboundGenericType)
Assert.True(type.Arity > 0 OrElse type.ConstructedFrom Is type, String.Format("Condition [{0} > 0 OrElse {1} Is {2}] failed.", type.Arity, type.ConstructedFrom.ToTestDisplayString(), type.ToTestDisplayString()))
Assert.True(type Is constructedFrom OrElse Not type.CanConstruct, String.Format("Condition [{0} Is constructedFrom OrElse Not {1}] failed.", type.ToTestDisplayString(), type.CanConstruct))
Assert.True(type.Arity > 0 OrElse Not type.CanConstruct, String.Format("Condition [{0} > 0 OrElse Not {1}] failed.", type.Arity, type.CanConstruct))
Assert.Equal(type.OriginalDefinition.IsAnonymousType, type.ConstructedFrom.IsAnonymousType)
Assert.Equal(type.ConstructedFrom.IsAnonymousType, type.IsAnonymousType)
Assert.Same(type.OriginalDefinition.EnumUnderlyingType, type.ConstructedFrom.EnumUnderlyingType)
Assert.Same(type.ConstructedFrom.EnumUnderlyingType, type.EnumUnderlyingType)
Assert.Equal(type.OriginalDefinition.TypeKind, type.ConstructedFrom.TypeKind)
Assert.Equal(type.ConstructedFrom.TypeKind, type.TypeKind)
Assert.Equal(type.OriginalDefinition.IsMustInherit, type.ConstructedFrom.IsMustInherit)
Assert.Equal(type.ConstructedFrom.IsMustInherit, type.IsMustInherit)
Assert.Equal(type.OriginalDefinition.IsNotInheritable, type.ConstructedFrom.IsNotInheritable)
Assert.Equal(type.ConstructedFrom.IsNotInheritable, type.IsNotInheritable)
Assert.False(type.OriginalDefinition.MightContainExtensionMethods)
Assert.False(type.ConstructedFrom.MightContainExtensionMethods)
Assert.False(type.MightContainExtensionMethods)
' Check UnboundGenericType invariants.
Dim containingType As NamedTypeSymbol = type.ContainingType
If containingType IsNot Nothing Then
containingType.VerifyGenericInstantiationInvariants()
If Not type.IsUnboundGenericType AndAlso containingType.IsUnboundGenericType Then
Assert.False(type.CanConstruct)
Assert.Null(type.BaseType)
Assert.Equal(0, type.Interfaces.Length)
End If
End If
If type.IsUnboundGenericType OrElse (containingType IsNot Nothing AndAlso containingType.IsUnboundGenericType) Then
Assert.Null(type.DefaultPropertyName)
Assert.Null(type.ConstructedFrom.DefaultPropertyName)
Else
Assert.Equal(type.OriginalDefinition.DefaultPropertyName, type.ConstructedFrom.DefaultPropertyName)
Assert.Equal(type.ConstructedFrom.DefaultPropertyName, type.DefaultPropertyName)
End If
If type.IsUnboundGenericType Then
Assert.False(type.CanConstruct)
Assert.Null(type.BaseType)
Assert.Equal(0, type.Interfaces.Length)
If containingType IsNot Nothing Then
Assert.Equal(containingType.IsGenericType, containingType.IsUnboundGenericType)
End If
For Each typeArgument In typeArguments
Assert.Same(UnboundGenericType.UnboundTypeArgument, typeArgument)
Next
ElseIf containingType IsNot Nothing AndAlso Not containingType.IsUnboundGenericType Then
containingType = containingType.ContainingType
While containingType IsNot Nothing
Assert.False(containingType.IsUnboundGenericType)
containingType = containingType.ContainingType
End While
End If
Dim testArgs() As TypeSymbol = GetTestArgs(type.Arity)
If type.CanConstruct Then
Dim constructed = type.Construct(testArgs)
Assert.NotSame(type, constructed)
Assert.Same(type, constructedFrom)
constructed.VerifyGenericInstantiationInvariants()
Assert.Same(type, type.Construct(type.TypeParameters.As(Of TypeSymbol)()))
Else
Assert.Throws(Of InvalidOperationException)(Sub() type.Construct(testArgs))
Assert.Throws(Of InvalidOperationException)(Sub() type.Construct(testArgs.AsImmutableOrNull()))
End If
Else
Assert.True(method Is constructedFrom OrElse Not method.CanConstruct, String.Format("Condition [{0} Is constructedFrom OrElse Not {1}] failed.", method.ToTestDisplayString(), method.CanConstruct))
Assert.True(method.Arity > 0 OrElse Not method.CanConstruct, String.Format("Condition [{0} > 0 OrElse Not {1}] failed.", method.Arity, method.CanConstruct))
Assert.Equal(method.ConstructedFrom.Arity, method.OriginalDefinition.Arity)
Assert.Equal(method.Arity, method.ConstructedFrom.Arity)
Assert.Equal(method.Arity = 0, method.ConstructedFrom Is method)
Assert.Same(method.OriginalDefinition.IsExtensionMethod, method.ConstructedFrom.IsExtensionMethod)
Assert.Same(method.ConstructedFrom.IsExtensionMethod, method.IsExtensionMethod)
Dim testArgs() As TypeSymbol = GetTestArgs(type.Arity)
If method.CanConstruct Then
Dim constructed = method.Construct(testArgs)
Assert.NotSame(method, constructed)
Assert.Same(method, constructedFrom)
constructed.VerifyGenericInstantiationInvariants()
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(method.TypeParameters.As(Of TypeSymbol)()))
Else
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(testArgs))
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(testArgs.AsImmutableOrNull()))
End If
End If
End Sub
Private Function GetTestArgs(arity As Integer) As TypeSymbol()
Dim a(arity - 1) As TypeSymbol
For i = 0 To a.Length - 1
a(i) = ErrorTypeSymbol.UnknownResultType
Next
Return a
End Function
End Module
Public Class InstantiatingGenerics
Inherits BasicTestBase
<Fact, WorkItem(910574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910574")>
Public Sub Test1()
Dim assembly = MetadataTestHelpers.LoadFromBytes(TestResources.General.MDTestLib1)
Dim module0 = assembly.Modules(0)
Dim C1 = module0.GlobalNamespace.GetTypeMembers("C1").Single()
Dim C1_T = C1.TypeParameters(0)
Assert.Equal("C1(Of C1_T)", C1.ToTestDisplayString())
Dim C2 = C1.GetTypeMembers("C2").Single()
Dim C2_T = C2.TypeParameters(0)
Assert.Equal("C1(Of C1_T).C2(Of C2_T)", C2.ToTestDisplayString())
Dim C3 = C1.GetTypeMembers("C3").Single()
Assert.Equal("C1(Of C1_T).C3", C3.ToTestDisplayString())
Dim C4 = C3.GetTypeMembers("C4").Single()
Dim C4_T = C4.TypeParameters(0)
Assert.Equal("C1(Of C1_T).C3.C4(Of C4_T)", C4.ToTestDisplayString())
Dim TC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single()
Dim TC2_T1 = TC2.TypeParameters(0)
Dim TC2_T2 = TC2.TypeParameters(1)
Assert.Equal("TC2(Of TC2_T1, TC2_T2)", TC2.ToTestDisplayString())
Dim C107 = module0.GlobalNamespace.GetTypeMembers("C107").Single()
Dim C108 = C107.GetTypeMembers("C108").Single()
Dim C108_T = C108.TypeParameters(0)
Assert.Equal("C107.C108(Of C108_T)", C108.ToTestDisplayString())
Dim g1 = C1.Construct({TC2_T1})
Assert.Equal("C1(Of TC2_T1)", g1.ToTestDisplayString())
Assert.Equal(C1, g1.ConstructedFrom)
Dim g1_C2 = g1.GetTypeMembers("C2").Single()
Assert.Equal("C1(Of TC2_T1).C2(Of C2_T)", g1_C2.ToTestDisplayString())
Assert.Equal(g1_C2, g1_C2.ConstructedFrom)
Assert.NotEqual(C2.TypeParameters(0), g1_C2.TypeParameters(0))
Assert.Same(C2.TypeParameters(0), g1_C2.TypeParameters(0).OriginalDefinition)
Assert.Same(g1_C2.TypeParameters(0), g1_C2.TypeArguments(0))
Dim g2 = g1_C2.Construct({TC2_T2})
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2.ToTestDisplayString())
Assert.Equal(g1_C2, g2.ConstructedFrom)
Dim g1_C3 = g1.GetTypeMembers("C3").Single()
Assert.Equal("C1(Of TC2_T1).C3", g1_C3.ToTestDisplayString())
Assert.Equal(g1_C3, g1_C3.ConstructedFrom)
Dim g1_C3_C4 = g1_C3.GetTypeMembers("C4").Single()
Assert.Equal("C1(Of TC2_T1).C3.C4(Of C4_T)", g1_C3_C4.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g1_C3_C4.ConstructedFrom)
Dim g4 = g1_C3_C4.Construct({TC2_T2})
Assert.Equal("C1(Of TC2_T1).C3.C4(Of TC2_T2)", g4.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g4.ConstructedFrom)
Dim g108 = C108.Construct({TC2_T1})
Assert.Equal("C107.C108(Of TC2_T1)", g108.ToTestDisplayString())
Assert.Equal(C108, g108.ConstructedFrom)
Dim g_TC2 = TC2.Construct({C107, C108})
Assert.Equal("TC2(Of C107, C107.C108(Of C108_T))", g_TC2.ToTestDisplayString())
Assert.Equal(TC2, g_TC2.ConstructedFrom)
Assert.Equal(TC2, TC2.Construct({TC2_T1, TC2_T2}))
Assert.Null(TypeSubstitution.Create(TC2, {TC2_T1, TC2_T2}, {TC2_T1, TC2_T2}))
Dim s1 = TypeSubstitution.Create(C1, {C1_T}, {TC2_T1})
Dim g1_1 = DirectCast(C1.Construct(s1), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1)", g1_1.ToTestDisplayString())
Assert.Equal(C1, g1_1.ConstructedFrom)
Assert.Equal(g1, g1_1)
Dim s2 = TypeSubstitution.Create(C2, {C1_T, C2_T}, {TC2_T1, TC2_T2})
Dim g2_1 = DirectCast(C2.Construct(s2), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2_1.ToTestDisplayString())
Assert.Equal(g1_C2, g2_1.ConstructedFrom)
Assert.Equal(g2, g2_1)
Dim s2_1 = TypeSubstitution.Create(C2, {C2_T}, {TC2_T2})
Dim s3 = TypeSubstitution.Concat(s2_1.TargetGenericDefinition, s1, s2_1)
Dim g2_2 = DirectCast(C2.Construct(s3), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2_2.ToTestDisplayString())
Assert.Equal(g1_C2, g2_2.ConstructedFrom)
Assert.Equal(g2, g2_2)
Dim g2_3 = DirectCast(C2.Construct(s2_1), NamedTypeSymbol)
Assert.Equal("C1(Of C1_T).C2(Of TC2_T2)", g2_3.ToTestDisplayString())
Assert.Equal(C2, g2_3.ConstructedFrom)
Dim s4 = TypeSubstitution.Create(C4, {C1_T, C4_T}, {TC2_T1, TC2_T2})
Dim g4_1 = DirectCast(C4.Construct(s4), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C3.C4(Of TC2_T2)", g4_1.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g4_1.ConstructedFrom)
Assert.Equal(g4, g4_1)
Dim s108 = TypeSubstitution.Create(C108, {C108_T}, {TC2_T1})
Dim g108_1 = DirectCast(C108.Construct(s108), NamedTypeSymbol)
Assert.Equal("C107.C108(Of TC2_T1)", g108_1.ToTestDisplayString())
Assert.Equal(C108, g108_1.ConstructedFrom)
Assert.Equal(g108, g108_1)
Dim sTC2 = TypeSubstitution.Create(TC2, {TC2_T1, TC2_T2}, {C107, C108})
Dim g_TC2_1 = DirectCast(TC2.Construct(sTC2), NamedTypeSymbol)
Assert.Equal("TC2(Of C107, C107.C108(Of C108_T))", g_TC2_1.ToTestDisplayString())
Assert.Equal(TC2, g_TC2_1.ConstructedFrom)
Assert.Equal(g_TC2, g_TC2_1)
g1.VerifyGenericInstantiationInvariants()
g2.VerifyGenericInstantiationInvariants()
g4.VerifyGenericInstantiationInvariants()
g108.VerifyGenericInstantiationInvariants()
g_TC2.VerifyGenericInstantiationInvariants()
g1_1.VerifyGenericInstantiationInvariants()
g2_2.VerifyGenericInstantiationInvariants()
g_TC2_1.VerifyGenericInstantiationInvariants()
End Sub
<Fact>
Public Sub AlphaRename()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Module Module1
Sub Main()
Dim x1 As New C1(Of Byte, Byte)()
Dim x2 As New C1(Of Byte, Byte).C2(Of Byte, Byte)()
Dim x3 As New C1(Of Byte, Byte).C2(Of Byte, Byte).C3(Of Byte, Byte)()
Dim x4 As New C1(Of Byte, Byte).C2(Of Byte, Byte).C3(Of Byte, Byte).C4(Of Byte)()
Dim x5 As New C1(Of Byte, Byte).C5()
End Sub
End Module
Class C1(Of C1T1, C1T2)
Class C2(Of C2T1, C2T2)
Class C3(Of C3T1, C3T2 As C1T1)
Function F1() As C1T1
Return Nothing
End Function
Function F2() As C2T1
Return Nothing
End Function
Function F3() As C3T1
Return Nothing
End Function
Function F4() As C1T2
Return Nothing
End Function
Function F5() As C2T2
Return Nothing
End Function
Function F6() As C3T2
Return Nothing
End Function
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Dim x As C1(Of Integer, Integer).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)
Class C4(Of C4T1)
End Class
End Class
Public V1 As C1(Of Integer, C2T2).C5
Public V2 As C1(Of C2T1, C2T2).C5
Public V3 As C1(Of Integer, Integer).C5
Public V4 As C2(Of Byte, Byte)
Public V5 As C1(Of C1T2, C1T1).C2(Of C2T1, C2T2)
Public V6 As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1)
Public V7 As C1(Of C1T2, C1T1).C2(Of Byte, Integer)
Public V8 As C2(Of C2T1, C2T2)
Public V9 As C2(Of Byte, C2T2)
Sub Test12(x As C2(Of Integer, Integer))
Dim y As C1(Of C1T1, C1T2).C2(Of Byte, Integer) = x.V9
End Sub
Sub Test11(x As C1(Of Integer, Integer).C2(Of Byte, Byte))
Dim y As C1(Of Integer, Integer).C2(Of Byte, Byte) = x.V8
End Sub
Sub Test6(x As C1(Of C1T2, C1T1).C2(Of C2T1, C2T2))
Dim y As C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) = x.V5
End Sub
Sub Test7(x As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) = x.V6
End Sub
Sub Test8(x As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T1, C1T2).C2(Of Byte, Integer) = x.V7
End Sub
Sub Test9(x As C1(Of Integer, Byte).C2(Of C2T2, C2T1))
Dim y As C1(Of Byte, Integer).C2(Of Byte, Integer) = x.V7
End Sub
Sub Test10(x As C1(Of C1T1, C1T2).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T2, C1T1).C2(Of Byte, Integer) = x.V7
End Sub
End Class
Class C5
End Class
Sub Test1(x As C2(Of C1T1, Integer))
Dim y As C1(Of Integer, Integer).C5 = x.V1
End Sub
Sub Test2(x As C2(Of C1T1, C1T2))
Dim y As C5 = x.V2
End Sub
Sub Test3(x As C2(Of C1T2, C1T1))
Dim y As C1(Of Integer, Integer).C5 = x.V3
End Sub
Sub Test4(x As C1(Of Integer, Integer).C2(Of C1T1, C1T2))
Dim y As C1(Of Integer, Integer).C2(Of Byte, Byte) = x.V4
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim int = compilation.GetSpecialType(SpecialType.System_Int32)
Assert.Throws(Of InvalidOperationException)(Function() int.Construct())
Dim c1 = compilation.GetTypeByMetadataName("C1`2")
Dim c2 = c1.GetTypeMembers("C2").Single()
Dim c3 = c2.GetTypeMembers("C3").Single()
Dim c4 = c3.GetTypeMembers("C4").Single()
Dim c5 = c1.GetTypeMembers("C5").Single()
Dim c3OfIntInt = c3.Construct(int, int)
Dim c2_c3OfIntInt = c3OfIntInt.ContainingType
Dim c1_c2_c3OfIntInt = c2_c3OfIntInt.ContainingType
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of System.Int32, System.Int32)", c3OfIntInt.ToTestDisplayString())
Assert.Same(c1, c1_c2_c3OfIntInt)
Assert.Same(c2, c2_c3OfIntInt)
Assert.Same(c3.TypeParameters(0), c3OfIntInt.TypeParameters(0))
Assert.Same(c3, c3OfIntInt.ConstructedFrom)
Dim substitution As TypeSubstitution
substitution = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_c2_c3 = DirectCast(c3.Construct(substitution), NamedTypeSymbol)
Dim c1OfIntInt_c2 = c1OfIntInt_c2_c3.ContainingType
Dim c1OfIntInt = c1OfIntInt_c2.ContainingType
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)", c1OfIntInt_c2_c3.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2)", c1OfIntInt_c2.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32)", c1OfIntInt.ToTestDisplayString())
Assert.Same(c1.TypeParameters(0), c1OfIntInt.TypeParameters(0))
Assert.Same(int, c1OfIntInt.TypeArguments(0))
Assert.NotSame(c2.TypeParameters(0), c1OfIntInt_c2.TypeParameters(0))
Assert.Same(c1OfIntInt_c2.TypeParameters(0), c1OfIntInt_c2.TypeArguments(0))
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.TypeParameters(0).ContainingSymbol)
Assert.NotSame(c3.TypeParameters(0), c1OfIntInt_c2_c3.TypeParameters(0))
Assert.Same(c1OfIntInt_c2_c3.TypeParameters(0), c1OfIntInt_c2_c3.TypeArguments(0))
Assert.Same(c1OfIntInt_c2_c3, c1OfIntInt_c2_c3.TypeParameters(0).ContainingSymbol)
Dim c1OfIntInt_c2_c3_F1 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F1").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F2 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F2").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F3 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F3").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F4 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F4").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F5 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F5").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F6 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F6").Single(), MethodSymbol)
Assert.Same(c1OfIntInt.TypeArguments(0), c1OfIntInt_c2_c3_F1.ReturnType)
Assert.Same(c1OfIntInt_c2.TypeArguments(0), c1OfIntInt_c2_c3_F2.ReturnType)
Assert.Same(c1OfIntInt_c2_c3.TypeArguments(0), c1OfIntInt_c2_c3_F3.ReturnType)
Assert.Same(c1OfIntInt.TypeArguments(1), c1OfIntInt_c2_c3_F4.ReturnType)
Assert.Same(c1OfIntInt_c2.TypeArguments(1), c1OfIntInt_c2_c3_F5.ReturnType)
Assert.Same(c1OfIntInt_c2_c3.TypeArguments(1), c1OfIntInt_c2_c3_F6.ReturnType)
substitution = TypeSubstitution.Create(c3, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_c2Of_c3Of = DirectCast(c3.Construct(substitution), NamedTypeSymbol)
' We need to distinguish these two things in order to be able to detect constraint violation.
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Assert.NotEqual(c1OfIntInt_c2Of_c3Of.ConstructedFrom, c1OfIntInt_c2Of_c3Of)
Dim c1OfIntInt_c2Of = c1OfIntInt_c2Of_c3Of.ContainingType
Assert.Equal(c1OfIntInt, c1OfIntInt_c2Of.ContainingType)
c1OfIntInt = c1OfIntInt_c2Of.ContainingType
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)", c1OfIntInt_c2Of_c3Of.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2)", c1OfIntInt_c2Of.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32)", c1OfIntInt.ToTestDisplayString())
Assert.Same(c1.TypeParameters(0), c1OfIntInt.TypeParameters(0))
Assert.Same(int, c1OfIntInt.TypeArguments(0))
Assert.NotSame(c2.TypeParameters(0), c1OfIntInt_c2Of.TypeParameters(0))
Assert.NotSame(c1OfIntInt_c2Of.TypeParameters(0), c1OfIntInt_c2Of.TypeArguments(0))
Assert.Same(c1OfIntInt_c2Of.TypeParameters(0).OriginalDefinition, c1OfIntInt_c2Of.TypeArguments(0))
Assert.NotSame(c1OfIntInt_c2Of, c1OfIntInt_c2Of.TypeParameters(0).ContainingSymbol)
Assert.Same(c1OfIntInt_c2Of.ConstructedFrom, c1OfIntInt_c2Of.TypeParameters(0).ContainingSymbol)
Assert.NotSame(c3.TypeParameters(0), c1OfIntInt_c2Of_c3Of.TypeParameters(0))
Assert.NotSame(c1OfIntInt_c2Of_c3Of.TypeParameters(0), c1OfIntInt_c2Of_c3Of.TypeArguments(0))
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeParameters(0).OriginalDefinition, c1OfIntInt_c2Of_c3Of.TypeArguments(0))
Assert.NotSame(c1OfIntInt_c2Of_c3Of, c1OfIntInt_c2Of_c3Of.TypeParameters(0).ContainingSymbol)
Assert.Same(c1OfIntInt_c2Of_c3Of.ConstructedFrom, c1OfIntInt_c2Of_c3Of.TypeParameters(0).ContainingSymbol)
Dim c1OfIntInt_c2Of_c3Of_F1 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F1").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F2 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F2").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F3 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F3").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F4 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F4").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F5 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F5").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F6 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F6").Single(), MethodSymbol)
Assert.Same(c1OfIntInt.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F1.ReturnType)
Assert.Same(c1OfIntInt_c2Of.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F2.ReturnType)
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F3.ReturnType)
Assert.Same(c1OfIntInt.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F4.ReturnType)
Assert.Same(c1OfIntInt_c2Of.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F5.ReturnType)
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F6.ReturnType)
substitution = TypeSubstitution.Create(c2,
{c1.TypeParameters(0), c1.TypeParameters(1), c2.TypeParameters(0), c2.TypeParameters(1)},
{int, int, c2.TypeParameters(0), c2.TypeParameters(1)})
Dim c1OfIntInt_c2Of_c3 = c3.Construct(substitution)
Assert.NotEqual(c1OfIntInt_c2_c3, c1OfIntInt_c2Of_c3)
Dim c1OfIntInt_c2Of_c3OfInt = c1OfIntInt_c2Of_c3.Construct(int, c3.TypeParameters(1))
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of System.Int32, C3T2)", c1OfIntInt_c2Of_c3OfInt.ToTestDisplayString())
Assert.True(c1OfIntInt_c2Of_c3OfInt.TypeArguments(1).IsDefinition)
Assert.False(c1OfIntInt_c2Of_c3OfInt.TypeParameters(1).IsDefinition)
Assert.NotEqual(c1OfIntInt_c2_c3, c1OfIntInt_c2Of_c3OfInt.ConstructedFrom)
Assert.Same(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3OfInt.ConstructedFrom)
Assert.NotEqual(c1OfIntInt_c2Of_c3.TypeParameters(1), c1OfIntInt_c2Of_c3OfInt.TypeArguments(1))
Assert.Same(c1OfIntInt_c2Of_c3.TypeParameters(1).OriginalDefinition, c1OfIntInt_c2Of_c3OfInt.TypeArguments(1))
Assert.Same(c3.TypeParameters(1), c1OfIntInt_c2Of_c3.TypeParameters(1).OriginalDefinition)
Assert.Same(c3.TypeParameters(1).Name, c1OfIntInt_c2Of_c3.TypeParameters(1).Name)
Assert.Equal(c3.TypeParameters(1).HasConstructorConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasConstructorConstraint)
Assert.Equal(c3.TypeParameters(1).HasReferenceTypeConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasReferenceTypeConstraint)
Assert.Equal(c3.TypeParameters(1).HasValueTypeConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasValueTypeConstraint)
Assert.Equal(c3.TypeParameters(1).Ordinal, c1OfIntInt_c2Of_c3.TypeParameters(1).Ordinal)
Assert.Throws(Of InvalidOperationException)(Sub() c1OfIntInt_c2_c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1)))
Dim c1OfIntInt_c2Of_c3Constructed = c1OfIntInt_c2Of_c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1))
Assert.Same(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3Constructed.ConstructedFrom)
Assert.False(c1OfIntInt_c2Of_c3Constructed.CanConstruct)
Assert.False(c1OfIntInt_c2Of_c3Constructed.ContainingType.CanConstruct)
Assert.NotEqual(c1OfIntInt_c2Of_c3Constructed.ContainingType, c1OfIntInt_c2Of_c3Constructed.ContainingType.ConstructedFrom)
' We need to distinguish these two things in order to be able to detect constraint violation.
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Assert.NotEqual(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3Constructed)
Assert.Same(c3, c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1)))
substitution = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_C5_1 = c5.Construct(substitution)
substitution = TypeSubstitution.Create(c5, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_C5_2 = c5.Construct(substitution)
Assert.Equal(c1OfIntInt_C5_1, c1OfIntInt_C5_2)
Assert.Equal(0, c1OfIntInt_C5_1.TypeParameters.Length)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Dim x As C1(Of Integer, Integer).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)
~~~~
</errors>)
Assert.Throws(Of InvalidOperationException)(Sub() c5.Construct(c1))
c3OfIntInt.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2_c3.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3Of.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3OfInt.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3Constructed.VerifyGenericInstantiationInvariants()
c1OfIntInt_C5_1.VerifyGenericInstantiationInvariants()
c1OfIntInt_C5_2.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2.VerifyGenericInstantiationInvariants()
Dim c1OfIntInt_c2_1 = c1OfIntInt.GetTypeMembers("c2").Single()
Assert.Equal(c1OfIntInt_c2, c1OfIntInt_c2_1)
Assert.NotSame(c1OfIntInt_c2, c1OfIntInt_c2_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.Construct(New List(Of TypeSymbol) From {c1OfIntInt_c2.TypeParameters(0), c1OfIntInt_c2.TypeParameters(1)}))
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(0), c1OfIntInt_c2_1.TypeParameters(1)))
Dim alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(1), c1OfIntInt_c2_1.TypeParameters(0))
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2.TypeParameters(1))
Assert.NotSame(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2_1.TypeParameters(1))
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2.TypeParameters(0))
Assert.NotSame(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2_1.TypeParameters(0))
alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(0), c1OfIntInt)
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2.TypeParameters(0))
Assert.NotSame(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2_1.TypeParameters(0))
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt)
alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt, c1OfIntInt_c2_1.TypeParameters(1))
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt)
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2.TypeParameters(1))
Assert.NotSame(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2_1.TypeParameters(1))
End Sub
<Fact>
Public Sub TypeSubstitutionTypeTest()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class C1(Of C1T1, C1T2)
Class C2(Of C2T1, C2T2)
Class C3(Of C3T1, C3T2 As C1T1)
Class C4(Of C4T1)
End Class
End Class
End Class
Class C5
End Class
End Class
</file>
</compilation>)
Dim int = compilation.GetSpecialType(SpecialType.System_Int32)
Dim bte = compilation.GetSpecialType(SpecialType.System_Byte)
Dim chr = compilation.GetSpecialType(SpecialType.System_Char)
Dim c1 = compilation.GetTypeByMetadataName("C1`2")
Dim c2 = c1.GetTypeMembers("C2").Single()
Dim c3 = c2.GetTypeMembers("C3").Single()
Dim c4 = c3.GetTypeMembers("C4").Single()
Dim c5 = c1.GetTypeMembers("C5").Single()
Dim substitution1 As TypeSubstitution
Dim substitution2 As TypeSubstitution
Dim substitution3 As TypeSubstitution
substitution1 = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Assert.Equal("C1(Of C1T1, C1T2) : {C1T1->Integer, C1T2->Integer}", substitution1.ToString())
substitution2 = TypeSubstitution.Create(c4, {c3.TypeParameters(0), c4.TypeParameters(0)}, {bte, chr})
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2).C4(Of C4T1) : {C3T1->Byte}, {C4T1->Char}", substitution2.ToString())
Assert.Same(substitution1, TypeSubstitution.Concat(c1, Nothing, substitution1))
Assert.Same(substitution1, TypeSubstitution.Concat(c1, substitution1, Nothing))
Assert.Null(TypeSubstitution.Concat(c1, Nothing, Nothing))
substitution3 = TypeSubstitution.Concat(c2, substitution1, Nothing)
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) : {C1T1->Integer, C1T2->Integer}, {}", substitution3.ToString())
substitution3 = TypeSubstitution.Concat(c4, substitution1, substitution2)
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2).C4(Of C4T1) : {C1T1->Integer, C1T2->Integer}, {}, {C3T1->Byte}, {C4T1->Char}", substitution3.ToString())
Assert.Null(TypeSubstitution.Create(c4, {c1.TypeParameters(0)}, {c1.TypeParameters(0)}))
End Sub
<Fact>
Public Sub ConstructionWithAlphaRenaming()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Module M
Public G As C1(Of Integer)
End Module
Class C1(Of T)
Class C2(Of U)
Public F As U()
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim moduleM = DirectCast(globalNS.GetMembers("M").First(), NamedTypeSymbol)
Dim fieldG = DirectCast(moduleM.GetMembers("G").First(), FieldSymbol)
Dim typeC1OfInteger = fieldG.Type
Dim typeC2 = DirectCast(typeC1OfInteger.GetMembers("C2").First(), NamedTypeSymbol)
Dim fieldF = DirectCast(typeC2.GetMembers("F").First(), FieldSymbol)
Dim fieldFType = fieldF.Type
Assert.Equal("U()", fieldF.Type.ToTestDisplayString())
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.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Friend Module InstantiatingGenericsExtensions
' Check generic instantiation invariants.
<Extension()>
Public Sub VerifyGenericInstantiationInvariants(instantiation As Symbol)
If instantiation.IsDefinition Then
Return
End If
Dim originalDefinition As Symbol = instantiation.OriginalDefinition
Dim constructedFrom As Symbol
Dim constructedFromConstructedFrom As Symbol
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim typeArguments As ImmutableArray(Of TypeSymbol)
Dim constructedFromTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim constructedFromTypeArguments As ImmutableArray(Of TypeSymbol)
Dim originalDefinitionTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Dim type = TryCast(instantiation, NamedTypeSymbol)
Dim method As MethodSymbol = Nothing
If type IsNot Nothing Then
typeParameters = type.TypeParameters
typeArguments = type.TypeArguments
constructedFrom = type.ConstructedFrom
constructedFromTypeParameters = type.ConstructedFrom.TypeParameters
constructedFromTypeArguments = type.ConstructedFrom.TypeArguments
originalDefinitionTypeParameters = type.OriginalDefinition.TypeParameters
constructedFromConstructedFrom = type.ConstructedFrom.ConstructedFrom
Else
method = DirectCast(instantiation, MethodSymbol)
typeParameters = method.TypeParameters
typeArguments = method.TypeArguments
constructedFrom = method.ConstructedFrom
constructedFromTypeParameters = method.ConstructedFrom.TypeParameters
constructedFromTypeArguments = method.ConstructedFrom.TypeArguments
originalDefinitionTypeParameters = method.OriginalDefinition.TypeParameters
constructedFromConstructedFrom = method.ConstructedFrom.ConstructedFrom
End If
Assert.Equal(instantiation.DeclaringCompilation, originalDefinition.DeclaringCompilation)
Assert.True(originalDefinition.IsDefinition)
' Check ConstructedFrom invariants.
Assert.Same(originalDefinition, constructedFrom.OriginalDefinition)
Assert.Same(constructedFrom, constructedFromConstructedFrom)
Assert.Same(instantiation.ContainingSymbol, constructedFrom.ContainingSymbol)
Assert.True(constructedFromTypeArguments.SequenceEqual(constructedFromTypeParameters, ReferenceEqualityComparer.Instance))
Assert.Equal(constructedFrom.Name, originalDefinition.Name)
Assert.Equal(constructedFrom.Kind, originalDefinition.Kind)
Assert.Equal(constructedFrom.DeclaredAccessibility, originalDefinition.DeclaredAccessibility)
Assert.Equal(constructedFrom.IsShared, originalDefinition.IsShared)
For Each typeParam In constructedFromTypeParameters
Assert.Same(constructedFrom, typeParam.ContainingSymbol)
Next
Dim constructedFromIsDefinition As Boolean = constructedFrom.IsDefinition
For Each typeParam In constructedFromTypeParameters
Assert.Equal(constructedFromIsDefinition, typeParam.IsDefinition)
Assert.Same(originalDefinitionTypeParameters(typeParam.Ordinal), typeParam.OriginalDefinition)
Next
' Check instantiation invariants.
Assert.True(typeParameters.SequenceEqual(constructedFromTypeParameters, ReferenceEqualityComparer.Instance))
Assert.True(instantiation Is constructedFrom OrElse Not typeArguments.SequenceEqual(typeParameters), String.Format("Constructed symbol {0} uses its own type parameters as type arguments", instantiation.ToTestDisplayString()))
Assert.Equal(instantiation Is constructedFrom, typeArguments.SequenceEqual(typeParameters, ReferenceEqualityComparer.Instance))
Assert.Equal(instantiation.Name, constructedFrom.Name)
Assert.Equal(instantiation.Kind, originalDefinition.Kind)
Assert.Equal(instantiation.DeclaredAccessibility, originalDefinition.DeclaredAccessibility)
Assert.Equal(instantiation.IsShared, originalDefinition.IsShared)
' TODO: Check constraints and other TypeParameter's properties.
If type IsNot Nothing Then
Assert.Equal(type.ConstructedFrom.Arity, type.OriginalDefinition.Arity)
Assert.Equal(type.Arity, type.ConstructedFrom.Arity)
Assert.False(type.OriginalDefinition.IsUnboundGenericType)
Assert.True(type.Arity > 0 OrElse type.ConstructedFrom Is type, String.Format("Condition [{0} > 0 OrElse {1} Is {2}] failed.", type.Arity, type.ConstructedFrom.ToTestDisplayString(), type.ToTestDisplayString()))
Assert.True(type Is constructedFrom OrElse Not type.CanConstruct, String.Format("Condition [{0} Is constructedFrom OrElse Not {1}] failed.", type.ToTestDisplayString(), type.CanConstruct))
Assert.True(type.Arity > 0 OrElse Not type.CanConstruct, String.Format("Condition [{0} > 0 OrElse Not {1}] failed.", type.Arity, type.CanConstruct))
Assert.Equal(type.OriginalDefinition.IsAnonymousType, type.ConstructedFrom.IsAnonymousType)
Assert.Equal(type.ConstructedFrom.IsAnonymousType, type.IsAnonymousType)
Assert.Same(type.OriginalDefinition.EnumUnderlyingType, type.ConstructedFrom.EnumUnderlyingType)
Assert.Same(type.ConstructedFrom.EnumUnderlyingType, type.EnumUnderlyingType)
Assert.Equal(type.OriginalDefinition.TypeKind, type.ConstructedFrom.TypeKind)
Assert.Equal(type.ConstructedFrom.TypeKind, type.TypeKind)
Assert.Equal(type.OriginalDefinition.IsMustInherit, type.ConstructedFrom.IsMustInherit)
Assert.Equal(type.ConstructedFrom.IsMustInherit, type.IsMustInherit)
Assert.Equal(type.OriginalDefinition.IsNotInheritable, type.ConstructedFrom.IsNotInheritable)
Assert.Equal(type.ConstructedFrom.IsNotInheritable, type.IsNotInheritable)
Assert.False(type.OriginalDefinition.MightContainExtensionMethods)
Assert.False(type.ConstructedFrom.MightContainExtensionMethods)
Assert.False(type.MightContainExtensionMethods)
' Check UnboundGenericType invariants.
Dim containingType As NamedTypeSymbol = type.ContainingType
If containingType IsNot Nothing Then
containingType.VerifyGenericInstantiationInvariants()
If Not type.IsUnboundGenericType AndAlso containingType.IsUnboundGenericType Then
Assert.False(type.CanConstruct)
Assert.Null(type.BaseType)
Assert.Equal(0, type.Interfaces.Length)
End If
End If
If type.IsUnboundGenericType OrElse (containingType IsNot Nothing AndAlso containingType.IsUnboundGenericType) Then
Assert.Null(type.DefaultPropertyName)
Assert.Null(type.ConstructedFrom.DefaultPropertyName)
Else
Assert.Equal(type.OriginalDefinition.DefaultPropertyName, type.ConstructedFrom.DefaultPropertyName)
Assert.Equal(type.ConstructedFrom.DefaultPropertyName, type.DefaultPropertyName)
End If
If type.IsUnboundGenericType Then
Assert.False(type.CanConstruct)
Assert.Null(type.BaseType)
Assert.Equal(0, type.Interfaces.Length)
If containingType IsNot Nothing Then
Assert.Equal(containingType.IsGenericType, containingType.IsUnboundGenericType)
End If
For Each typeArgument In typeArguments
Assert.Same(UnboundGenericType.UnboundTypeArgument, typeArgument)
Next
ElseIf containingType IsNot Nothing AndAlso Not containingType.IsUnboundGenericType Then
containingType = containingType.ContainingType
While containingType IsNot Nothing
Assert.False(containingType.IsUnboundGenericType)
containingType = containingType.ContainingType
End While
End If
Dim testArgs() As TypeSymbol = GetTestArgs(type.Arity)
If type.CanConstruct Then
Dim constructed = type.Construct(testArgs)
Assert.NotSame(type, constructed)
Assert.Same(type, constructedFrom)
constructed.VerifyGenericInstantiationInvariants()
Assert.Same(type, type.Construct(type.TypeParameters.As(Of TypeSymbol)()))
Else
Assert.Throws(Of InvalidOperationException)(Sub() type.Construct(testArgs))
Assert.Throws(Of InvalidOperationException)(Sub() type.Construct(testArgs.AsImmutableOrNull()))
End If
Else
Assert.True(method Is constructedFrom OrElse Not method.CanConstruct, String.Format("Condition [{0} Is constructedFrom OrElse Not {1}] failed.", method.ToTestDisplayString(), method.CanConstruct))
Assert.True(method.Arity > 0 OrElse Not method.CanConstruct, String.Format("Condition [{0} > 0 OrElse Not {1}] failed.", method.Arity, method.CanConstruct))
Assert.Equal(method.ConstructedFrom.Arity, method.OriginalDefinition.Arity)
Assert.Equal(method.Arity, method.ConstructedFrom.Arity)
Assert.Equal(method.Arity = 0, method.ConstructedFrom Is method)
Assert.Same(method.OriginalDefinition.IsExtensionMethod, method.ConstructedFrom.IsExtensionMethod)
Assert.Same(method.ConstructedFrom.IsExtensionMethod, method.IsExtensionMethod)
Dim testArgs() As TypeSymbol = GetTestArgs(type.Arity)
If method.CanConstruct Then
Dim constructed = method.Construct(testArgs)
Assert.NotSame(method, constructed)
Assert.Same(method, constructedFrom)
constructed.VerifyGenericInstantiationInvariants()
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(method.TypeParameters.As(Of TypeSymbol)()))
Else
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(testArgs))
Assert.Throws(Of InvalidOperationException)(Sub() method.Construct(testArgs.AsImmutableOrNull()))
End If
End If
End Sub
Private Function GetTestArgs(arity As Integer) As TypeSymbol()
Dim a(arity - 1) As TypeSymbol
For i = 0 To a.Length - 1
a(i) = ErrorTypeSymbol.UnknownResultType
Next
Return a
End Function
End Module
Public Class InstantiatingGenerics
Inherits BasicTestBase
<Fact, WorkItem(910574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910574")>
Public Sub Test1()
Dim assembly = MetadataTestHelpers.LoadFromBytes(TestResources.General.MDTestLib1)
Dim module0 = assembly.Modules(0)
Dim C1 = module0.GlobalNamespace.GetTypeMembers("C1").Single()
Dim C1_T = C1.TypeParameters(0)
Assert.Equal("C1(Of C1_T)", C1.ToTestDisplayString())
Dim C2 = C1.GetTypeMembers("C2").Single()
Dim C2_T = C2.TypeParameters(0)
Assert.Equal("C1(Of C1_T).C2(Of C2_T)", C2.ToTestDisplayString())
Dim C3 = C1.GetTypeMembers("C3").Single()
Assert.Equal("C1(Of C1_T).C3", C3.ToTestDisplayString())
Dim C4 = C3.GetTypeMembers("C4").Single()
Dim C4_T = C4.TypeParameters(0)
Assert.Equal("C1(Of C1_T).C3.C4(Of C4_T)", C4.ToTestDisplayString())
Dim TC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single()
Dim TC2_T1 = TC2.TypeParameters(0)
Dim TC2_T2 = TC2.TypeParameters(1)
Assert.Equal("TC2(Of TC2_T1, TC2_T2)", TC2.ToTestDisplayString())
Dim C107 = module0.GlobalNamespace.GetTypeMembers("C107").Single()
Dim C108 = C107.GetTypeMembers("C108").Single()
Dim C108_T = C108.TypeParameters(0)
Assert.Equal("C107.C108(Of C108_T)", C108.ToTestDisplayString())
Dim g1 = C1.Construct({TC2_T1})
Assert.Equal("C1(Of TC2_T1)", g1.ToTestDisplayString())
Assert.Equal(C1, g1.ConstructedFrom)
Dim g1_C2 = g1.GetTypeMembers("C2").Single()
Assert.Equal("C1(Of TC2_T1).C2(Of C2_T)", g1_C2.ToTestDisplayString())
Assert.Equal(g1_C2, g1_C2.ConstructedFrom)
Assert.NotEqual(C2.TypeParameters(0), g1_C2.TypeParameters(0))
Assert.Same(C2.TypeParameters(0), g1_C2.TypeParameters(0).OriginalDefinition)
Assert.Same(g1_C2.TypeParameters(0), g1_C2.TypeArguments(0))
Dim g2 = g1_C2.Construct({TC2_T2})
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2.ToTestDisplayString())
Assert.Equal(g1_C2, g2.ConstructedFrom)
Dim g1_C3 = g1.GetTypeMembers("C3").Single()
Assert.Equal("C1(Of TC2_T1).C3", g1_C3.ToTestDisplayString())
Assert.Equal(g1_C3, g1_C3.ConstructedFrom)
Dim g1_C3_C4 = g1_C3.GetTypeMembers("C4").Single()
Assert.Equal("C1(Of TC2_T1).C3.C4(Of C4_T)", g1_C3_C4.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g1_C3_C4.ConstructedFrom)
Dim g4 = g1_C3_C4.Construct({TC2_T2})
Assert.Equal("C1(Of TC2_T1).C3.C4(Of TC2_T2)", g4.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g4.ConstructedFrom)
Dim g108 = C108.Construct({TC2_T1})
Assert.Equal("C107.C108(Of TC2_T1)", g108.ToTestDisplayString())
Assert.Equal(C108, g108.ConstructedFrom)
Dim g_TC2 = TC2.Construct({C107, C108})
Assert.Equal("TC2(Of C107, C107.C108(Of C108_T))", g_TC2.ToTestDisplayString())
Assert.Equal(TC2, g_TC2.ConstructedFrom)
Assert.Equal(TC2, TC2.Construct({TC2_T1, TC2_T2}))
Assert.Null(TypeSubstitution.Create(TC2, {TC2_T1, TC2_T2}, {TC2_T1, TC2_T2}))
Dim s1 = TypeSubstitution.Create(C1, {C1_T}, {TC2_T1})
Dim g1_1 = DirectCast(C1.Construct(s1), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1)", g1_1.ToTestDisplayString())
Assert.Equal(C1, g1_1.ConstructedFrom)
Assert.Equal(g1, g1_1)
Dim s2 = TypeSubstitution.Create(C2, {C1_T, C2_T}, {TC2_T1, TC2_T2})
Dim g2_1 = DirectCast(C2.Construct(s2), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2_1.ToTestDisplayString())
Assert.Equal(g1_C2, g2_1.ConstructedFrom)
Assert.Equal(g2, g2_1)
Dim s2_1 = TypeSubstitution.Create(C2, {C2_T}, {TC2_T2})
Dim s3 = TypeSubstitution.Concat(s2_1.TargetGenericDefinition, s1, s2_1)
Dim g2_2 = DirectCast(C2.Construct(s3), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C2(Of TC2_T2)", g2_2.ToTestDisplayString())
Assert.Equal(g1_C2, g2_2.ConstructedFrom)
Assert.Equal(g2, g2_2)
Dim g2_3 = DirectCast(C2.Construct(s2_1), NamedTypeSymbol)
Assert.Equal("C1(Of C1_T).C2(Of TC2_T2)", g2_3.ToTestDisplayString())
Assert.Equal(C2, g2_3.ConstructedFrom)
Dim s4 = TypeSubstitution.Create(C4, {C1_T, C4_T}, {TC2_T1, TC2_T2})
Dim g4_1 = DirectCast(C4.Construct(s4), NamedTypeSymbol)
Assert.Equal("C1(Of TC2_T1).C3.C4(Of TC2_T2)", g4_1.ToTestDisplayString())
Assert.Equal(g1_C3_C4, g4_1.ConstructedFrom)
Assert.Equal(g4, g4_1)
Dim s108 = TypeSubstitution.Create(C108, {C108_T}, {TC2_T1})
Dim g108_1 = DirectCast(C108.Construct(s108), NamedTypeSymbol)
Assert.Equal("C107.C108(Of TC2_T1)", g108_1.ToTestDisplayString())
Assert.Equal(C108, g108_1.ConstructedFrom)
Assert.Equal(g108, g108_1)
Dim sTC2 = TypeSubstitution.Create(TC2, {TC2_T1, TC2_T2}, {C107, C108})
Dim g_TC2_1 = DirectCast(TC2.Construct(sTC2), NamedTypeSymbol)
Assert.Equal("TC2(Of C107, C107.C108(Of C108_T))", g_TC2_1.ToTestDisplayString())
Assert.Equal(TC2, g_TC2_1.ConstructedFrom)
Assert.Equal(g_TC2, g_TC2_1)
g1.VerifyGenericInstantiationInvariants()
g2.VerifyGenericInstantiationInvariants()
g4.VerifyGenericInstantiationInvariants()
g108.VerifyGenericInstantiationInvariants()
g_TC2.VerifyGenericInstantiationInvariants()
g1_1.VerifyGenericInstantiationInvariants()
g2_2.VerifyGenericInstantiationInvariants()
g_TC2_1.VerifyGenericInstantiationInvariants()
End Sub
<Fact>
Public Sub AlphaRename()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Module Module1
Sub Main()
Dim x1 As New C1(Of Byte, Byte)()
Dim x2 As New C1(Of Byte, Byte).C2(Of Byte, Byte)()
Dim x3 As New C1(Of Byte, Byte).C2(Of Byte, Byte).C3(Of Byte, Byte)()
Dim x4 As New C1(Of Byte, Byte).C2(Of Byte, Byte).C3(Of Byte, Byte).C4(Of Byte)()
Dim x5 As New C1(Of Byte, Byte).C5()
End Sub
End Module
Class C1(Of C1T1, C1T2)
Class C2(Of C2T1, C2T2)
Class C3(Of C3T1, C3T2 As C1T1)
Function F1() As C1T1
Return Nothing
End Function
Function F2() As C2T1
Return Nothing
End Function
Function F3() As C3T1
Return Nothing
End Function
Function F4() As C1T2
Return Nothing
End Function
Function F5() As C2T2
Return Nothing
End Function
Function F6() As C3T2
Return Nothing
End Function
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Dim x As C1(Of Integer, Integer).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)
Class C4(Of C4T1)
End Class
End Class
Public V1 As C1(Of Integer, C2T2).C5
Public V2 As C1(Of C2T1, C2T2).C5
Public V3 As C1(Of Integer, Integer).C5
Public V4 As C2(Of Byte, Byte)
Public V5 As C1(Of C1T2, C1T1).C2(Of C2T1, C2T2)
Public V6 As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1)
Public V7 As C1(Of C1T2, C1T1).C2(Of Byte, Integer)
Public V8 As C2(Of C2T1, C2T2)
Public V9 As C2(Of Byte, C2T2)
Sub Test12(x As C2(Of Integer, Integer))
Dim y As C1(Of C1T1, C1T2).C2(Of Byte, Integer) = x.V9
End Sub
Sub Test11(x As C1(Of Integer, Integer).C2(Of Byte, Byte))
Dim y As C1(Of Integer, Integer).C2(Of Byte, Byte) = x.V8
End Sub
Sub Test6(x As C1(Of C1T2, C1T1).C2(Of C2T1, C2T2))
Dim y As C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) = x.V5
End Sub
Sub Test7(x As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) = x.V6
End Sub
Sub Test8(x As C1(Of C1T2, C1T1).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T1, C1T2).C2(Of Byte, Integer) = x.V7
End Sub
Sub Test9(x As C1(Of Integer, Byte).C2(Of C2T2, C2T1))
Dim y As C1(Of Byte, Integer).C2(Of Byte, Integer) = x.V7
End Sub
Sub Test10(x As C1(Of C1T1, C1T2).C2(Of C2T2, C2T1))
Dim y As C1(Of C1T2, C1T1).C2(Of Byte, Integer) = x.V7
End Sub
End Class
Class C5
End Class
Sub Test1(x As C2(Of C1T1, Integer))
Dim y As C1(Of Integer, Integer).C5 = x.V1
End Sub
Sub Test2(x As C2(Of C1T1, C1T2))
Dim y As C5 = x.V2
End Sub
Sub Test3(x As C2(Of C1T2, C1T1))
Dim y As C1(Of Integer, Integer).C5 = x.V3
End Sub
Sub Test4(x As C1(Of Integer, Integer).C2(Of C1T1, C1T2))
Dim y As C1(Of Integer, Integer).C2(Of Byte, Byte) = x.V4
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim int = compilation.GetSpecialType(SpecialType.System_Int32)
Assert.Throws(Of InvalidOperationException)(Function() int.Construct())
Dim c1 = compilation.GetTypeByMetadataName("C1`2")
Dim c2 = c1.GetTypeMembers("C2").Single()
Dim c3 = c2.GetTypeMembers("C3").Single()
Dim c4 = c3.GetTypeMembers("C4").Single()
Dim c5 = c1.GetTypeMembers("C5").Single()
Dim c3OfIntInt = c3.Construct(int, int)
Dim c2_c3OfIntInt = c3OfIntInt.ContainingType
Dim c1_c2_c3OfIntInt = c2_c3OfIntInt.ContainingType
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of System.Int32, System.Int32)", c3OfIntInt.ToTestDisplayString())
Assert.Same(c1, c1_c2_c3OfIntInt)
Assert.Same(c2, c2_c3OfIntInt)
Assert.Same(c3.TypeParameters(0), c3OfIntInt.TypeParameters(0))
Assert.Same(c3, c3OfIntInt.ConstructedFrom)
Dim substitution As TypeSubstitution
substitution = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_c2_c3 = DirectCast(c3.Construct(substitution), NamedTypeSymbol)
Dim c1OfIntInt_c2 = c1OfIntInt_c2_c3.ContainingType
Dim c1OfIntInt = c1OfIntInt_c2.ContainingType
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)", c1OfIntInt_c2_c3.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2)", c1OfIntInt_c2.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32)", c1OfIntInt.ToTestDisplayString())
Assert.Same(c1.TypeParameters(0), c1OfIntInt.TypeParameters(0))
Assert.Same(int, c1OfIntInt.TypeArguments(0))
Assert.NotSame(c2.TypeParameters(0), c1OfIntInt_c2.TypeParameters(0))
Assert.Same(c1OfIntInt_c2.TypeParameters(0), c1OfIntInt_c2.TypeArguments(0))
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.TypeParameters(0).ContainingSymbol)
Assert.NotSame(c3.TypeParameters(0), c1OfIntInt_c2_c3.TypeParameters(0))
Assert.Same(c1OfIntInt_c2_c3.TypeParameters(0), c1OfIntInt_c2_c3.TypeArguments(0))
Assert.Same(c1OfIntInt_c2_c3, c1OfIntInt_c2_c3.TypeParameters(0).ContainingSymbol)
Dim c1OfIntInt_c2_c3_F1 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F1").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F2 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F2").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F3 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F3").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F4 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F4").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F5 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F5").Single(), MethodSymbol)
Dim c1OfIntInt_c2_c3_F6 = DirectCast(c1OfIntInt_c2_c3.GetMembers("F6").Single(), MethodSymbol)
Assert.Same(c1OfIntInt.TypeArguments(0), c1OfIntInt_c2_c3_F1.ReturnType)
Assert.Same(c1OfIntInt_c2.TypeArguments(0), c1OfIntInt_c2_c3_F2.ReturnType)
Assert.Same(c1OfIntInt_c2_c3.TypeArguments(0), c1OfIntInt_c2_c3_F3.ReturnType)
Assert.Same(c1OfIntInt.TypeArguments(1), c1OfIntInt_c2_c3_F4.ReturnType)
Assert.Same(c1OfIntInt_c2.TypeArguments(1), c1OfIntInt_c2_c3_F5.ReturnType)
Assert.Same(c1OfIntInt_c2_c3.TypeArguments(1), c1OfIntInt_c2_c3_F6.ReturnType)
substitution = TypeSubstitution.Create(c3, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_c2Of_c3Of = DirectCast(c3.Construct(substitution), NamedTypeSymbol)
' We need to distinguish these two things in order to be able to detect constraint violation.
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Assert.NotEqual(c1OfIntInt_c2Of_c3Of.ConstructedFrom, c1OfIntInt_c2Of_c3Of)
Dim c1OfIntInt_c2Of = c1OfIntInt_c2Of_c3Of.ContainingType
Assert.Equal(c1OfIntInt, c1OfIntInt_c2Of.ContainingType)
c1OfIntInt = c1OfIntInt_c2Of.ContainingType
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)", c1OfIntInt_c2Of_c3Of.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2)", c1OfIntInt_c2Of.ToTestDisplayString())
Assert.Equal("C1(Of System.Int32, System.Int32)", c1OfIntInt.ToTestDisplayString())
Assert.Same(c1.TypeParameters(0), c1OfIntInt.TypeParameters(0))
Assert.Same(int, c1OfIntInt.TypeArguments(0))
Assert.NotSame(c2.TypeParameters(0), c1OfIntInt_c2Of.TypeParameters(0))
Assert.NotSame(c1OfIntInt_c2Of.TypeParameters(0), c1OfIntInt_c2Of.TypeArguments(0))
Assert.Same(c1OfIntInt_c2Of.TypeParameters(0).OriginalDefinition, c1OfIntInt_c2Of.TypeArguments(0))
Assert.NotSame(c1OfIntInt_c2Of, c1OfIntInt_c2Of.TypeParameters(0).ContainingSymbol)
Assert.Same(c1OfIntInt_c2Of.ConstructedFrom, c1OfIntInt_c2Of.TypeParameters(0).ContainingSymbol)
Assert.NotSame(c3.TypeParameters(0), c1OfIntInt_c2Of_c3Of.TypeParameters(0))
Assert.NotSame(c1OfIntInt_c2Of_c3Of.TypeParameters(0), c1OfIntInt_c2Of_c3Of.TypeArguments(0))
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeParameters(0).OriginalDefinition, c1OfIntInt_c2Of_c3Of.TypeArguments(0))
Assert.NotSame(c1OfIntInt_c2Of_c3Of, c1OfIntInt_c2Of_c3Of.TypeParameters(0).ContainingSymbol)
Assert.Same(c1OfIntInt_c2Of_c3Of.ConstructedFrom, c1OfIntInt_c2Of_c3Of.TypeParameters(0).ContainingSymbol)
Dim c1OfIntInt_c2Of_c3Of_F1 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F1").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F2 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F2").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F3 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F3").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F4 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F4").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F5 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F5").Single(), MethodSymbol)
Dim c1OfIntInt_c2Of_c3Of_F6 = DirectCast(c1OfIntInt_c2Of_c3Of.GetMembers("F6").Single(), MethodSymbol)
Assert.Same(c1OfIntInt.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F1.ReturnType)
Assert.Same(c1OfIntInt_c2Of.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F2.ReturnType)
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeArguments(0), c1OfIntInt_c2Of_c3Of_F3.ReturnType)
Assert.Same(c1OfIntInt.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F4.ReturnType)
Assert.Same(c1OfIntInt_c2Of.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F5.ReturnType)
Assert.Same(c1OfIntInt_c2Of_c3Of.TypeArguments(1), c1OfIntInt_c2Of_c3Of_F6.ReturnType)
substitution = TypeSubstitution.Create(c2,
{c1.TypeParameters(0), c1.TypeParameters(1), c2.TypeParameters(0), c2.TypeParameters(1)},
{int, int, c2.TypeParameters(0), c2.TypeParameters(1)})
Dim c1OfIntInt_c2Of_c3 = c3.Construct(substitution)
Assert.NotEqual(c1OfIntInt_c2_c3, c1OfIntInt_c2Of_c3)
Dim c1OfIntInt_c2Of_c3OfInt = c1OfIntInt_c2Of_c3.Construct(int, c3.TypeParameters(1))
Assert.Equal("C1(Of System.Int32, System.Int32).C2(Of C2T1, C2T2).C3(Of System.Int32, C3T2)", c1OfIntInt_c2Of_c3OfInt.ToTestDisplayString())
Assert.True(c1OfIntInt_c2Of_c3OfInt.TypeArguments(1).IsDefinition)
Assert.False(c1OfIntInt_c2Of_c3OfInt.TypeParameters(1).IsDefinition)
Assert.NotEqual(c1OfIntInt_c2_c3, c1OfIntInt_c2Of_c3OfInt.ConstructedFrom)
Assert.Same(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3OfInt.ConstructedFrom)
Assert.NotEqual(c1OfIntInt_c2Of_c3.TypeParameters(1), c1OfIntInt_c2Of_c3OfInt.TypeArguments(1))
Assert.Same(c1OfIntInt_c2Of_c3.TypeParameters(1).OriginalDefinition, c1OfIntInt_c2Of_c3OfInt.TypeArguments(1))
Assert.Same(c3.TypeParameters(1), c1OfIntInt_c2Of_c3.TypeParameters(1).OriginalDefinition)
Assert.Same(c3.TypeParameters(1).Name, c1OfIntInt_c2Of_c3.TypeParameters(1).Name)
Assert.Equal(c3.TypeParameters(1).HasConstructorConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasConstructorConstraint)
Assert.Equal(c3.TypeParameters(1).HasReferenceTypeConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasReferenceTypeConstraint)
Assert.Equal(c3.TypeParameters(1).HasValueTypeConstraint, c1OfIntInt_c2Of_c3.TypeParameters(1).HasValueTypeConstraint)
Assert.Equal(c3.TypeParameters(1).Ordinal, c1OfIntInt_c2Of_c3.TypeParameters(1).Ordinal)
Assert.Throws(Of InvalidOperationException)(Sub() c1OfIntInt_c2_c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1)))
Dim c1OfIntInt_c2Of_c3Constructed = c1OfIntInt_c2Of_c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1))
Assert.Same(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3Constructed.ConstructedFrom)
Assert.False(c1OfIntInt_c2Of_c3Constructed.CanConstruct)
Assert.False(c1OfIntInt_c2Of_c3Constructed.ContainingType.CanConstruct)
Assert.NotEqual(c1OfIntInt_c2Of_c3Constructed.ContainingType, c1OfIntInt_c2Of_c3Constructed.ContainingType.ConstructedFrom)
' We need to distinguish these two things in order to be able to detect constraint violation.
' error BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Assert.NotEqual(c1OfIntInt_c2Of_c3, c1OfIntInt_c2Of_c3Constructed)
Assert.Same(c3, c3.Construct(c3.TypeParameters(0), c3.TypeParameters(1)))
substitution = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_C5_1 = c5.Construct(substitution)
substitution = TypeSubstitution.Create(c5, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Dim c1OfIntInt_C5_2 = c5.Construct(substitution)
Assert.Equal(c1OfIntInt_C5_1, c1OfIntInt_C5_2)
Assert.Equal(0, c1OfIntInt_C5_1.TypeParameters.Length)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32044: Type argument 'C3T2' does not inherit from or implement the constraint type 'Integer'.
Dim x As C1(Of Integer, Integer).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2)
~~~~
</errors>)
Assert.Throws(Of InvalidOperationException)(Sub() c5.Construct(c1))
c3OfIntInt.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2_c3.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3Of.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3OfInt.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2Of_c3Constructed.VerifyGenericInstantiationInvariants()
c1OfIntInt_C5_1.VerifyGenericInstantiationInvariants()
c1OfIntInt_C5_2.VerifyGenericInstantiationInvariants()
c1OfIntInt_c2.VerifyGenericInstantiationInvariants()
Dim c1OfIntInt_c2_1 = c1OfIntInt.GetTypeMembers("c2").Single()
Assert.Equal(c1OfIntInt_c2, c1OfIntInt_c2_1)
Assert.NotSame(c1OfIntInt_c2, c1OfIntInt_c2_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.Construct(New List(Of TypeSymbol) From {c1OfIntInt_c2.TypeParameters(0), c1OfIntInt_c2.TypeParameters(1)}))
Assert.Same(c1OfIntInt_c2, c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(0), c1OfIntInt_c2_1.TypeParameters(1)))
Dim alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(1), c1OfIntInt_c2_1.TypeParameters(0))
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2.TypeParameters(1))
Assert.NotSame(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2_1.TypeParameters(1))
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2.TypeParameters(0))
Assert.NotSame(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2_1.TypeParameters(0))
alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt_c2_1.TypeParameters(0), c1OfIntInt)
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2.TypeParameters(0))
Assert.NotSame(alphaConstructedC2.TypeArguments(0), c1OfIntInt_c2_1.TypeParameters(0))
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt)
alphaConstructedC2 = c1OfIntInt_c2.Construct(c1OfIntInt, c1OfIntInt_c2_1.TypeParameters(1))
Assert.Same(c1OfIntInt_c2, alphaConstructedC2.ConstructedFrom)
Assert.Same(alphaConstructedC2.TypeArguments(0), c1OfIntInt)
Assert.Same(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2.TypeParameters(1))
Assert.NotSame(alphaConstructedC2.TypeArguments(1), c1OfIntInt_c2_1.TypeParameters(1))
End Sub
<Fact>
Public Sub TypeSubstitutionTypeTest()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class C1(Of C1T1, C1T2)
Class C2(Of C2T1, C2T2)
Class C3(Of C3T1, C3T2 As C1T1)
Class C4(Of C4T1)
End Class
End Class
End Class
Class C5
End Class
End Class
</file>
</compilation>)
Dim int = compilation.GetSpecialType(SpecialType.System_Int32)
Dim bte = compilation.GetSpecialType(SpecialType.System_Byte)
Dim chr = compilation.GetSpecialType(SpecialType.System_Char)
Dim c1 = compilation.GetTypeByMetadataName("C1`2")
Dim c2 = c1.GetTypeMembers("C2").Single()
Dim c3 = c2.GetTypeMembers("C3").Single()
Dim c4 = c3.GetTypeMembers("C4").Single()
Dim c5 = c1.GetTypeMembers("C5").Single()
Dim substitution1 As TypeSubstitution
Dim substitution2 As TypeSubstitution
Dim substitution3 As TypeSubstitution
substitution1 = TypeSubstitution.Create(c1, {c1.TypeParameters(0), c1.TypeParameters(1)}, {int, int})
Assert.Equal("C1(Of C1T1, C1T2) : {C1T1->Integer, C1T2->Integer}", substitution1.ToString())
substitution2 = TypeSubstitution.Create(c4, {c3.TypeParameters(0), c4.TypeParameters(0)}, {bte, chr})
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2).C4(Of C4T1) : {C3T1->Byte}, {C4T1->Char}", substitution2.ToString())
Assert.Same(substitution1, TypeSubstitution.Concat(c1, Nothing, substitution1))
Assert.Same(substitution1, TypeSubstitution.Concat(c1, substitution1, Nothing))
Assert.Null(TypeSubstitution.Concat(c1, Nothing, Nothing))
substitution3 = TypeSubstitution.Concat(c2, substitution1, Nothing)
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2) : {C1T1->Integer, C1T2->Integer}, {}", substitution3.ToString())
substitution3 = TypeSubstitution.Concat(c4, substitution1, substitution2)
Assert.Equal("C1(Of C1T1, C1T2).C2(Of C2T1, C2T2).C3(Of C3T1, C3T2).C4(Of C4T1) : {C1T1->Integer, C1T2->Integer}, {}, {C3T1->Byte}, {C4T1->Char}", substitution3.ToString())
Assert.Null(TypeSubstitution.Create(c4, {c1.TypeParameters(0)}, {c1.TypeParameters(0)}))
End Sub
<Fact>
Public Sub ConstructionWithAlphaRenaming()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Module M
Public G As C1(Of Integer)
End Module
Class C1(Of T)
Class C2(Of U)
Public F As U()
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim moduleM = DirectCast(globalNS.GetMembers("M").First(), NamedTypeSymbol)
Dim fieldG = DirectCast(moduleM.GetMembers("G").First(), FieldSymbol)
Dim typeC1OfInteger = fieldG.Type
Dim typeC2 = DirectCast(typeC1OfInteger.GetMembers("C2").First(), NamedTypeSymbol)
Dim fieldF = DirectCast(typeC2.GetMembers("F").First(), FieldSymbol)
Dim fieldFType = fieldF.Type
Assert.Equal("U()", fieldF.Type.ToTestDisplayString())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Tools/BuildBoss/Program.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.Linq;
using Mono.Options;
namespace BuildBoss
{
internal static class Program
{
internal static int Main(string[] args)
{
try
{
return MainCore(args) ? 0 : 1;
}
catch (Exception ex)
{
Console.WriteLine($"Unhandled exception: {ex.Message}");
Console.WriteLine(ex.StackTrace);
return 1;
}
}
private static bool MainCore(string[] args)
{
string repositoryDirectory = null;
string configuration = "Debug";
string primarySolution = null;
List<string> solutionFiles;
var options = new OptionSet
{
{ "r|root=", "The repository root", value => repositoryDirectory = value },
{ "c|configuration=", "Build configuration", value => configuration = value },
{ "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value },
};
if (configuration != "Debug" && configuration != "Release")
{
Console.Error.WriteLine($"Invalid configuration: '{configuration}'");
return false;
}
try
{
solutionFiles = options.Parse(args);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
options.WriteOptionDescriptions(Console.Error);
return false;
}
if (string.IsNullOrEmpty(repositoryDirectory))
{
repositoryDirectory = FindRepositoryRoot(
(solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory);
if (repositoryDirectory == null)
{
Console.Error.WriteLine("Unable to find repository root");
return false;
}
}
if (solutionFiles.Count == 0)
{
solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList();
}
return Go(repositoryDirectory, configuration, primarySolution, solutionFiles);
}
private static string FindRepositoryRoot(string startDirectory)
{
string dir = startDirectory;
while (dir != null && !File.Exists(Path.Combine(dir, "global.json")))
{
dir = Path.GetDirectoryName(dir);
}
return dir;
}
private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames)
{
var allGood = true;
foreach (var solutionFileName in solutionFileNames)
{
allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution);
}
var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts");
allGood &= ProcessTargets(repositoryDirectory);
allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration);
allGood &= ProcessStructuredLog(artifactsDirectory, configuration);
allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration);
if (!allGood)
{
Console.WriteLine("Failed");
}
return allGood;
}
private static bool CheckCore(ICheckerUtil util, string title)
{
Console.Write($"Processing {title} ... ");
var textWriter = new StringWriter();
if (util.Check(textWriter))
{
Console.WriteLine("passed");
return true;
}
else
{
Console.WriteLine("FAILED");
Console.WriteLine(textWriter.ToString());
return false;
}
}
private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution)
{
var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution);
return CheckCore(util, $"Solution {solutionFilePath}");
}
private static bool ProcessTargets(string repositoryDirectory)
{
var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets");
var checker = new TargetsCheckerUtil(targetsDirectory);
return CheckCore(checker, $"Targets {targetsDirectory}");
}
private static bool ProcessStructuredLog(string artifactsDirectory, string configuration)
{
var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog");
var util = new StructuredLoggerCheckerUtil(logFilePath);
return CheckCore(util, $"Structured log {logFilePath}");
}
private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration)
{
var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, $"NuPkg and VSIX files");
}
private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration)
{
var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, $"OptProf inputs");
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using Mono.Options;
namespace BuildBoss
{
internal static class Program
{
internal static int Main(string[] args)
{
try
{
return MainCore(args) ? 0 : 1;
}
catch (Exception ex)
{
Console.WriteLine($"Unhandled exception: {ex.Message}");
Console.WriteLine(ex.StackTrace);
return 1;
}
}
private static bool MainCore(string[] args)
{
string repositoryDirectory = null;
string configuration = "Debug";
string primarySolution = null;
List<string> solutionFiles;
var options = new OptionSet
{
{ "r|root=", "The repository root", value => repositoryDirectory = value },
{ "c|configuration=", "Build configuration", value => configuration = value },
{ "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value },
};
if (configuration != "Debug" && configuration != "Release")
{
Console.Error.WriteLine($"Invalid configuration: '{configuration}'");
return false;
}
try
{
solutionFiles = options.Parse(args);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
options.WriteOptionDescriptions(Console.Error);
return false;
}
if (string.IsNullOrEmpty(repositoryDirectory))
{
repositoryDirectory = FindRepositoryRoot(
(solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory);
if (repositoryDirectory == null)
{
Console.Error.WriteLine("Unable to find repository root");
return false;
}
}
if (solutionFiles.Count == 0)
{
solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList();
}
return Go(repositoryDirectory, configuration, primarySolution, solutionFiles);
}
private static string FindRepositoryRoot(string startDirectory)
{
string dir = startDirectory;
while (dir != null && !File.Exists(Path.Combine(dir, "global.json")))
{
dir = Path.GetDirectoryName(dir);
}
return dir;
}
private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames)
{
var allGood = true;
foreach (var solutionFileName in solutionFileNames)
{
allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution);
}
var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts");
allGood &= ProcessTargets(repositoryDirectory);
allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration);
allGood &= ProcessStructuredLog(artifactsDirectory, configuration);
allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration);
if (!allGood)
{
Console.WriteLine("Failed");
}
return allGood;
}
private static bool CheckCore(ICheckerUtil util, string title)
{
Console.Write($"Processing {title} ... ");
var textWriter = new StringWriter();
if (util.Check(textWriter))
{
Console.WriteLine("passed");
return true;
}
else
{
Console.WriteLine("FAILED");
Console.WriteLine(textWriter.ToString());
return false;
}
}
private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution)
{
var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution);
return CheckCore(util, $"Solution {solutionFilePath}");
}
private static bool ProcessTargets(string repositoryDirectory)
{
var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets");
var checker = new TargetsCheckerUtil(targetsDirectory);
return CheckCore(checker, $"Targets {targetsDirectory}");
}
private static bool ProcessStructuredLog(string artifactsDirectory, string configuration)
{
var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog");
var util = new StructuredLoggerCheckerUtil(logFilePath);
return CheckCore(util, $"Structured log {logFilePath}");
}
private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration)
{
var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, $"NuPkg and VSIX files");
}
private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration)
{
var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, $"OptProf inputs");
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Test/Core/Traits/CompilerTraitDiscoverer.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 Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilerTraitDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var array = (CompilerFeature[])traitAttribute.GetConstructorArguments().Single();
foreach (var feature in array)
{
var value = feature.ToString();
yield return new KeyValuePair<string, string>("Compiler", value);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilerTraitDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var array = (CompilerFeature[])traitAttribute.GetConstructorArguments().Single();
foreach (var feature in array)
{
var value = feature.ToString();
yield return new KeyValuePair<string, string>("Compiler", value);
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/CSharpTest2/Recommendations/NamespaceKeywordRecommenderTests.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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class NamespaceKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespaceKeyword()
=> await VerifyAbsenceAsync(@"namespace $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPreviousFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsingInFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
using U;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingInNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N
{
using U;
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"extern alias goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"extern alias goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternInFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
extern alias A;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExternInNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N
{
extern alias A;
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingAlias()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingAlias_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsingAlias()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"global using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsingAlias_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"global using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassDeclaration()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedDelegateDeclaration()
{
await VerifyAbsenceAsync(
@"class C {
delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedMember()
{
await VerifyAbsenceAsync(@"class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespaceKeyword_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
namespace $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_InsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
namespace N1 {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_InsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
namespace N1 {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMember_InsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMember_InsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeExtern()
{
await VerifyAbsenceAsync(@"$$
extern alias Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenUsings()
{
await VerifyAbsenceAsync(
@"using Goo;
$$
using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenGlobalUsings_01()
{
await VerifyAbsenceAsync(
@"global using Goo;
$$
using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenGlobalUsings_02()
{
await VerifyAbsenceAsync(
@"global using Goo;
$$
global using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalAttribute()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"[assembly: Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalAttribute_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"[assembly: Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAttribute()
{
await VerifyAbsenceAsync(
@"[Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedAttribute()
{
await VerifyAbsenceAsync(
@"class C {
[Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRegion()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"#region EDM Relationship Metadata
[assembly: EdmRelationshipAttribute(""PerformanceResultsModel"", ""FK_Runs_Machines"", ""Machines"", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(PerformanceViewerSL.Web.Machine), ""Runs"", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(PerformanceViewerSL.Web.Run), true)]
#endregion
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRegion_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"#region EDM Relationship Metadata
[assembly: EdmRelationshipAttribute(""PerformanceResultsModel"", ""FK_Runs_Machines"", ""Machines"", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(PerformanceViewerSL.Web.Machine), ""Runs"", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(PerformanceViewerSL.Web.Run), true)]
#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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class NamespaceKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespaceKeyword()
=> await VerifyAbsenceAsync(@"namespace $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPreviousFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsingInFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
using U;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingInNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N
{
using U;
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"extern alias goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"extern alias goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterExternInFileScopedNamespace()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"namespace N;
extern alias A;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExternInNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N
{
extern alias A;
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingAlias()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingAlias_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsingAlias()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"global using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsingAlias_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"global using Goo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassDeclaration()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedDelegateDeclaration()
{
await VerifyAbsenceAsync(
@"class C {
delegate void D();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedMember()
{
await VerifyAbsenceAsync(@"class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNamespaceKeyword_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
namespace $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_InsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
namespace N1 {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNamespace_InsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
namespace N1 {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMember_InsideNamespace()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMember_InsideNamespace_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeExtern()
{
await VerifyAbsenceAsync(@"$$
extern alias Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenUsings()
{
await VerifyAbsenceAsync(
@"using Goo;
$$
using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenGlobalUsings_01()
{
await VerifyAbsenceAsync(
@"global using Goo;
$$
using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenGlobalUsings_02()
{
await VerifyAbsenceAsync(
@"global using Goo;
$$
global using Bar;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalAttribute()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"[assembly: Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalAttribute_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"[assembly: Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAttribute()
{
await VerifyAbsenceAsync(
@"[Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedAttribute()
{
await VerifyAbsenceAsync(
@"class C {
[Goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRegion()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"#region EDM Relationship Metadata
[assembly: EdmRelationshipAttribute(""PerformanceResultsModel"", ""FK_Runs_Machines"", ""Machines"", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(PerformanceViewerSL.Web.Machine), ""Runs"", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(PerformanceViewerSL.Web.Run), true)]
#endregion
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRegion_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"#region EDM Relationship Metadata
[assembly: EdmRelationshipAttribute(""PerformanceResultsModel"", ""FK_Runs_Machines"", ""Machines"", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(PerformanceViewerSL.Web.Machine), ""Runs"", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(PerformanceViewerSL.Web.Run), true)]
#endregion
$$");
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/VisualStudio/Core/Def/Implementation/Snippets/IVsExpansionSessionInternal.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;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// This allows us to get pNode as an IntPtr instead of a via a RCW. Otherwise, a second
/// invocation of the same snippet may cause an AccessViolationException.
/// </summary>
[Guid("3DFA7603-3B51-4484-81CD-FF1470123C7C")]
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IVsExpansionSessionInternal
{
void Reserved1();
void Reserved2();
void Reserved3();
void Reserved4();
void Reserved5();
void Reserved6();
void Reserved7();
void Reserved8();
/// <summary>
/// WARNING: Marshal pNode with GetUniqueObjectForIUnknown and call ReleaseComObject on it
/// before leaving the calling method.
/// </summary>
[PreserveSig]
int GetSnippetNode([MarshalAs(UnmanagedType.BStr)] string bstrNode, out IntPtr pNode);
void Reserved9();
void Reserved10();
void Reserved11();
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// This allows us to get pNode as an IntPtr instead of a via a RCW. Otherwise, a second
/// invocation of the same snippet may cause an AccessViolationException.
/// </summary>
[Guid("3DFA7603-3B51-4484-81CD-FF1470123C7C")]
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IVsExpansionSessionInternal
{
void Reserved1();
void Reserved2();
void Reserved3();
void Reserved4();
void Reserved5();
void Reserved6();
void Reserved7();
void Reserved8();
/// <summary>
/// WARNING: Marshal pNode with GetUniqueObjectForIUnknown and call ReleaseComObject on it
/// before leaving the calling method.
/// </summary>
[PreserveSig]
int GetSnippetNode([MarshalAs(UnmanagedType.BStr)] string bstrNode, out IntPtr pNode);
void Reserved9();
void Reserved10();
void Reserved11();
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/Core/Portable/Diagnostics/BuildToolId.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Support ErrorSource information.
/// </summary>
internal abstract class BuildToolId
{
public abstract string BuildTool { get; }
internal abstract class Base<T> : BuildToolId
{
protected readonly T? _Field1;
public Base(T? field)
=> _Field1 = field;
public override bool Equals(object? obj)
{
if (obj is not Base<T> other)
{
return false;
}
return object.Equals(_Field1, other._Field1);
}
public override int GetHashCode()
=> _Field1?.GetHashCode() ?? 0;
}
internal abstract class Base<T1, T2> : Base<T2>
{
private readonly T1? _Field2;
public Base(T1? field1, T2? field2) : base(field2)
=> _Field2 = field1;
public override bool Equals(object? obj)
{
if (obj is not Base<T1, T2> other)
{
return false;
}
return object.Equals(_Field2, other._Field2) && base.Equals(other);
}
public override int GetHashCode()
=> Hash.Combine(_Field2?.GetHashCode() ?? 0, base.GetHashCode());
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Support ErrorSource information.
/// </summary>
internal abstract class BuildToolId
{
public abstract string BuildTool { get; }
internal abstract class Base<T> : BuildToolId
{
protected readonly T? _Field1;
public Base(T? field)
=> _Field1 = field;
public override bool Equals(object? obj)
{
if (obj is not Base<T> other)
{
return false;
}
return object.Equals(_Field1, other._Field1);
}
public override int GetHashCode()
=> _Field1?.GetHashCode() ?? 0;
}
internal abstract class Base<T1, T2> : Base<T2>
{
private readonly T1? _Field2;
public Base(T1? field1, T2? field2) : base(field2)
=> _Field2 = field1;
public override bool Equals(object? obj)
{
if (obj is not Base<T1, T2> other)
{
return false;
}
return object.Equals(_Field2, other._Field2) && base.Equals(other);
}
public override int GetHashCode()
=> Hash.Combine(_Field2?.GetHashCode() ?? 0, base.GetHashCode());
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState_Checksum.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;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class TextDocumentState
{
public bool TryGetStateChecksums([NotNullWhen(returnValue: true)] out DocumentStateChecksums? stateChecksums)
=> _lazyChecksums.TryGetValue(out stateChecksums);
public Task<DocumentStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken)
=> _lazyChecksums.GetValueAsync(cancellationToken);
public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken)
{
return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(
static (lazyChecksums, cancellationToken) => new ValueTask<DocumentStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)),
static (documentStateChecksums, _) => documentStateChecksums.Checksum,
_lazyChecksums,
cancellationToken).AsTask();
}
private async Task<DocumentStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.DocumentState_ComputeChecksumsAsync, FilePath, cancellationToken))
{
var serializer = solutionServices.Workspace.Services.GetRequiredService<ISerializerService>();
var infoChecksum = serializer.CreateChecksum(Attributes, cancellationToken);
var serializableText = await SerializableSourceText.FromTextDocumentStateAsync(this, cancellationToken).ConfigureAwait(false);
var textChecksum = serializer.CreateChecksum(serializableText, cancellationToken);
return new DocumentStateChecksums(infoChecksum, textChecksum);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class TextDocumentState
{
public bool TryGetStateChecksums([NotNullWhen(returnValue: true)] out DocumentStateChecksums? stateChecksums)
=> _lazyChecksums.TryGetValue(out stateChecksums);
public Task<DocumentStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken)
=> _lazyChecksums.GetValueAsync(cancellationToken);
public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken)
{
return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(
static (lazyChecksums, cancellationToken) => new ValueTask<DocumentStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)),
static (documentStateChecksums, _) => documentStateChecksums.Checksum,
_lazyChecksums,
cancellationToken).AsTask();
}
private async Task<DocumentStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.DocumentState_ComputeChecksumsAsync, FilePath, cancellationToken))
{
var serializer = solutionServices.Workspace.Services.GetRequiredService<ISerializerService>();
var infoChecksum = serializer.CreateChecksum(Attributes, cancellationToken);
var serializableText = await SerializableSourceText.FromTextDocumentStateAsync(this, cancellationToken).ConfigureAwait(false);
var textChecksum = serializer.CreateChecksum(serializableText, cancellationToken);
return new DocumentStateChecksums(infoChecksum, textChecksum);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/CSharp/Portable/CodeRefactorings/AddMissingImports/CSharpAddMissingImportsRefactoringProvider.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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.AddMissingImports;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.PasteTracking;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddMissingImports
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddMissingImports), Shared]
internal class CSharpAddMissingImportsRefactoringProvider : AbstractAddMissingImportsRefactoringProvider
{
protected override string CodeActionTitle => CSharpFeaturesResources.Add_missing_usings;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddMissingImportsRefactoringProvider(IPasteTrackingService pasteTrackingService)
: base(pasteTrackingService)
{
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.AddMissingImports;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.PasteTracking;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddMissingImports
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddMissingImports), Shared]
internal class CSharpAddMissingImportsRefactoringProvider : AbstractAddMissingImportsRefactoringProvider
{
protected override string CodeActionTitle => CSharpFeaturesResources.Add_missing_usings;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddMissingImportsRefactoringProvider(IPasteTrackingService pasteTrackingService)
: base(pasteTrackingService)
{
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Test/Core/Assert/TestExceptionUtilities.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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class TestExceptionUtilities
{
public static InvalidOperationException UnexpectedValue(object o)
{
string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "<unknown>");
System.Diagnostics.Debug.Fail(output);
return new InvalidOperationException(output);
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class TestExceptionUtilities
{
public static InvalidOperationException UnexpectedValue(object o)
{
string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "<unknown>");
System.Diagnostics.Debug.Fail(output);
return new InvalidOperationException(output);
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/Custom.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
#pragma warning disable 169 // unused field
#pragma warning disable 649 // field not set, will always be default value
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace ObjectFormatterFixtures
{
internal class Outer
{
public class Nested<T>
{
public readonly int A = 1;
public readonly int B = 2;
public const int S = 3;
}
}
internal class A<T>
{
public class B<S>
{
public class C
{
public class D<Q, R>
{
public class E
{
}
}
}
}
public static readonly B<T> X = new B<T>();
}
internal class Sort
{
public readonly byte ab = 1;
public readonly sbyte aB = -1;
public readonly short Ac = -1;
public readonly ushort Ad = 1;
public readonly int ad = -1;
public readonly uint aE = 1;
public readonly long aF = -1;
public readonly ulong AG = 1;
}
internal class Signatures
{
public static readonly MethodInfo Arrays = typeof(Signatures).GetMethod(nameof(ArrayParameters));
public void ArrayParameters(int[] arrayOne, int[,] arrayTwo, int[,,] arrayThree) { }
}
internal class RecursiveRootHidden
{
public readonly int A;
public readonly int B;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public RecursiveRootHidden C;
}
internal class RecursiveProxy
{
private class Proxy
{
public Proxy() { }
public Proxy(Node node)
{
x = node.value;
y = node.next;
}
public readonly int x;
public readonly Node y;
}
[DebuggerTypeProxy(typeof(Proxy))]
public class Node
{
public Node(int value)
{
if (value < 5)
{
next = new Node(value + 1);
}
this.value = value;
}
public readonly int value;
public readonly Node next;
}
}
internal class InvalidRecursiveProxy
{
private class Proxy
{
public Proxy() { }
public Proxy(Node c) { }
public readonly int x;
public readonly Node p = new Node();
public readonly int y;
}
[DebuggerTypeProxy(typeof(Proxy))]
public class Node
{
public readonly int a;
public readonly int b;
}
}
internal class ComplexProxyBase
{
private int Goo()
{
return 1;
}
}
internal class ComplexProxy : ComplexProxyBase
{
public ComplexProxy()
{
}
public ComplexProxy(object b)
{
}
[DebuggerDisplay("*1")]
public int _02_public_property_dd { get { return 1; } }
[DebuggerDisplay("*2")]
private int _03_private_property_dd { get { return 1; } }
[DebuggerDisplay("*3")]
protected int _04_protected_property_dd { get { return 1; } }
[DebuggerDisplay("*4")]
internal int _05_internal_property_dd { get { return 1; } }
[DebuggerDisplay("+1")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public readonly int _06_public_field_dd_never;
[DebuggerDisplay("+2")]
private readonly int _07_private_field_dd;
[DebuggerDisplay("+3")]
protected readonly int _08_protected_field_dd;
[DebuggerDisplay("+4")]
internal readonly int _09_internal_field_dd;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private readonly int _10_private_collapsed;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private readonly int _10_private_rootHidden;
public readonly int _12_public;
private readonly int _13_private;
protected readonly int _14_protected;
internal readonly int _15_internal;
[DebuggerDisplay("==\r\n=\r\n=")]
public readonly int _16_eolns;
[DebuggerDisplay("=={==")]
public readonly int _17_braces_0;
[DebuggerDisplay("=={{==")]
public readonly int _17_braces_1;
[DebuggerDisplay("=={'{'}==")]
public readonly int _17_braces_2;
[DebuggerDisplay("=={'\\{'}==")]
public readonly int _17_braces_3;
[DebuggerDisplay("=={1/*{*/}==")]
public readonly int _17_braces_4;
[DebuggerDisplay("=={'{'/*\\}*/}==")]
public readonly int _17_braces_5;
[DebuggerDisplay("=={'{'/*}*/}==")]
public readonly int _17_braces_6;
[DebuggerDisplay("==\\{\\x\\t==")]
public readonly int _19_escapes;
[DebuggerDisplay("{1+1}")]
public readonly int _21;
[DebuggerDisplay("{\"xxx\"}")]
public readonly int _22;
[DebuggerDisplay("{\"xxx\",nq}")]
public readonly int _23;
[DebuggerDisplay("{'x'}")]
public readonly int _24;
[DebuggerDisplay("{'x',nq}")]
public readonly int _25;
[DebuggerDisplay("{new B()}")]
public readonly int _26_0;
[DebuggerDisplay("{new D()}")]
public readonly int _26_1;
[DebuggerDisplay("{new E()}")]
public readonly int _26_2;
[DebuggerDisplay("{ReturnVoid()}")]
public readonly int _26_3;
private void ReturnVoid() { }
[DebuggerDisplay("{F1(1)}")]
public readonly int _26_4;
[DebuggerDisplay("{Goo}")]
public readonly int _26_5;
[DebuggerDisplay("{goo}")]
public readonly int _26_6;
private int goo()
{
return 2;
}
private int F1(int a) { return 1; }
private int F2(short a) { return 2; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly C _27_rootHidden = new C();
public readonly C _28 = new C();
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public readonly C _29_collapsed = new C();
public int _31 { get; set; }
[CompilerGenerated]
public readonly int _32;
[CompilerGenerated]
private readonly int _33;
public int _34_Exception { get { throw new Exception("error1"); } }
[DebuggerDisplay("-!-")]
public int _35_Exception { get { throw new Exception("error2"); } }
public readonly object _36 = new ToStringException();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int _37 { get { throw new Exception("error3"); } }
public int _38_private_get_public_set { private get { return 1; } set { } }
public int _39_public_get_private_set { get { return 1; } private set { } }
private int _40_private_get_private_set { get { return 1; } set { } }
private int _41_set_only_property { set { } }
public override string ToString()
{
return "AStr";
}
}
[DebuggerTypeProxy(typeof(ComplexProxy))]
internal class TypeWithComplexProxy
{
public override string ToString()
{
return "BStr";
}
}
[DebuggerTypeProxy(typeof(Proxy))]
[DebuggerDisplay("DD")]
internal class TypeWithDebuggerDisplayAndProxy
{
public override string ToString()
{
return "<ToString>";
}
[DebuggerDisplay("pxy")]
private class Proxy
{
public Proxy(object x)
{
}
public readonly int A;
public readonly int B;
}
}
internal class C
{
public readonly int A = 1;
public readonly int B = 2;
public override string ToString()
{
return "CStr";
}
}
[DebuggerDisplay("DebuggerDisplayValue")]
internal class BaseClassWithDebuggerDisplay
{
}
internal class InheritedDebuggerDisplay : BaseClassWithDebuggerDisplay
{
}
internal class ToStringException
{
public override string ToString()
{
throw new MyException();
}
}
internal class MyException : Exception
{
public override string ToString()
{
return "my exception";
}
}
public class ThrowingDictionary : IDictionary
{
private readonly int _throwAt;
public ThrowingDictionary(int throwAt)
{
_throwAt = throwAt;
}
public void Add(object key, object value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(object key)
{
throw new NotImplementedException();
}
public IDictionaryEnumerator GetEnumerator()
{
return new E(_throwAt);
}
public bool IsFixedSize
{
get { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public ICollection Keys
{
get { return new[] { 1, 2 }; }
}
public void Remove(object key)
{
}
public ICollection Values
{
get { return new[] { 1, 2 }; }
}
public object this[object key]
{
get
{
return 1;
}
set
{
}
}
public void CopyTo(Array array, int index)
{
}
public int Count
{
get { return 10; }
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return new E(-1);
}
private class E : IEnumerator, IDictionaryEnumerator
{
private int _i;
private readonly int _throwAt;
public E(int throwAt)
{
_throwAt = throwAt;
}
public object Current
{
get { return new DictionaryEntry(_i, _i); }
}
public bool MoveNext()
{
_i++;
if (_i == _throwAt)
{
throw new Exception();
}
return _i < 5;
}
public void Reset()
{
}
public DictionaryEntry Entry
{
get { return (DictionaryEntry)Current; }
}
public object Key
{
get { return _i; }
}
public object Value
{
get { return _i; }
}
}
}
public class ListNode
{
public ListNode next;
public object data;
}
public class LongMembers
{
public readonly string LongName0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789 = "hello";
public readonly string LongValue = "0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789";
}
}
| // Licensed to the .NET Foundation under one or more 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
#pragma warning disable 169 // unused field
#pragma warning disable 649 // field not set, will always be default value
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace ObjectFormatterFixtures
{
internal class Outer
{
public class Nested<T>
{
public readonly int A = 1;
public readonly int B = 2;
public const int S = 3;
}
}
internal class A<T>
{
public class B<S>
{
public class C
{
public class D<Q, R>
{
public class E
{
}
}
}
}
public static readonly B<T> X = new B<T>();
}
internal class Sort
{
public readonly byte ab = 1;
public readonly sbyte aB = -1;
public readonly short Ac = -1;
public readonly ushort Ad = 1;
public readonly int ad = -1;
public readonly uint aE = 1;
public readonly long aF = -1;
public readonly ulong AG = 1;
}
internal class Signatures
{
public static readonly MethodInfo Arrays = typeof(Signatures).GetMethod(nameof(ArrayParameters));
public void ArrayParameters(int[] arrayOne, int[,] arrayTwo, int[,,] arrayThree) { }
}
internal class RecursiveRootHidden
{
public readonly int A;
public readonly int B;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public RecursiveRootHidden C;
}
internal class RecursiveProxy
{
private class Proxy
{
public Proxy() { }
public Proxy(Node node)
{
x = node.value;
y = node.next;
}
public readonly int x;
public readonly Node y;
}
[DebuggerTypeProxy(typeof(Proxy))]
public class Node
{
public Node(int value)
{
if (value < 5)
{
next = new Node(value + 1);
}
this.value = value;
}
public readonly int value;
public readonly Node next;
}
}
internal class InvalidRecursiveProxy
{
private class Proxy
{
public Proxy() { }
public Proxy(Node c) { }
public readonly int x;
public readonly Node p = new Node();
public readonly int y;
}
[DebuggerTypeProxy(typeof(Proxy))]
public class Node
{
public readonly int a;
public readonly int b;
}
}
internal class ComplexProxyBase
{
private int Goo()
{
return 1;
}
}
internal class ComplexProxy : ComplexProxyBase
{
public ComplexProxy()
{
}
public ComplexProxy(object b)
{
}
[DebuggerDisplay("*1")]
public int _02_public_property_dd { get { return 1; } }
[DebuggerDisplay("*2")]
private int _03_private_property_dd { get { return 1; } }
[DebuggerDisplay("*3")]
protected int _04_protected_property_dd { get { return 1; } }
[DebuggerDisplay("*4")]
internal int _05_internal_property_dd { get { return 1; } }
[DebuggerDisplay("+1")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public readonly int _06_public_field_dd_never;
[DebuggerDisplay("+2")]
private readonly int _07_private_field_dd;
[DebuggerDisplay("+3")]
protected readonly int _08_protected_field_dd;
[DebuggerDisplay("+4")]
internal readonly int _09_internal_field_dd;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private readonly int _10_private_collapsed;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private readonly int _10_private_rootHidden;
public readonly int _12_public;
private readonly int _13_private;
protected readonly int _14_protected;
internal readonly int _15_internal;
[DebuggerDisplay("==\r\n=\r\n=")]
public readonly int _16_eolns;
[DebuggerDisplay("=={==")]
public readonly int _17_braces_0;
[DebuggerDisplay("=={{==")]
public readonly int _17_braces_1;
[DebuggerDisplay("=={'{'}==")]
public readonly int _17_braces_2;
[DebuggerDisplay("=={'\\{'}==")]
public readonly int _17_braces_3;
[DebuggerDisplay("=={1/*{*/}==")]
public readonly int _17_braces_4;
[DebuggerDisplay("=={'{'/*\\}*/}==")]
public readonly int _17_braces_5;
[DebuggerDisplay("=={'{'/*}*/}==")]
public readonly int _17_braces_6;
[DebuggerDisplay("==\\{\\x\\t==")]
public readonly int _19_escapes;
[DebuggerDisplay("{1+1}")]
public readonly int _21;
[DebuggerDisplay("{\"xxx\"}")]
public readonly int _22;
[DebuggerDisplay("{\"xxx\",nq}")]
public readonly int _23;
[DebuggerDisplay("{'x'}")]
public readonly int _24;
[DebuggerDisplay("{'x',nq}")]
public readonly int _25;
[DebuggerDisplay("{new B()}")]
public readonly int _26_0;
[DebuggerDisplay("{new D()}")]
public readonly int _26_1;
[DebuggerDisplay("{new E()}")]
public readonly int _26_2;
[DebuggerDisplay("{ReturnVoid()}")]
public readonly int _26_3;
private void ReturnVoid() { }
[DebuggerDisplay("{F1(1)}")]
public readonly int _26_4;
[DebuggerDisplay("{Goo}")]
public readonly int _26_5;
[DebuggerDisplay("{goo}")]
public readonly int _26_6;
private int goo()
{
return 2;
}
private int F1(int a) { return 1; }
private int F2(short a) { return 2; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly C _27_rootHidden = new C();
public readonly C _28 = new C();
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
public readonly C _29_collapsed = new C();
public int _31 { get; set; }
[CompilerGenerated]
public readonly int _32;
[CompilerGenerated]
private readonly int _33;
public int _34_Exception { get { throw new Exception("error1"); } }
[DebuggerDisplay("-!-")]
public int _35_Exception { get { throw new Exception("error2"); } }
public readonly object _36 = new ToStringException();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int _37 { get { throw new Exception("error3"); } }
public int _38_private_get_public_set { private get { return 1; } set { } }
public int _39_public_get_private_set { get { return 1; } private set { } }
private int _40_private_get_private_set { get { return 1; } set { } }
private int _41_set_only_property { set { } }
public override string ToString()
{
return "AStr";
}
}
[DebuggerTypeProxy(typeof(ComplexProxy))]
internal class TypeWithComplexProxy
{
public override string ToString()
{
return "BStr";
}
}
[DebuggerTypeProxy(typeof(Proxy))]
[DebuggerDisplay("DD")]
internal class TypeWithDebuggerDisplayAndProxy
{
public override string ToString()
{
return "<ToString>";
}
[DebuggerDisplay("pxy")]
private class Proxy
{
public Proxy(object x)
{
}
public readonly int A;
public readonly int B;
}
}
internal class C
{
public readonly int A = 1;
public readonly int B = 2;
public override string ToString()
{
return "CStr";
}
}
[DebuggerDisplay("DebuggerDisplayValue")]
internal class BaseClassWithDebuggerDisplay
{
}
internal class InheritedDebuggerDisplay : BaseClassWithDebuggerDisplay
{
}
internal class ToStringException
{
public override string ToString()
{
throw new MyException();
}
}
internal class MyException : Exception
{
public override string ToString()
{
return "my exception";
}
}
public class ThrowingDictionary : IDictionary
{
private readonly int _throwAt;
public ThrowingDictionary(int throwAt)
{
_throwAt = throwAt;
}
public void Add(object key, object value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(object key)
{
throw new NotImplementedException();
}
public IDictionaryEnumerator GetEnumerator()
{
return new E(_throwAt);
}
public bool IsFixedSize
{
get { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public ICollection Keys
{
get { return new[] { 1, 2 }; }
}
public void Remove(object key)
{
}
public ICollection Values
{
get { return new[] { 1, 2 }; }
}
public object this[object key]
{
get
{
return 1;
}
set
{
}
}
public void CopyTo(Array array, int index)
{
}
public int Count
{
get { return 10; }
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return new E(-1);
}
private class E : IEnumerator, IDictionaryEnumerator
{
private int _i;
private readonly int _throwAt;
public E(int throwAt)
{
_throwAt = throwAt;
}
public object Current
{
get { return new DictionaryEntry(_i, _i); }
}
public bool MoveNext()
{
_i++;
if (_i == _throwAt)
{
throw new Exception();
}
return _i < 5;
}
public void Reset()
{
}
public DictionaryEntry Entry
{
get { return (DictionaryEntry)Current; }
}
public object Key
{
get { return _i; }
}
public object Value
{
get { return _i; }
}
}
}
public class ListNode
{
public ListNode next;
public object data;
}
public class LongMembers
{
public readonly string LongName0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789 = "hello";
public readonly string LongValue = "0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789";
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedEvent.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.Diagnostics;
using System.Threading;
using Cci = Microsoft.Cci;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition
{
private readonly TEmbeddedMethod _adder;
private readonly TEmbeddedMethod _remover;
private readonly TEmbeddedMethod _caller;
private int _isUsedForComAwareEventBinding;
protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) :
base(underlyingEvent)
{
Debug.Assert(adder != null || remover != null);
_adder = adder;
_remover = remover;
_caller = caller;
}
internal override TEmbeddedTypesManager TypeManager
{
get
{
return AnAccessor.TypeManager;
}
}
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract TEmbeddedType ContainingType { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
public TEventSymbol UnderlyingEvent
{
get
{
return this.UnderlyingSymbol;
}
}
protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding);
internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding)
{
if (_isUsedForComAwareEventBinding == 0 &&
(!isUsedForComAwareEventBinding ||
Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0))
{
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding);
}
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get { return _adder; }
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get { return _remover; }
}
Cci.IMethodReference Cci.IEventDefinition.Caller
{
get { return _caller; }
}
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
if (_adder != null)
{
yield return _adder;
}
if (_remover != null)
{
yield return _remover;
}
if (_caller != null)
{
yield return _caller;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
return IsRuntimeSpecial;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
protected TEmbeddedMethod AnAccessor
{
get
{
return _adder ?? _remover;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get { return ContainingType; }
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
return Visibility;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name
{
get
{
return 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.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Cci = Microsoft.Cci;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition
{
private readonly TEmbeddedMethod _adder;
private readonly TEmbeddedMethod _remover;
private readonly TEmbeddedMethod _caller;
private int _isUsedForComAwareEventBinding;
protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) :
base(underlyingEvent)
{
Debug.Assert(adder != null || remover != null);
_adder = adder;
_remover = remover;
_caller = caller;
}
internal override TEmbeddedTypesManager TypeManager
{
get
{
return AnAccessor.TypeManager;
}
}
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract TEmbeddedType ContainingType { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
public TEventSymbol UnderlyingEvent
{
get
{
return this.UnderlyingSymbol;
}
}
protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding);
internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding)
{
if (_isUsedForComAwareEventBinding == 0 &&
(!isUsedForComAwareEventBinding ||
Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0))
{
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding);
}
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get { return _adder; }
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get { return _remover; }
}
Cci.IMethodReference Cci.IEventDefinition.Caller
{
get { return _caller; }
}
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
if (_adder != null)
{
yield return _adder;
}
if (_remover != null)
{
yield return _remover;
}
if (_caller != null)
{
yield return _caller;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
return IsRuntimeSpecial;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
protected TEmbeddedMethod AnAccessor
{
get
{
return _adder ?? _remover;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get { return ContainingType; }
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
return Visibility;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name
{
get
{
return Name;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/CodeAnalysisTest/LinePositionTests.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 Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class LinePositionTests
{
[Fact]
public void Equality1()
{
EqualityUtil.RunAll(
(left, right) => left == right,
(left, right) => left != right,
EqualityUnit.Create(new LinePosition(1, 2)).WithEqualValues(new LinePosition(1, 2)),
EqualityUnit.Create(new LinePosition()).WithEqualValues(new LinePosition()),
EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(1, 3)),
EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(2, 2)));
}
[Fact]
public void Ctor1()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => { var notUsed = new LinePosition(-1, 42); });
}
[Fact]
public void Ctor2()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => { var notUsed = new LinePosition(42, -1); });
}
[Fact]
public void Ctor3()
{
var lp = new LinePosition(42, 13);
Assert.Equal(42, lp.Line);
Assert.Equal(13, lp.Character);
}
// In general, different values are not required to have different hash codes.
// But for perf reasons we want hash functions with a good distribution,
// so we expect hash codes to differ if a single component is incremented.
// But program correctness should be preserved even with a null hash function,
// so we need a way to disable these tests during such correctness validation.
#if !DISABLE_GOOD_HASH_TESTS
[Fact]
public void SaneHashCode()
{
var hash1 = new LinePosition(1, 1).GetHashCode();
var hash2 = new LinePosition(2, 2).GetHashCode();
var hash3 = new LinePosition(1, 2).GetHashCode();
var hash4 = new LinePosition(2, 1).GetHashCode();
Assert.NotEqual(hash1, hash2);
Assert.NotEqual(hash1, hash3);
Assert.NotEqual(hash1, hash4);
Assert.NotEqual(hash2, hash3);
Assert.NotEqual(hash2, hash4);
Assert.NotEqual(hash3, hash4);
}
#endif
[Fact]
public void CompareTo()
{
Assert.Equal(0, new LinePosition(1, 1).CompareTo(new LinePosition(1, 1)));
Assert.Equal(-1, Math.Sign(new LinePosition(1, 1).CompareTo(new LinePosition(1, 2))));
Assert.True(new LinePosition(1, 1) < new LinePosition(1, 2));
Assert.Equal(-1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(2, 1))));
Assert.True(new LinePosition(1, 2) < new LinePosition(2, 1));
Assert.True(new LinePosition(1, 2) <= new LinePosition(1, 2));
Assert.True(new LinePosition(1, 2) <= new LinePosition(2, 1));
Assert.Equal(+1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(1, 1))));
Assert.True(new LinePosition(1, 2) > new LinePosition(1, 1));
Assert.Equal(+1, Math.Sign(new LinePosition(2, 1).CompareTo(new LinePosition(1, 2))));
Assert.True(new LinePosition(2, 1) > new LinePosition(1, 2));
Assert.True(new LinePosition(2, 1) >= new LinePosition(2, 1));
Assert.True(new LinePosition(2, 1) >= new LinePosition(1, 2));
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class LinePositionTests
{
[Fact]
public void Equality1()
{
EqualityUtil.RunAll(
(left, right) => left == right,
(left, right) => left != right,
EqualityUnit.Create(new LinePosition(1, 2)).WithEqualValues(new LinePosition(1, 2)),
EqualityUnit.Create(new LinePosition()).WithEqualValues(new LinePosition()),
EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(1, 3)),
EqualityUnit.Create(new LinePosition(1, 2)).WithNotEqualValues(new LinePosition(2, 2)));
}
[Fact]
public void Ctor1()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => { var notUsed = new LinePosition(-1, 42); });
}
[Fact]
public void Ctor2()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => { var notUsed = new LinePosition(42, -1); });
}
[Fact]
public void Ctor3()
{
var lp = new LinePosition(42, 13);
Assert.Equal(42, lp.Line);
Assert.Equal(13, lp.Character);
}
// In general, different values are not required to have different hash codes.
// But for perf reasons we want hash functions with a good distribution,
// so we expect hash codes to differ if a single component is incremented.
// But program correctness should be preserved even with a null hash function,
// so we need a way to disable these tests during such correctness validation.
#if !DISABLE_GOOD_HASH_TESTS
[Fact]
public void SaneHashCode()
{
var hash1 = new LinePosition(1, 1).GetHashCode();
var hash2 = new LinePosition(2, 2).GetHashCode();
var hash3 = new LinePosition(1, 2).GetHashCode();
var hash4 = new LinePosition(2, 1).GetHashCode();
Assert.NotEqual(hash1, hash2);
Assert.NotEqual(hash1, hash3);
Assert.NotEqual(hash1, hash4);
Assert.NotEqual(hash2, hash3);
Assert.NotEqual(hash2, hash4);
Assert.NotEqual(hash3, hash4);
}
#endif
[Fact]
public void CompareTo()
{
Assert.Equal(0, new LinePosition(1, 1).CompareTo(new LinePosition(1, 1)));
Assert.Equal(-1, Math.Sign(new LinePosition(1, 1).CompareTo(new LinePosition(1, 2))));
Assert.True(new LinePosition(1, 1) < new LinePosition(1, 2));
Assert.Equal(-1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(2, 1))));
Assert.True(new LinePosition(1, 2) < new LinePosition(2, 1));
Assert.True(new LinePosition(1, 2) <= new LinePosition(1, 2));
Assert.True(new LinePosition(1, 2) <= new LinePosition(2, 1));
Assert.Equal(+1, Math.Sign(new LinePosition(1, 2).CompareTo(new LinePosition(1, 1))));
Assert.True(new LinePosition(1, 2) > new LinePosition(1, 1));
Assert.Equal(+1, Math.Sign(new LinePosition(2, 1).CompareTo(new LinePosition(1, 2))));
Assert.True(new LinePosition(2, 1) > new LinePosition(1, 2));
Assert.True(new LinePosition(2, 1) >= new LinePosition(2, 1));
Assert.True(new LinePosition(2, 1) >= new LinePosition(1, 2));
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrameCopyConstructor.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.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Copy constructor has one parameter of the same type as the enclosing type.
''' The purpose is to copy all the lifted values from previous version of the
''' frame if there was any into the new one.
''' </summary>
Friend Class SynthesizedLambdaCopyConstructor
Inherits SynthesizedLambdaConstructor
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Friend Sub New(syntaxNode As SyntaxNode, containingType As LambdaFrame)
MyBase.New(syntaxNode, containingType)
_parameters = ImmutableArray.Create(Of ParameterSymbol)(New SourceSimpleParameterSymbol(Me, "arg0", 0, containingType, Nothing))
End Sub
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
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
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Copy constructor has one parameter of the same type as the enclosing type.
''' The purpose is to copy all the lifted values from previous version of the
''' frame if there was any into the new one.
''' </summary>
Friend Class SynthesizedLambdaCopyConstructor
Inherits SynthesizedLambdaConstructor
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Friend Sub New(syntaxNode As SyntaxNode, containingType As LambdaFrame)
MyBase.New(syntaxNode, containingType)
_parameters = ImmutableArray.Create(Of ParameterSymbol)(New SourceSimpleParameterSymbol(Me, "arg0", 0, containingType, Nothing))
End Sub
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TopologicalSorter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Roslyn.Utilities
{
internal static class TopologicalSorter
{
public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore)
{
var result = new List<T>();
var visited = new HashSet<T>();
foreach (var item in items)
{
Visit(item, itemsBefore, result, visited);
}
return result;
}
public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore, Func<T, IEnumerable<T>> itemsAfter)
where T : notnull
{
var combinedItemsBefore = CreateCombinedItemsBefore(items, itemsBefore, itemsAfter);
return TopologicalSort(items, combinedItemsBefore);
}
private static void Visit<T>(
T item,
Func<T, IEnumerable<T>> itemsBefore,
List<T> result,
HashSet<T> visited)
{
if (visited.Add(item))
{
foreach (var before in itemsBefore(item))
{
Visit(before, itemsBefore, result, visited);
}
result.Add(item);
}
}
private static Func<T, IEnumerable<T>> CreateCombinedItemsBefore<T>(IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore, Func<T, IEnumerable<T>> itemsAfter)
where T : notnull
{
// create initial list
var itemToItemsBefore = items.ToDictionary(item => item, item =>
{
var naturalItemsBefore = itemsBefore != null ? itemsBefore(item) : null;
if (naturalItemsBefore != null)
{
return naturalItemsBefore.ToList();
}
else
{
return new List<T>();
}
});
// add items after by making the after items explicitly list the item as before it
if (itemsAfter != null)
{
foreach (var item in items)
{
var naturalItemsAfter = itemsAfter(item);
if (naturalItemsAfter != null)
{
foreach (var itemAfter in naturalItemsAfter)
{
var itemsAfterBeforeList = itemToItemsBefore[itemAfter];
itemsAfterBeforeList.Add(item);
}
}
}
}
return item => itemToItemsBefore[item];
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Roslyn.Utilities
{
internal static class TopologicalSorter
{
public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore)
{
var result = new List<T>();
var visited = new HashSet<T>();
foreach (var item in items)
{
Visit(item, itemsBefore, result, visited);
}
return result;
}
public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore, Func<T, IEnumerable<T>> itemsAfter)
where T : notnull
{
var combinedItemsBefore = CreateCombinedItemsBefore(items, itemsBefore, itemsAfter);
return TopologicalSort(items, combinedItemsBefore);
}
private static void Visit<T>(
T item,
Func<T, IEnumerable<T>> itemsBefore,
List<T> result,
HashSet<T> visited)
{
if (visited.Add(item))
{
foreach (var before in itemsBefore(item))
{
Visit(before, itemsBefore, result, visited);
}
result.Add(item);
}
}
private static Func<T, IEnumerable<T>> CreateCombinedItemsBefore<T>(IEnumerable<T> items, Func<T, IEnumerable<T>> itemsBefore, Func<T, IEnumerable<T>> itemsAfter)
where T : notnull
{
// create initial list
var itemToItemsBefore = items.ToDictionary(item => item, item =>
{
var naturalItemsBefore = itemsBefore != null ? itemsBefore(item) : null;
if (naturalItemsBefore != null)
{
return naturalItemsBefore.ToList();
}
else
{
return new List<T>();
}
});
// add items after by making the after items explicitly list the item as before it
if (itemsAfter != null)
{
foreach (var item in items)
{
var naturalItemsAfter = itemsAfter(item);
if (naturalItemsAfter != null)
{
foreach (var itemAfter in naturalItemsAfter)
{
var itemsAfterBeforeList = itemToItemsBefore[itemAfter];
itemsAfterBeforeList.Add(item);
}
}
}
}
return item => itemToItemsBefore[item];
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/Portable/Symbols/NullableFlowState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the compiler's analysis of whether an expression may be null
/// </summary>
// Review docs: https://github.com/dotnet/roslyn/issues/35046
public enum NullableFlowState : byte
{
/// <summary>
/// Syntax is not an expression, or was not analyzed.
/// </summary>
None = 0,
/// <summary>
/// Expression is not null.
/// </summary>
NotNull,
/// <summary>
/// Expression may be null.
/// </summary>
MaybeNull
}
internal static class NullableFlowStateExtensions
{
/// <summary>
/// This method directly converts a <see cref="NullableFlowState"/> to a <see cref="NullableAnnotation"/>,
/// ignoring the <see cref="ITypeSymbol"/> to which it is attached. It should only be used when converting
/// an RValue flow state to an RValue annotation for returning via the public API. For general use, please
/// use Microsoft.CodeAnalysis.CSharp.Symbols.TypeWithState.ToTypeWithAnnotations.
/// </summary>
public static NullableAnnotation ToAnnotation(this NullableFlowState nullableFlowState)
{
switch (nullableFlowState)
{
case CodeAnalysis.NullableFlowState.MaybeNull:
return CodeAnalysis.NullableAnnotation.Annotated;
case CodeAnalysis.NullableFlowState.NotNull:
return CodeAnalysis.NullableAnnotation.NotAnnotated;
default:
return CodeAnalysis.NullableAnnotation.None;
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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
{
/// <summary>
/// Represents the compiler's analysis of whether an expression may be null
/// </summary>
// Review docs: https://github.com/dotnet/roslyn/issues/35046
public enum NullableFlowState : byte
{
/// <summary>
/// Syntax is not an expression, or was not analyzed.
/// </summary>
None = 0,
/// <summary>
/// Expression is not null.
/// </summary>
NotNull,
/// <summary>
/// Expression may be null.
/// </summary>
MaybeNull
}
internal static class NullableFlowStateExtensions
{
/// <summary>
/// This method directly converts a <see cref="NullableFlowState"/> to a <see cref="NullableAnnotation"/>,
/// ignoring the <see cref="ITypeSymbol"/> to which it is attached. It should only be used when converting
/// an RValue flow state to an RValue annotation for returning via the public API. For general use, please
/// use Microsoft.CodeAnalysis.CSharp.Symbols.TypeWithState.ToTypeWithAnnotations.
/// </summary>
public static NullableAnnotation ToAnnotation(this NullableFlowState nullableFlowState)
{
switch (nullableFlowState)
{
case CodeAnalysis.NullableFlowState.MaybeNull:
return CodeAnalysis.NullableAnnotation.Annotated;
case CodeAnalysis.NullableFlowState.NotNull:
return CodeAnalysis.NullableAnnotation.NotAnnotated;
default:
return CodeAnalysis.NullableAnnotation.None;
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmProcess.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
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
namespace Microsoft.VisualStudio.Debugger
{
public class DkmProcess
{
public readonly DkmEngineSettings EngineSettings = new DkmEngineSettings();
private readonly bool _nativeDebuggingEnabled;
public DkmProcess(bool enableNativeDebugging)
{
_nativeDebuggingEnabled = enableNativeDebugging;
}
public DkmRuntimeInstance GetNativeRuntimeInstance()
{
if (!_nativeDebuggingEnabled)
{
throw new DkmException(DkmExceptionCode.E_XAPI_DATA_ITEM_NOT_FOUND);
}
return null; // Value isn't required for testing
}
}
public class DkmThread
{
}
}
| // Licensed to the .NET Foundation under one or more 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
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
namespace Microsoft.VisualStudio.Debugger
{
public class DkmProcess
{
public readonly DkmEngineSettings EngineSettings = new DkmEngineSettings();
private readonly bool _nativeDebuggingEnabled;
public DkmProcess(bool enableNativeDebugging)
{
_nativeDebuggingEnabled = enableNativeDebugging;
}
public DkmRuntimeInstance GetNativeRuntimeInstance()
{
if (!_nativeDebuggingEnabled)
{
throw new DkmException(DkmExceptionCode.E_XAPI_DATA_ITEM_NOT_FOUND);
}
return null; // Value isn't required for testing
}
}
public class DkmThread
{
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolution.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.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class OverloadResolution
{
public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We can do a table lookup for well-known problems in overload resolution.
BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result);
if (result.Results.Count > 0)
{
return;
}
BinaryOperatorOverloadResolution_NoEasyOut(kind, left, right, result, ref useSiteInfo);
}
internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// SPEC: An operation of the form x&&y or x||y is processed by applying overload resolution
// SPEC: as if the operation was written x&y or x|y.
// SPEC VIOLATION: For compatibility with Dev11, do not apply this rule to built-in conversions.
BinaryOperatorKind underlyingKind = kind & ~BinaryOperatorKind.Logical;
BinaryOperatorEasyOut(underlyingKind, left, right, result);
}
internal void BinaryOperatorOverloadResolution_NoEasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// SPEC: An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// SPEC: The set of candidate user-defined operators provided by the types (if any) of x and y for the
// SPEC operation operator op(x, y) is determined.
TypeSymbol leftOperatorSourceOpt = left.Type?.StrippedType();
TypeSymbol rightOperatorSourceOpt = right.Type?.StrippedType();
bool leftSourceIsInterface = leftOperatorSourceOpt?.IsInterfaceType() == true;
bool rightSourceIsInterface = rightOperatorSourceOpt?.IsInterfaceType() == true;
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// TODO (tomat): The spec needs to be updated to use identity conversion instead of type equality.
// Spec 7.3.4 Binary operator overload resolution:
// An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// The set of candidate user-defined operators provided by the types (if any) of x and y for the
// operation operator op(x, y) is determined. The set consists of the union of the candidate operators
// provided by the type of x (if any) and the candidate operators provided by the type of y (if any),
// each determined using the rules of 7.3.5. Candidate operators only occur in the combined set once.
// From https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-27.md:
// - We only even look for operator implementations in interfaces if one of the operands has a type that is
// an interface or a type parameter with a non-empty effective base interface list.
// - We should look at operators from classes first, in order to avoid breaking changes.
// Only if there are no applicable user-defined operators from classes will we look in interfaces.
// If there aren't any there either, we go to built-ins.
// - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in
// base interfaces: we stop looking.
bool hadApplicableCandidates = false;
// In order to preserve backward compatibility, at first we ignore interface sources.
if ((object)leftOperatorSourceOpt != null && !leftSourceIsInterface)
{
hadApplicableCandidates = GetUserDefinedOperators(kind, leftOperatorSourceOpt, left, right, result.Results, ref useSiteInfo);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
}
if ((object)rightOperatorSourceOpt != null && !rightSourceIsInterface && !rightOperatorSourceOpt.Equals(leftOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedOperators(kind, rightOperatorSourceOpt, left, right, rightOperators, ref useSiteInfo))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
// If there are no applicable candidates in classes / stuctures, try with interface sources.
if (!hadApplicableCandidates)
{
result.Results.Clear();
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var lookedInInterfaces = PooledDictionary<TypeSymbol, bool>.GetInstance();
TypeSymbol firstOperatorSourceOpt;
TypeSymbol secondOperatorSourceOpt;
bool firstSourceIsInterface;
bool secondSourceIsInterface;
// Always start lookup from a type parameter. This ensures that regardless of the order we always pick up constrained type for
// each distinct candidate operator.
if (leftOperatorSourceOpt is null || (leftOperatorSourceOpt is not TypeParameterSymbol && rightOperatorSourceOpt is TypeParameterSymbol))
{
firstOperatorSourceOpt = rightOperatorSourceOpt;
secondOperatorSourceOpt = leftOperatorSourceOpt;
firstSourceIsInterface = rightSourceIsInterface;
secondSourceIsInterface = leftSourceIsInterface;
}
else
{
firstOperatorSourceOpt = leftOperatorSourceOpt;
secondOperatorSourceOpt = rightOperatorSourceOpt;
firstSourceIsInterface = leftSourceIsInterface;
secondSourceIsInterface = rightSourceIsInterface;
}
hadApplicableCandidates = GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
firstOperatorSourceOpt, firstSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, result.Results);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
if ((object)secondOperatorSourceOpt != null && !secondOperatorSourceOpt.Equals(firstOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
secondOperatorSourceOpt, secondSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, rightOperators))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
lookedInInterfaces.Free();
}
// SPEC: If the set of candidate user-defined operators is not empty, then this becomes the set of candidate
// SPEC: operators for the operation. Otherwise, the predefined binary operator op implementations, including
// SPEC: their lifted forms, become the set of candidate operators for the operation.
// Note that the native compiler has a bug in its binary operator overload resolution involving
// lifted built-in operators. The spec says that we should add the lifted and unlifted operators
// to a candidate set, eliminate the inapplicable operators, and then choose the best of what is left.
// The lifted operator is defined as, say int? + int? --> int?. That is not what the native compiler
// does. The native compiler, rather, effectively says that there are *three* lifted operators:
// int? + int? --> int?, int + int? --> int? and int? + int --> int?, and it chooses the best operator
// amongst those choices.
//
// This is a subtle difference; most of the time all it means is that we generate better code because we
// skip an unnecessary operand conversion to int? when adding int to int?. But some of the time it
// means that a different user-defined conversion is chosen than the one you would expect, if the
// operand has a user-defined conversion to both int and int?.
//
// Roslyn matches the specification and takes the break from the native compiler.
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
if (!hadApplicableCandidates)
{
result.Results.Clear();
GetAllBuiltInOperators(kind, left, right, result.Results, ref useSiteInfo);
}
// SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators to select the best
// SPEC: operator with respect to the argument list (x, y), and this operator becomes the result of the overload
// SPEC: resolution process. If overload resolution fails to select a single best operator, a binding-time
// SPEC: error occurs.
BinaryOperatorOverloadResolution(left, right, result, ref useSiteInfo);
}
private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind, string name,
TypeSymbol operatorSourceOpt, bool sourceIsInterface,
BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
Dictionary<TypeSymbol, bool> lookedInInterfaces, ArrayBuilder<BinaryOperatorAnalysisResult> candidates)
{
Debug.Assert(candidates.Count == 0);
if ((object)operatorSourceOpt == null)
{
return false;
}
bool hadUserDefinedCandidateFromInterfaces = false;
ImmutableArray<NamedTypeSymbol> interfaces = default;
TypeSymbol constrainedToTypeOpt = null;
if (sourceIsInterface)
{
if (!lookedInInterfaces.TryGetValue(operatorSourceOpt, out _))
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, (NamedTypeSymbol)operatorSourceOpt, kind, name, operators);
hadUserDefinedCandidateFromInterfaces = CandidateOperators(operators, left, right, candidates, ref useSiteInfo);
operators.Free();
Debug.Assert(hadUserDefinedCandidateFromInterfaces == candidates.Any(r => r.IsValid));
lookedInInterfaces.Add(operatorSourceOpt, hadUserDefinedCandidateFromInterfaces);
if (!hadUserDefinedCandidateFromInterfaces)
{
candidates.Clear();
interfaces = operatorSourceOpt.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
}
}
else if (operatorSourceOpt.IsTypeParameter())
{
interfaces = ((TypeParameterSymbol)operatorSourceOpt).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
constrainedToTypeOpt = operatorSourceOpt;
}
if (!interfaces.IsDefaultOrEmpty)
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
var results = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
var shadowedInterfaces = PooledHashSet<NamedTypeSymbol>.GetInstance();
foreach (NamedTypeSymbol @interface in interfaces)
{
if ([email protected])
{
// this code could be reachable in error situations
continue;
}
if (shadowedInterfaces.Contains(@interface))
{
// this interface is "shadowed" by a derived interface
continue;
}
if (lookedInInterfaces.TryGetValue(@interface, out bool hadUserDefinedCandidate))
{
if (hadUserDefinedCandidate)
{
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo));
}
// no need to perform another lookup in this interface
continue;
}
operators.Clear();
results.Clear();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name, operators);
hadUserDefinedCandidate = CandidateOperators(operators, left, right, results, ref useSiteInfo);
Debug.Assert(hadUserDefinedCandidate == results.Any(r => r.IsValid));
lookedInInterfaces.Add(@interface, hadUserDefinedCandidate);
if (hadUserDefinedCandidate)
{
hadUserDefinedCandidateFromInterfaces = true;
candidates.AddRange(results);
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo));
}
}
operators.Free();
results.Free();
shadowedInterfaces.Free();
}
return hadUserDefinedCandidateFromInterfaces;
}
private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
default:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType));
break;
}
}
private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> operators, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
break;
default:
// Unhandled bin op kind in get delegate operation
throw ExceptionUtilities.UnexpectedValue(kind);
}
var leftType = left.Type;
var leftDelegate = (object)leftType != null && leftType.IsDelegateType();
var rightType = right.Type;
var rightDelegate = (object)rightType != null && rightType.IsDelegateType();
// If no operands have delegate types then add nothing.
if (!leftDelegate && !rightDelegate)
{
// Even though neither left nor right type is a delegate type,
// both types might have implicit conversions to System.Delegate type.
// Spec 7.10.8: Delegate equality operators:
// Every delegate type implicitly provides the following predefined comparison operators:
// bool operator ==(System.Delegate x, System.Delegate y)
// bool operator !=(System.Delegate x, System.Delegate y)
switch (OperatorKindExtensions.Operator(kind))
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
TypeSymbol systemDelegateType = _binder.Compilation.GetSpecialType(SpecialType.System_Delegate);
systemDelegateType.AddUseSiteInfo(ref useSiteInfo);
if (Conversions.ClassifyImplicitConversionFromExpression(left, systemDelegateType, ref useSiteInfo).IsValid &&
Conversions.ClassifyImplicitConversionFromExpression(right, systemDelegateType, ref useSiteInfo).IsValid)
{
AddDelegateOperation(kind, systemDelegateType, operators);
}
break;
}
return;
}
// We might have a situation like
//
// Func<string> + Func<object>
//
// in which case overload resolution should consider both
//
// Func<string> + Func<string>
// Func<object> + Func<object>
//
// are candidates (and it will pick Func<object>). Similarly,
// we might have something like:
//
// Func<object> + Func<dynamic>
//
// in which case neither candidate is better than the other,
// resulting in an error.
//
// We could as an optimization say that if you are adding two completely
// dissimilar delegate types D1 and D2, that neither is added to the candidate
// set because neither can possibly be applicable, but let's not go there.
// Let's just add them to the set and let overload resolution (and the
// error recovery heuristics) have at the real candidate set.
//
// However, we will take a spec violation for this scenario:
//
// SPEC VIOLATION:
//
// Technically the spec implies that we ought to be able to compare
//
// Func<int> x = whatever;
// bool y = x == ()=>1;
//
// The native compiler does not allow this. I see no
// reason why we ought to allow this. However, a good question is whether
// the violation ought to be here, where we are determining the operator
// candidate set, or in overload resolution where we are determining applicability.
// In the native compiler we did it during candidate set determination,
// so let's stick with that.
if (leftDelegate && rightDelegate)
{
// They are both delegate types. Add them both if they are different types.
AddDelegateOperation(kind, leftType, operators);
// There is no reason why we can't compare instances of delegate types that are identity convertible.
// We can't perform + or - operation on them since it is not clear what the return type of such operation should be.
bool useIdentityConversion = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (!(useIdentityConversion ? Conversions.HasIdentityConversion(leftType, rightType) : leftType.Equals(rightType)))
{
AddDelegateOperation(kind, rightType, operators);
}
return;
}
// One of them is a delegate, the other is not.
TypeSymbol delegateType = leftDelegate ? leftType : rightType;
BoundExpression nonDelegate = leftDelegate ? right : left;
if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)
&& nonDelegate.Kind == BoundKind.UnboundLambda)
{
return;
}
AddDelegateOperation(kind, delegateType, operators);
}
private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)enumType != null);
AssertNotChecked(kind);
if (!enumType.IsValidEnumType())
{
return;
}
var underlying = enumType.GetEnumUnderlyingType();
Debug.Assert((object)underlying != null);
Debug.Assert(underlying.SpecialType != SpecialType.None);
var nullable = Compilation.GetSpecialType(SpecialType.System_Nullable_T);
var nullableEnum = nullable.Construct(enumType);
var nullableUnderlying = nullable.Construct(underlying);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, underlying, enumType, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, nullableEnum, nullableUnderlying, nullableEnum));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, nullableUnderlying, nullableEnum, nullableEnum));
break;
case BinaryOperatorKind.Subtraction:
if (Strict)
{
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum));
}
else
{
// SPEC VIOLATION:
// The native compiler has bugs in overload resolution involving binary operator- for enums,
// which we duplicate by hardcoding Priority values among the operators. When present on both
// methods being compared during overload resolution, Priority values are used to decide between
// two candidates (instead of the usual language-specified rules).
bool isExactSubtraction = TypeSymbol.Equals(right.Type?.StrippedType(), underlying, TypeCompareKind.ConsiderEverything2);
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying)
{ Priority = 2 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType)
{ Priority = isExactSubtraction ? 1 : 3 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying)
{ Priority = 12 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum)
{ Priority = isExactSubtraction ? 11 : 13 });
// Due to a bug, the native compiler allows "underlying - enum", so Roslyn does as well.
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, underlying, enumType, enumType)
{ Priority = 4 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, nullableUnderlying, nullableEnum, nullableEnum)
{ Priority = 14 });
}
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var boolean = Compilation.GetSpecialType(SpecialType.System_Boolean);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, boolean));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, boolean));
break;
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, nullableEnum));
break;
}
}
private void GetPointerArithmeticOperators(
BinaryOperatorKind kind,
PointerTypeSymbol pointerType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)pointerType != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType, pointerType));
break;
case BinaryOperatorKind.Subtraction:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64)));
break;
}
}
private void GetPointerComparisonOperators(
BinaryOperatorKind kind,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var voidPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(Compilation.GetSpecialType(SpecialType.System_Void)));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, voidPointerType, voidPointerType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
}
}
private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
// First take some easy outs:
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
}
var leftType = left.Type;
if ((object)leftType != null)
{
leftType = leftType.StrippedType();
}
var rightType = right.Type;
if ((object)rightType != null)
{
rightType = rightType.StrippedType();
}
bool useIdentityConversion;
switch (kind)
{
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
// These operations are ambiguous on non-equal identity-convertible types -
// it's not clear what the resulting type of the operation should be:
// C<?>.E operator +(C<dynamic>.E x, C<object>.E y)
useIdentityConversion = false;
break;
case BinaryOperatorKind.Addition:
// Addition only accepts a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// E operator +(E x, U y)
// E operator +(U x, E y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Subtraction:
// Subtraction either returns underlying type or only accept a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// U operator –(E x, E y)
// E operator –(E x, U y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
// Relational operations return Boolean, so operations on non-equal identity-convertible types are not ambiguous.
// Boolean operator op(C<dynamic>.E, C<object>.E)
useIdentityConversion = true;
break;
default:
// Unhandled bin op kind in get enum operations
throw ExceptionUtilities.UnexpectedValue(kind);
}
if ((object)leftType != null)
{
GetEnumOperation(kind, leftType, left, right, results);
}
if ((object)rightType != null && ((object)leftType == null || !(useIdentityConversion ? Conversions.HasIdentityConversion(rightType, leftType) : rightType.Equals(leftType))))
{
GetEnumOperation(kind, rightType, left, right, results);
}
}
private void GetPointerOperators(
BinaryOperatorKind kind,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
var leftType = left.Type as PointerTypeSymbol;
var rightType = right.Type as PointerTypeSymbol;
if ((object)leftType != null)
{
GetPointerArithmeticOperators(kind, leftType, results);
}
// The only arithmetic operator that is applicable on two distinct pointer types is
// long operator –(T* x, T* y)
// This operator returns long and so it's not ambiguous to apply it on T1 and T2 that are identity convertible to each other.
if ((object)rightType != null && ((object)leftType == null || !Conversions.HasIdentityConversion(rightType, leftType)))
{
GetPointerArithmeticOperators(kind, rightType, results);
}
if ((object)leftType != null || (object)rightType != null || left.Type is FunctionPointerTypeSymbol || right.Type is FunctionPointerTypeSymbol)
{
// The pointer comparison operators are all "void* OP void*".
GetPointerComparisonOperators(kind, results);
}
}
private void GetAllBuiltInOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// Strip the "checked" off; the checked-ness of the context does not affect which built-in operators
// are applicable.
kind = kind.OperatorWithLogical();
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (isEquality && useOnlyReferenceEquality(Conversions, left, right, ref useSiteInfo))
{
// As a special case, if the reference equality operator is applicable (and it
// is not a string or delegate) we do not check any other operators. This patches
// what is otherwise a flaw in the language specification. See 11426.
GetReferenceEquality(kind, operators);
}
else
{
this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators, skipNativeIntegerOperators: !left.Type.IsNativeIntegerOrNullableNativeIntegerType() && !right.Type.IsNativeIntegerOrNullableNativeIntegerType());
// SPEC 7.3.4: For predefined enum and delegate operators, the only operators
// considered are those defined by an enum or delegate type that is the binding
//-time type of one of the operands.
GetDelegateOperations(kind, left, right, operators, ref useSiteInfo);
GetEnumOperations(kind, left, right, operators);
// We similarly limit pointer operator candidates considered.
GetPointerOperators(kind, left, right, operators);
}
CandidateOperators(operators, left, right, results, ref useSiteInfo);
operators.Free();
static bool useOnlyReferenceEquality(Conversions conversions, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We consider the `null` literal, but not the `default` literal, since the latter does not require a reference equality
return
BuiltInOperators.IsValidObjectEquality(conversions, left.Type, left.IsLiteralNull(), leftIsDefault: false, right.Type, right.IsLiteralNull(), rightIsDefault: false, ref useSiteInfo) &&
((object)left.Type == null || (!left.Type.IsDelegateType() && left.Type.SpecialType != SpecialType.System_String && left.Type.SpecialType != SpecialType.System_Delegate)) &&
((object)right.Type == null || (!right.Type.IsDelegateType() && right.Type.SpecialType != SpecialType.System_String && right.Type.SpecialType != SpecialType.System_Delegate));
}
}
private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators)
{
var @object = Compilation.GetSpecialType(SpecialType.System_Object);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, @object, @object, Compilation.GetSpecialType(SpecialType.System_Boolean)));
}
private bool CandidateOperators(
ArrayBuilder<BinaryOperatorSignature> operators,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool hadApplicableCandidate = false;
foreach (var op in operators)
{
var convLeft = Conversions.ClassifyConversionFromExpression(left, op.LeftType, ref useSiteInfo);
var convRight = Conversions.ClassifyConversionFromExpression(right, op.RightType, ref useSiteInfo);
if (convLeft.IsImplicit && convRight.IsImplicit)
{
results.Add(BinaryOperatorAnalysisResult.Applicable(op, convLeft, convRight));
hadApplicableCandidate = true;
}
else
{
results.Add(BinaryOperatorAnalysisResult.Inapplicable(op, convLeft, convRight));
}
}
return hadApplicableCandidate;
}
private static void AddDistinctOperators(ArrayBuilder<BinaryOperatorAnalysisResult> result, ArrayBuilder<BinaryOperatorAnalysisResult> additionalOperators)
{
int initialCount = result.Count;
foreach (var op in additionalOperators)
{
bool equivalentToExisting = false;
for (int i = 0; i < initialCount; i++)
{
var existingSignature = result[i].Signature;
Debug.Assert(op.Signature.Kind.Operator() == existingSignature.Kind.Operator());
// Return types must match exactly, parameters might match modulo identity conversion.
if (op.Signature.Kind == existingSignature.Kind && // Easy out
equalsIgnoringNullable(op.Signature.ReturnType, existingSignature.ReturnType) &&
equalsIgnoringNullableAndDynamic(op.Signature.LeftType, existingSignature.LeftType) &&
equalsIgnoringNullableAndDynamic(op.Signature.RightType, existingSignature.RightType) &&
equalsIgnoringNullableAndDynamic(op.Signature.Method.ContainingType, existingSignature.Method.ContainingType))
{
equivalentToExisting = true;
break;
}
}
if (!equivalentToExisting)
{
result.Add(op);
}
}
static bool equalsIgnoringNullable(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions);
static bool equalsIgnoringNullableAndDynamic(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreDynamic);
}
private bool GetUserDefinedOperators(
BinaryOperatorKind kind,
TypeSymbol type0,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(results.Count == 0);
if ((object)type0 == null || OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
{
return false;
}
// Spec 7.3.5 Candidate user-defined operators
// SPEC: Given a type T and an operation operator op(A), where op is an overloadable
// SPEC: operator and A is an argument list, the set of candidate user-defined operators
// SPEC: provided by T for operator op(A) is determined as follows:
// SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type,
// SPEC: otherwise T0 is equal to T.
// (The caller has already passed in the stripped type.)
// SPEC: For all operator op declarations in T0 and all lifted forms of such operators,
// SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument
// SPEC: list A, then the set of candidate operators consists of all such applicable
// SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
// SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate
// SPEC: operators provided by the direct base class of T0, or the effective base class of
// SPEC: T0 if T0 is a type parameter.
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool hadApplicableCandidates = false;
NamedTypeSymbol current = type0 as NamedTypeSymbol;
if ((object)current == null)
{
current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
if ((object)current == null && type0.IsTypeParameter())
{
current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteInfo);
}
for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
operators.Clear();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt: null, current, kind, name, operators);
results.Clear();
if (CandidateOperators(operators, left, right, results, ref useSiteInfo))
{
hadApplicableCandidates = true;
break;
}
}
operators.Free();
Debug.Assert(hadApplicableCandidates == results.Any(r => r.IsValid));
return hadApplicableCandidates;
}
private void GetUserDefinedBinaryOperatorsFromType(
TypeSymbol constrainedToTypeOpt,
NamedTypeSymbol type,
BinaryOperatorKind kind,
string name,
ArrayBuilder<BinaryOperatorSignature> operators)
{
foreach (MethodSymbol op in type.GetOperators(name))
{
// If we're in error recovery, we might have bad operators. Just ignore it.
if (op.ParameterCount != 2 || op.ReturnsVoid)
{
continue;
}
TypeSymbol leftOperandType = op.GetParameterType(0);
TypeSymbol rightOperandType = op.GetParameterType(1);
TypeSymbol resultType = op.ReturnType;
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op, constrainedToTypeOpt));
LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind);
if (lifting == LiftingResult.LiftOperandsAndResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op, constrainedToTypeOpt));
}
else if (lifting == LiftingResult.LiftOperandsButNotResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op, constrainedToTypeOpt));
}
}
}
private enum LiftingResult
{
NotLifted,
LiftOperandsAndResult,
LiftOperandsButNotResult
}
private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind)
{
// SPEC: For the binary operators + - * / % & | ^ << >> a lifted form of the
// SPEC: operator exists if the operand and result types are all non-nullable
// SPEC: value types. The lifted form is constructed by adding a single ?
// SPEC: modifier to each operand and result type.
//
// SPEC: For the equality operators == != a lifted form of the operator exists
// SPEC: if the operand types are both non-nullable value types and if the
// SPEC: result type is bool. The lifted form is constructed by adding
// SPEC: a single ? modifier to each operand type.
//
// SPEC: For the relational operators > < >= <= a lifted form of the
// SPEC: operator exists if the operand types are both non-nullable value
// SPEC: types and if the result type is bool. The lifted form is
// SPEC: constructed by adding a single ? modifier to each operand type.
if (!left.IsValueType ||
left.IsNullableType() ||
!right.IsValueType ||
right.IsNullableType())
{
return LiftingResult.NotLifted;
}
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// Spec violation: can't lift unless the types match.
// The spec doesn't require this, but dev11 does and it reduces ambiguity in some cases.
if (!TypeSymbol.Equals(left, right, TypeCompareKind.ConsiderEverything2)) return LiftingResult.NotLifted;
goto case BinaryOperatorKind.GreaterThan;
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return result.SpecialType == SpecialType.System_Boolean ?
LiftingResult.LiftOperandsButNotResult :
LiftingResult.NotLifted;
default:
return result.IsValueType && !result.IsNullableType() ?
LiftingResult.LiftOperandsAndResult :
LiftingResult.NotLifted;
}
}
// Takes a list of candidates and mutates the list to throw out the ones that are worse than
// another applicable candidate.
private void BinaryOperatorOverloadResolution(
BoundExpression left,
BoundExpression right,
BinaryOperatorOverloadResolutionResult result,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// SPEC: Given the set of applicable candidate function members, the best function member in that set is located.
// SPEC: If the set contains only one function member, then that function member is the best function member.
if (result.SingleValid())
{
return;
}
// SPEC: Otherwise, the best function member is the one function member that is better than all other function
// SPEC: members with respect to the given argument list, provided that each function member is compared to all
// SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is
// SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time
// SPEC: error occurs.
var candidates = result.Results;
// Try to find a single best candidate
int bestIndex = GetTheBestCandidateIndex(left, right, candidates, ref useSiteInfo);
if (bestIndex != -1)
{
// Mark all other candidates as worse
for (int index = 0; index < candidates.Count; ++index)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex)
{
candidates[index] = candidates[index].Worse();
}
}
return;
}
for (int i = 1; i < candidates.Count; ++i)
{
if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Is this applicable operator better than every other applicable method?
for (int j = 0; j < i; ++j)
{
if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, left, right, ref useSiteInfo);
if (better == BetterResult.Left)
{
candidates[j] = candidates[j].Worse();
}
else if (better == BetterResult.Right)
{
candidates[i] = candidates[i].Worse();
}
}
}
}
private int GetTheBestCandidateIndex(
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> candidates,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
int currentBestIndex = -1;
for (int index = 0; index < candidates.Count; index++)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Assume that the current candidate is the best if we don't have any
if (currentBestIndex == -1)
{
currentBestIndex = index;
}
else
{
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteInfo);
if (better == BetterResult.Right)
{
// The current best is worse
currentBestIndex = index;
}
else if (better != BetterResult.Left)
{
// The current best is not better
currentBestIndex = -1;
}
}
}
// Make sure that every candidate up to the current best is worse
for (int index = 0; index < currentBestIndex; index++)
{
if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteInfo);
if (better != BetterResult.Left)
{
// The current best is not better
return -1;
}
}
return currentBestIndex;
}
private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We use Priority as a tie-breaker to help match native compiler bugs.
Debug.Assert(op1.Priority.HasValue == op2.Priority.HasValue);
if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault())
{
return (op1.Priority.GetValueOrDefault() < op2.Priority.GetValueOrDefault()) ? BetterResult.Left : BetterResult.Right;
}
BetterResult leftBetter = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteInfo);
BetterResult rightBetter = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteInfo);
// SPEC: Mp is defined to be a better function member than Mq if:
// SPEC: * For each argument, the implicit conversion from Ex to Qx is not better than
// SPEC: the implicit conversion from Ex to Px, and
// SPEC: * For at least one argument, the conversion from Ex to Px is better than the
// SPEC: conversion from Ex to Qx.
// If that is hard to follow, consult this handy chart:
// op1.Left vs op2.Left op1.Right vs op2.Right result
// -----------------------------------------------------------
// op1 better op1 better op1 better
// op1 better neither better op1 better
// op1 better op2 better neither better
// neither better op1 better op1 better
// neither better neither better neither better
// neither better op2 better op2 better
// op2 better op1 better neither better
// op2 better neither better op2 better
// op2 better op2 better op2 better
if (leftBetter == BetterResult.Left && rightBetter != BetterResult.Right ||
leftBetter != BetterResult.Right && rightBetter == BetterResult.Left)
{
return BetterResult.Left;
}
if (leftBetter == BetterResult.Right && rightBetter != BetterResult.Left ||
leftBetter != BetterResult.Left && rightBetter == BetterResult.Right)
{
return BetterResult.Right;
}
// There was no better member on the basis of conversions. Go to the tiebreaking round.
// SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi
// SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules
// SPEC: are applied:
if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) &&
Conversions.HasIdentityConversion(op1.RightType, op2.RightType))
{
// NOTE: The native compiler does not follow these rules; effectively, the native
// compiler checks for liftedness first, and then for specificity. For example:
// struct S<T> where T : struct {
// public static bool operator +(S<T> x, int y) { return true; }
// public static bool? operator +(S<T>? x, int? y) { return false; }
// }
//
// bool? b = new S<int>?() + new int?();
//
// should reason as follows: the two applicable operators are the lifted
// form of the first operator and the unlifted second operator. The
// lifted form of the first operator is *more specific* because int?
// is more specific than T?. Therefore it should win. In fact the
// native compiler chooses the second operator, because it is unlifted.
//
// Roslyn follows the spec rules; if we decide to change the spec to match
// the native compiler, or decide to change Roslyn to match the native
// compiler, we should change the order of the checks here.
// SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq.
BetterResult result = MoreSpecificOperator(op1, op2, ref useSiteInfo);
if (result == BetterResult.Left || result == BetterResult.Right)
{
return result;
}
// SPEC: If one member is a non-lifted operator and the other is a lifted operator,
// SPEC: the non-lifted one is better.
bool lifted1 = op1.Kind.IsLifted();
bool lifted2 = op2.Kind.IsLifted();
if (lifted1 && !lifted2)
{
return BetterResult.Right;
}
else if (!lifted1 && lifted2)
{
return BetterResult.Left;
}
}
// Always prefer operators with val parameters over operators with in parameters:
BetterResult valOverInPreference;
if (op1.LeftRefKind == RefKind.None && op2.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Left;
}
else if (op2.LeftRefKind == RefKind.None && op1.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Right;
}
else
{
valOverInPreference = BetterResult.Neither;
}
if (op1.RightRefKind == RefKind.None && op2.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Right)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Left;
}
}
else if (op2.RightRefKind == RefKind.None && op1.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Left)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Right;
}
}
return valOverInPreference;
}
private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
TypeSymbol op1Left, op1Right, op2Left, op2Right;
if ((object)op1.Method != null)
{
var p = op1.Method.OriginalDefinition.GetParameters();
op1Left = p[0].Type;
op1Right = p[1].Type;
if (op1.Kind.IsLifted())
{
op1Left = MakeNullable(op1Left);
op1Right = MakeNullable(op1Right);
}
}
else
{
op1Left = op1.LeftType;
op1Right = op1.RightType;
}
if ((object)op2.Method != null)
{
var p = op2.Method.OriginalDefinition.GetParameters();
op2Left = p[0].Type;
op2Right = p[1].Type;
if (op2.Kind.IsLifted())
{
op2Left = MakeNullable(op2Left);
op2Right = MakeNullable(op2Right);
}
}
else
{
op2Left = op2.LeftType;
op2Right = op2.RightType;
}
var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();
uninst1.Add(op1Left);
uninst1.Add(op1Right);
uninst2.Add(op2Left);
uninst2.Add(op2Right);
BetterResult result = MoreSpecificType(uninst1, uninst2, ref useSiteInfo);
uninst1.Free();
uninst2.Free();
return result;
}
[Conditional("DEBUG")]
private static void AssertNotChecked(BinaryOperatorKind kind)
{
Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked. Consider using .Operator() to mask.");
}
}
}
| // Licensed to the .NET Foundation under one or more 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.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class OverloadResolution
{
public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We can do a table lookup for well-known problems in overload resolution.
BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result);
if (result.Results.Count > 0)
{
return;
}
BinaryOperatorOverloadResolution_NoEasyOut(kind, left, right, result, ref useSiteInfo);
}
internal void BinaryOperatorOverloadResolution_EasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// SPEC: An operation of the form x&&y or x||y is processed by applying overload resolution
// SPEC: as if the operation was written x&y or x|y.
// SPEC VIOLATION: For compatibility with Dev11, do not apply this rule to built-in conversions.
BinaryOperatorKind underlyingKind = kind & ~BinaryOperatorKind.Logical;
BinaryOperatorEasyOut(underlyingKind, left, right, result);
}
internal void BinaryOperatorOverloadResolution_NoEasyOut(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(result.Results.Count == 0);
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// SPEC: An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// SPEC: The set of candidate user-defined operators provided by the types (if any) of x and y for the
// SPEC operation operator op(x, y) is determined.
TypeSymbol leftOperatorSourceOpt = left.Type?.StrippedType();
TypeSymbol rightOperatorSourceOpt = right.Type?.StrippedType();
bool leftSourceIsInterface = leftOperatorSourceOpt?.IsInterfaceType() == true;
bool rightSourceIsInterface = rightOperatorSourceOpt?.IsInterfaceType() == true;
// The following is a slight rewording of the specification to emphasize that not all
// operands of a binary operation need to have a type.
// TODO (tomat): The spec needs to be updated to use identity conversion instead of type equality.
// Spec 7.3.4 Binary operator overload resolution:
// An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
// The set of candidate user-defined operators provided by the types (if any) of x and y for the
// operation operator op(x, y) is determined. The set consists of the union of the candidate operators
// provided by the type of x (if any) and the candidate operators provided by the type of y (if any),
// each determined using the rules of 7.3.5. Candidate operators only occur in the combined set once.
// From https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-06-27.md:
// - We only even look for operator implementations in interfaces if one of the operands has a type that is
// an interface or a type parameter with a non-empty effective base interface list.
// - We should look at operators from classes first, in order to avoid breaking changes.
// Only if there are no applicable user-defined operators from classes will we look in interfaces.
// If there aren't any there either, we go to built-ins.
// - If we find an applicable candidate in an interface, that candidate shadows all applicable operators in
// base interfaces: we stop looking.
bool hadApplicableCandidates = false;
// In order to preserve backward compatibility, at first we ignore interface sources.
if ((object)leftOperatorSourceOpt != null && !leftSourceIsInterface)
{
hadApplicableCandidates = GetUserDefinedOperators(kind, leftOperatorSourceOpt, left, right, result.Results, ref useSiteInfo);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
}
if ((object)rightOperatorSourceOpt != null && !rightSourceIsInterface && !rightOperatorSourceOpt.Equals(leftOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedOperators(kind, rightOperatorSourceOpt, left, right, rightOperators, ref useSiteInfo))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
// If there are no applicable candidates in classes / stuctures, try with interface sources.
if (!hadApplicableCandidates)
{
result.Results.Clear();
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var lookedInInterfaces = PooledDictionary<TypeSymbol, bool>.GetInstance();
TypeSymbol firstOperatorSourceOpt;
TypeSymbol secondOperatorSourceOpt;
bool firstSourceIsInterface;
bool secondSourceIsInterface;
// Always start lookup from a type parameter. This ensures that regardless of the order we always pick up constrained type for
// each distinct candidate operator.
if (leftOperatorSourceOpt is null || (leftOperatorSourceOpt is not TypeParameterSymbol && rightOperatorSourceOpt is TypeParameterSymbol))
{
firstOperatorSourceOpt = rightOperatorSourceOpt;
secondOperatorSourceOpt = leftOperatorSourceOpt;
firstSourceIsInterface = rightSourceIsInterface;
secondSourceIsInterface = leftSourceIsInterface;
}
else
{
firstOperatorSourceOpt = leftOperatorSourceOpt;
secondOperatorSourceOpt = rightOperatorSourceOpt;
firstSourceIsInterface = leftSourceIsInterface;
secondSourceIsInterface = rightSourceIsInterface;
}
hadApplicableCandidates = GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
firstOperatorSourceOpt, firstSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, result.Results);
if (!hadApplicableCandidates)
{
result.Results.Clear();
}
if ((object)secondOperatorSourceOpt != null && !secondOperatorSourceOpt.Equals(firstOperatorSourceOpt))
{
var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
if (GetUserDefinedBinaryOperatorsFromInterfaces(kind, name,
secondOperatorSourceOpt, secondSourceIsInterface, left, right, ref useSiteInfo, lookedInInterfaces, rightOperators))
{
hadApplicableCandidates = true;
AddDistinctOperators(result.Results, rightOperators);
}
rightOperators.Free();
}
lookedInInterfaces.Free();
}
// SPEC: If the set of candidate user-defined operators is not empty, then this becomes the set of candidate
// SPEC: operators for the operation. Otherwise, the predefined binary operator op implementations, including
// SPEC: their lifted forms, become the set of candidate operators for the operation.
// Note that the native compiler has a bug in its binary operator overload resolution involving
// lifted built-in operators. The spec says that we should add the lifted and unlifted operators
// to a candidate set, eliminate the inapplicable operators, and then choose the best of what is left.
// The lifted operator is defined as, say int? + int? --> int?. That is not what the native compiler
// does. The native compiler, rather, effectively says that there are *three* lifted operators:
// int? + int? --> int?, int + int? --> int? and int? + int --> int?, and it chooses the best operator
// amongst those choices.
//
// This is a subtle difference; most of the time all it means is that we generate better code because we
// skip an unnecessary operand conversion to int? when adding int to int?. But some of the time it
// means that a different user-defined conversion is chosen than the one you would expect, if the
// operand has a user-defined conversion to both int and int?.
//
// Roslyn matches the specification and takes the break from the native compiler.
Debug.Assert((result.Results.Count == 0) != hadApplicableCandidates);
if (!hadApplicableCandidates)
{
result.Results.Clear();
GetAllBuiltInOperators(kind, left, right, result.Results, ref useSiteInfo);
}
// SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators to select the best
// SPEC: operator with respect to the argument list (x, y), and this operator becomes the result of the overload
// SPEC: resolution process. If overload resolution fails to select a single best operator, a binding-time
// SPEC: error occurs.
BinaryOperatorOverloadResolution(left, right, result, ref useSiteInfo);
}
private bool GetUserDefinedBinaryOperatorsFromInterfaces(BinaryOperatorKind kind, string name,
TypeSymbol operatorSourceOpt, bool sourceIsInterface,
BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
Dictionary<TypeSymbol, bool> lookedInInterfaces, ArrayBuilder<BinaryOperatorAnalysisResult> candidates)
{
Debug.Assert(candidates.Count == 0);
if ((object)operatorSourceOpt == null)
{
return false;
}
bool hadUserDefinedCandidateFromInterfaces = false;
ImmutableArray<NamedTypeSymbol> interfaces = default;
TypeSymbol constrainedToTypeOpt = null;
if (sourceIsInterface)
{
if (!lookedInInterfaces.TryGetValue(operatorSourceOpt, out _))
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, (NamedTypeSymbol)operatorSourceOpt, kind, name, operators);
hadUserDefinedCandidateFromInterfaces = CandidateOperators(operators, left, right, candidates, ref useSiteInfo);
operators.Free();
Debug.Assert(hadUserDefinedCandidateFromInterfaces == candidates.Any(r => r.IsValid));
lookedInInterfaces.Add(operatorSourceOpt, hadUserDefinedCandidateFromInterfaces);
if (!hadUserDefinedCandidateFromInterfaces)
{
candidates.Clear();
interfaces = operatorSourceOpt.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
}
}
else if (operatorSourceOpt.IsTypeParameter())
{
interfaces = ((TypeParameterSymbol)operatorSourceOpt).AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
constrainedToTypeOpt = operatorSourceOpt;
}
if (!interfaces.IsDefaultOrEmpty)
{
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
var results = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
var shadowedInterfaces = PooledHashSet<NamedTypeSymbol>.GetInstance();
foreach (NamedTypeSymbol @interface in interfaces)
{
if ([email protected])
{
// this code could be reachable in error situations
continue;
}
if (shadowedInterfaces.Contains(@interface))
{
// this interface is "shadowed" by a derived interface
continue;
}
if (lookedInInterfaces.TryGetValue(@interface, out bool hadUserDefinedCandidate))
{
if (hadUserDefinedCandidate)
{
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo));
}
// no need to perform another lookup in this interface
continue;
}
operators.Clear();
results.Clear();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt, @interface, kind, name, operators);
hadUserDefinedCandidate = CandidateOperators(operators, left, right, results, ref useSiteInfo);
Debug.Assert(hadUserDefinedCandidate == results.Any(r => r.IsValid));
lookedInInterfaces.Add(@interface, hadUserDefinedCandidate);
if (hadUserDefinedCandidate)
{
hadUserDefinedCandidateFromInterfaces = true;
candidates.AddRange(results);
// this interface "shadows" all its base interfaces
shadowedInterfaces.AddAll(@interface.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo));
}
}
operators.Free();
results.Free();
shadowedInterfaces.Free();
}
return hadUserDefinedCandidateFromInterfaces;
}
private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
default:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType));
break;
}
}
private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> operators, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
break;
default:
// Unhandled bin op kind in get delegate operation
throw ExceptionUtilities.UnexpectedValue(kind);
}
var leftType = left.Type;
var leftDelegate = (object)leftType != null && leftType.IsDelegateType();
var rightType = right.Type;
var rightDelegate = (object)rightType != null && rightType.IsDelegateType();
// If no operands have delegate types then add nothing.
if (!leftDelegate && !rightDelegate)
{
// Even though neither left nor right type is a delegate type,
// both types might have implicit conversions to System.Delegate type.
// Spec 7.10.8: Delegate equality operators:
// Every delegate type implicitly provides the following predefined comparison operators:
// bool operator ==(System.Delegate x, System.Delegate y)
// bool operator !=(System.Delegate x, System.Delegate y)
switch (OperatorKindExtensions.Operator(kind))
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
TypeSymbol systemDelegateType = _binder.Compilation.GetSpecialType(SpecialType.System_Delegate);
systemDelegateType.AddUseSiteInfo(ref useSiteInfo);
if (Conversions.ClassifyImplicitConversionFromExpression(left, systemDelegateType, ref useSiteInfo).IsValid &&
Conversions.ClassifyImplicitConversionFromExpression(right, systemDelegateType, ref useSiteInfo).IsValid)
{
AddDelegateOperation(kind, systemDelegateType, operators);
}
break;
}
return;
}
// We might have a situation like
//
// Func<string> + Func<object>
//
// in which case overload resolution should consider both
//
// Func<string> + Func<string>
// Func<object> + Func<object>
//
// are candidates (and it will pick Func<object>). Similarly,
// we might have something like:
//
// Func<object> + Func<dynamic>
//
// in which case neither candidate is better than the other,
// resulting in an error.
//
// We could as an optimization say that if you are adding two completely
// dissimilar delegate types D1 and D2, that neither is added to the candidate
// set because neither can possibly be applicable, but let's not go there.
// Let's just add them to the set and let overload resolution (and the
// error recovery heuristics) have at the real candidate set.
//
// However, we will take a spec violation for this scenario:
//
// SPEC VIOLATION:
//
// Technically the spec implies that we ought to be able to compare
//
// Func<int> x = whatever;
// bool y = x == ()=>1;
//
// The native compiler does not allow this. I see no
// reason why we ought to allow this. However, a good question is whether
// the violation ought to be here, where we are determining the operator
// candidate set, or in overload resolution where we are determining applicability.
// In the native compiler we did it during candidate set determination,
// so let's stick with that.
if (leftDelegate && rightDelegate)
{
// They are both delegate types. Add them both if they are different types.
AddDelegateOperation(kind, leftType, operators);
// There is no reason why we can't compare instances of delegate types that are identity convertible.
// We can't perform + or - operation on them since it is not clear what the return type of such operation should be.
bool useIdentityConversion = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (!(useIdentityConversion ? Conversions.HasIdentityConversion(leftType, rightType) : leftType.Equals(rightType)))
{
AddDelegateOperation(kind, rightType, operators);
}
return;
}
// One of them is a delegate, the other is not.
TypeSymbol delegateType = leftDelegate ? leftType : rightType;
BoundExpression nonDelegate = leftDelegate ? right : left;
if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)
&& nonDelegate.Kind == BoundKind.UnboundLambda)
{
return;
}
AddDelegateOperation(kind, delegateType, operators);
}
private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)enumType != null);
AssertNotChecked(kind);
if (!enumType.IsValidEnumType())
{
return;
}
var underlying = enumType.GetEnumUnderlyingType();
Debug.Assert((object)underlying != null);
Debug.Assert(underlying.SpecialType != SpecialType.None);
var nullable = Compilation.GetSpecialType(SpecialType.System_Nullable_T);
var nullableEnum = nullable.Construct(enumType);
var nullableUnderlying = nullable.Construct(underlying);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, underlying, enumType, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, nullableEnum, nullableUnderlying, nullableEnum));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, nullableUnderlying, nullableEnum, nullableEnum));
break;
case BinaryOperatorKind.Subtraction:
if (Strict)
{
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum));
}
else
{
// SPEC VIOLATION:
// The native compiler has bugs in overload resolution involving binary operator- for enums,
// which we duplicate by hardcoding Priority values among the operators. When present on both
// methods being compared during overload resolution, Priority values are used to decide between
// two candidates (instead of the usual language-specified rules).
bool isExactSubtraction = TypeSymbol.Equals(right.Type?.StrippedType(), underlying, TypeCompareKind.ConsiderEverything2);
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying)
{ Priority = 2 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType)
{ Priority = isExactSubtraction ? 1 : 3 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying)
{ Priority = 12 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum)
{ Priority = isExactSubtraction ? 11 : 13 });
// Due to a bug, the native compiler allows "underlying - enum", so Roslyn does as well.
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, underlying, enumType, enumType)
{ Priority = 4 });
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, nullableUnderlying, nullableEnum, nullableEnum)
{ Priority = 14 });
}
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var boolean = Compilation.GetSpecialType(SpecialType.System_Boolean);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, boolean));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, boolean));
break;
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, nullableEnum));
break;
}
}
private void GetPointerArithmeticOperators(
BinaryOperatorKind kind,
PointerTypeSymbol pointerType,
ArrayBuilder<BinaryOperatorSignature> operators)
{
Debug.Assert((object)pointerType != null);
AssertNotChecked(kind);
switch (kind)
{
case BinaryOperatorKind.Addition:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType, pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType, pointerType));
break;
case BinaryOperatorKind.Subtraction:
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64)));
break;
}
}
private void GetPointerComparisonOperators(
BinaryOperatorKind kind,
ArrayBuilder<BinaryOperatorSignature> operators)
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
var voidPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(Compilation.GetSpecialType(SpecialType.System_Void)));
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, voidPointerType, voidPointerType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
break;
}
}
private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
// First take some easy outs:
switch (kind)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
case BinaryOperatorKind.Remainder:
case BinaryOperatorKind.RightShift:
case BinaryOperatorKind.LeftShift:
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
return;
}
var leftType = left.Type;
if ((object)leftType != null)
{
leftType = leftType.StrippedType();
}
var rightType = right.Type;
if ((object)rightType != null)
{
rightType = rightType.StrippedType();
}
bool useIdentityConversion;
switch (kind)
{
case BinaryOperatorKind.And:
case BinaryOperatorKind.Or:
case BinaryOperatorKind.Xor:
// These operations are ambiguous on non-equal identity-convertible types -
// it's not clear what the resulting type of the operation should be:
// C<?>.E operator +(C<dynamic>.E x, C<object>.E y)
useIdentityConversion = false;
break;
case BinaryOperatorKind.Addition:
// Addition only accepts a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// E operator +(E x, U y)
// E operator +(U x, E y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Subtraction:
// Subtraction either returns underlying type or only accept a single enum type, so operations on non-equal identity-convertible types are not ambiguous.
// U operator –(E x, E y)
// E operator –(E x, U y)
useIdentityConversion = true;
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
// Relational operations return Boolean, so operations on non-equal identity-convertible types are not ambiguous.
// Boolean operator op(C<dynamic>.E, C<object>.E)
useIdentityConversion = true;
break;
default:
// Unhandled bin op kind in get enum operations
throw ExceptionUtilities.UnexpectedValue(kind);
}
if ((object)leftType != null)
{
GetEnumOperation(kind, leftType, left, right, results);
}
if ((object)rightType != null && ((object)leftType == null || !(useIdentityConversion ? Conversions.HasIdentityConversion(rightType, leftType) : rightType.Equals(leftType))))
{
GetEnumOperation(kind, rightType, left, right, results);
}
}
private void GetPointerOperators(
BinaryOperatorKind kind,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorSignature> results)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
AssertNotChecked(kind);
var leftType = left.Type as PointerTypeSymbol;
var rightType = right.Type as PointerTypeSymbol;
if ((object)leftType != null)
{
GetPointerArithmeticOperators(kind, leftType, results);
}
// The only arithmetic operator that is applicable on two distinct pointer types is
// long operator –(T* x, T* y)
// This operator returns long and so it's not ambiguous to apply it on T1 and T2 that are identity convertible to each other.
if ((object)rightType != null && ((object)leftType == null || !Conversions.HasIdentityConversion(rightType, leftType)))
{
GetPointerArithmeticOperators(kind, rightType, results);
}
if ((object)leftType != null || (object)rightType != null || left.Type is FunctionPointerTypeSymbol || right.Type is FunctionPointerTypeSymbol)
{
// The pointer comparison operators are all "void* OP void*".
GetPointerComparisonOperators(kind, results);
}
}
private void GetAllBuiltInOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// Strip the "checked" off; the checked-ness of the context does not affect which built-in operators
// are applicable.
kind = kind.OperatorWithLogical();
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
if (isEquality && useOnlyReferenceEquality(Conversions, left, right, ref useSiteInfo))
{
// As a special case, if the reference equality operator is applicable (and it
// is not a string or delegate) we do not check any other operators. This patches
// what is otherwise a flaw in the language specification. See 11426.
GetReferenceEquality(kind, operators);
}
else
{
this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators, skipNativeIntegerOperators: !left.Type.IsNativeIntegerOrNullableNativeIntegerType() && !right.Type.IsNativeIntegerOrNullableNativeIntegerType());
// SPEC 7.3.4: For predefined enum and delegate operators, the only operators
// considered are those defined by an enum or delegate type that is the binding
//-time type of one of the operands.
GetDelegateOperations(kind, left, right, operators, ref useSiteInfo);
GetEnumOperations(kind, left, right, operators);
// We similarly limit pointer operator candidates considered.
GetPointerOperators(kind, left, right, operators);
}
CandidateOperators(operators, left, right, results, ref useSiteInfo);
operators.Free();
static bool useOnlyReferenceEquality(Conversions conversions, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We consider the `null` literal, but not the `default` literal, since the latter does not require a reference equality
return
BuiltInOperators.IsValidObjectEquality(conversions, left.Type, left.IsLiteralNull(), leftIsDefault: false, right.Type, right.IsLiteralNull(), rightIsDefault: false, ref useSiteInfo) &&
((object)left.Type == null || (!left.Type.IsDelegateType() && left.Type.SpecialType != SpecialType.System_String && left.Type.SpecialType != SpecialType.System_Delegate)) &&
((object)right.Type == null || (!right.Type.IsDelegateType() && right.Type.SpecialType != SpecialType.System_String && right.Type.SpecialType != SpecialType.System_Delegate));
}
}
private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators)
{
var @object = Compilation.GetSpecialType(SpecialType.System_Object);
operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, @object, @object, Compilation.GetSpecialType(SpecialType.System_Boolean)));
}
private bool CandidateOperators(
ArrayBuilder<BinaryOperatorSignature> operators,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool hadApplicableCandidate = false;
foreach (var op in operators)
{
var convLeft = Conversions.ClassifyConversionFromExpression(left, op.LeftType, ref useSiteInfo);
var convRight = Conversions.ClassifyConversionFromExpression(right, op.RightType, ref useSiteInfo);
if (convLeft.IsImplicit && convRight.IsImplicit)
{
results.Add(BinaryOperatorAnalysisResult.Applicable(op, convLeft, convRight));
hadApplicableCandidate = true;
}
else
{
results.Add(BinaryOperatorAnalysisResult.Inapplicable(op, convLeft, convRight));
}
}
return hadApplicableCandidate;
}
private static void AddDistinctOperators(ArrayBuilder<BinaryOperatorAnalysisResult> result, ArrayBuilder<BinaryOperatorAnalysisResult> additionalOperators)
{
int initialCount = result.Count;
foreach (var op in additionalOperators)
{
bool equivalentToExisting = false;
for (int i = 0; i < initialCount; i++)
{
var existingSignature = result[i].Signature;
Debug.Assert(op.Signature.Kind.Operator() == existingSignature.Kind.Operator());
// Return types must match exactly, parameters might match modulo identity conversion.
if (op.Signature.Kind == existingSignature.Kind && // Easy out
equalsIgnoringNullable(op.Signature.ReturnType, existingSignature.ReturnType) &&
equalsIgnoringNullableAndDynamic(op.Signature.LeftType, existingSignature.LeftType) &&
equalsIgnoringNullableAndDynamic(op.Signature.RightType, existingSignature.RightType) &&
equalsIgnoringNullableAndDynamic(op.Signature.Method.ContainingType, existingSignature.Method.ContainingType))
{
equivalentToExisting = true;
break;
}
}
if (!equivalentToExisting)
{
result.Add(op);
}
}
static bool equalsIgnoringNullable(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions);
static bool equalsIgnoringNullableAndDynamic(TypeSymbol a, TypeSymbol b) => a.Equals(b, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreDynamic);
}
private bool GetUserDefinedOperators(
BinaryOperatorKind kind,
TypeSymbol type0,
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> results,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(results.Count == 0);
if ((object)type0 == null || OperatorFacts.DefinitelyHasNoUserDefinedOperators(type0))
{
return false;
}
// Spec 7.3.5 Candidate user-defined operators
// SPEC: Given a type T and an operation operator op(A), where op is an overloadable
// SPEC: operator and A is an argument list, the set of candidate user-defined operators
// SPEC: provided by T for operator op(A) is determined as follows:
// SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type,
// SPEC: otherwise T0 is equal to T.
// (The caller has already passed in the stripped type.)
// SPEC: For all operator op declarations in T0 and all lifted forms of such operators,
// SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument
// SPEC: list A, then the set of candidate operators consists of all such applicable
// SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
// SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate
// SPEC: operators provided by the direct base class of T0, or the effective base class of
// SPEC: T0 if T0 is a type parameter.
string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
bool hadApplicableCandidates = false;
NamedTypeSymbol current = type0 as NamedTypeSymbol;
if ((object)current == null)
{
current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
if ((object)current == null && type0.IsTypeParameter())
{
current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteInfo);
}
for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
operators.Clear();
GetUserDefinedBinaryOperatorsFromType(constrainedToTypeOpt: null, current, kind, name, operators);
results.Clear();
if (CandidateOperators(operators, left, right, results, ref useSiteInfo))
{
hadApplicableCandidates = true;
break;
}
}
operators.Free();
Debug.Assert(hadApplicableCandidates == results.Any(r => r.IsValid));
return hadApplicableCandidates;
}
private void GetUserDefinedBinaryOperatorsFromType(
TypeSymbol constrainedToTypeOpt,
NamedTypeSymbol type,
BinaryOperatorKind kind,
string name,
ArrayBuilder<BinaryOperatorSignature> operators)
{
foreach (MethodSymbol op in type.GetOperators(name))
{
// If we're in error recovery, we might have bad operators. Just ignore it.
if (op.ParameterCount != 2 || op.ReturnsVoid)
{
continue;
}
TypeSymbol leftOperandType = op.GetParameterType(0);
TypeSymbol rightOperandType = op.GetParameterType(1);
TypeSymbol resultType = op.ReturnType;
operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op, constrainedToTypeOpt));
LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind);
if (lifting == LiftingResult.LiftOperandsAndResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op, constrainedToTypeOpt));
}
else if (lifting == LiftingResult.LiftOperandsButNotResult)
{
operators.Add(new BinaryOperatorSignature(
BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op, constrainedToTypeOpt));
}
}
}
private enum LiftingResult
{
NotLifted,
LiftOperandsAndResult,
LiftOperandsButNotResult
}
private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind)
{
// SPEC: For the binary operators + - * / % & | ^ << >> a lifted form of the
// SPEC: operator exists if the operand and result types are all non-nullable
// SPEC: value types. The lifted form is constructed by adding a single ?
// SPEC: modifier to each operand and result type.
//
// SPEC: For the equality operators == != a lifted form of the operator exists
// SPEC: if the operand types are both non-nullable value types and if the
// SPEC: result type is bool. The lifted form is constructed by adding
// SPEC: a single ? modifier to each operand type.
//
// SPEC: For the relational operators > < >= <= a lifted form of the
// SPEC: operator exists if the operand types are both non-nullable value
// SPEC: types and if the result type is bool. The lifted form is
// SPEC: constructed by adding a single ? modifier to each operand type.
if (!left.IsValueType ||
left.IsNullableType() ||
!right.IsValueType ||
right.IsNullableType())
{
return LiftingResult.NotLifted;
}
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// Spec violation: can't lift unless the types match.
// The spec doesn't require this, but dev11 does and it reduces ambiguity in some cases.
if (!TypeSymbol.Equals(left, right, TypeCompareKind.ConsiderEverything2)) return LiftingResult.NotLifted;
goto case BinaryOperatorKind.GreaterThan;
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return result.SpecialType == SpecialType.System_Boolean ?
LiftingResult.LiftOperandsButNotResult :
LiftingResult.NotLifted;
default:
return result.IsValueType && !result.IsNullableType() ?
LiftingResult.LiftOperandsAndResult :
LiftingResult.NotLifted;
}
}
// Takes a list of candidates and mutates the list to throw out the ones that are worse than
// another applicable candidate.
private void BinaryOperatorOverloadResolution(
BoundExpression left,
BoundExpression right,
BinaryOperatorOverloadResolutionResult result,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// SPEC: Given the set of applicable candidate function members, the best function member in that set is located.
// SPEC: If the set contains only one function member, then that function member is the best function member.
if (result.SingleValid())
{
return;
}
// SPEC: Otherwise, the best function member is the one function member that is better than all other function
// SPEC: members with respect to the given argument list, provided that each function member is compared to all
// SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is
// SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time
// SPEC: error occurs.
var candidates = result.Results;
// Try to find a single best candidate
int bestIndex = GetTheBestCandidateIndex(left, right, candidates, ref useSiteInfo);
if (bestIndex != -1)
{
// Mark all other candidates as worse
for (int index = 0; index < candidates.Count; ++index)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex)
{
candidates[index] = candidates[index].Worse();
}
}
return;
}
for (int i = 1; i < candidates.Count; ++i)
{
if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Is this applicable operator better than every other applicable method?
for (int j = 0; j < i; ++j)
{
if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, left, right, ref useSiteInfo);
if (better == BetterResult.Left)
{
candidates[j] = candidates[j].Worse();
}
else if (better == BetterResult.Right)
{
candidates[i] = candidates[i].Worse();
}
}
}
}
private int GetTheBestCandidateIndex(
BoundExpression left,
BoundExpression right,
ArrayBuilder<BinaryOperatorAnalysisResult> candidates,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
int currentBestIndex = -1;
for (int index = 0; index < candidates.Count; index++)
{
if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable)
{
continue;
}
// Assume that the current candidate is the best if we don't have any
if (currentBestIndex == -1)
{
currentBestIndex = index;
}
else
{
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteInfo);
if (better == BetterResult.Right)
{
// The current best is worse
currentBestIndex = index;
}
else if (better != BetterResult.Left)
{
// The current best is not better
currentBestIndex = -1;
}
}
}
// Make sure that every candidate up to the current best is worse
for (int index = 0; index < currentBestIndex; index++)
{
if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable)
{
continue;
}
var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteInfo);
if (better != BetterResult.Left)
{
// The current best is not better
return -1;
}
}
return currentBestIndex;
}
private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
// We use Priority as a tie-breaker to help match native compiler bugs.
Debug.Assert(op1.Priority.HasValue == op2.Priority.HasValue);
if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault())
{
return (op1.Priority.GetValueOrDefault() < op2.Priority.GetValueOrDefault()) ? BetterResult.Left : BetterResult.Right;
}
BetterResult leftBetter = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteInfo);
BetterResult rightBetter = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteInfo);
// SPEC: Mp is defined to be a better function member than Mq if:
// SPEC: * For each argument, the implicit conversion from Ex to Qx is not better than
// SPEC: the implicit conversion from Ex to Px, and
// SPEC: * For at least one argument, the conversion from Ex to Px is better than the
// SPEC: conversion from Ex to Qx.
// If that is hard to follow, consult this handy chart:
// op1.Left vs op2.Left op1.Right vs op2.Right result
// -----------------------------------------------------------
// op1 better op1 better op1 better
// op1 better neither better op1 better
// op1 better op2 better neither better
// neither better op1 better op1 better
// neither better neither better neither better
// neither better op2 better op2 better
// op2 better op1 better neither better
// op2 better neither better op2 better
// op2 better op2 better op2 better
if (leftBetter == BetterResult.Left && rightBetter != BetterResult.Right ||
leftBetter != BetterResult.Right && rightBetter == BetterResult.Left)
{
return BetterResult.Left;
}
if (leftBetter == BetterResult.Right && rightBetter != BetterResult.Left ||
leftBetter != BetterResult.Left && rightBetter == BetterResult.Right)
{
return BetterResult.Right;
}
// There was no better member on the basis of conversions. Go to the tiebreaking round.
// SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi
// SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules
// SPEC: are applied:
if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) &&
Conversions.HasIdentityConversion(op1.RightType, op2.RightType))
{
// NOTE: The native compiler does not follow these rules; effectively, the native
// compiler checks for liftedness first, and then for specificity. For example:
// struct S<T> where T : struct {
// public static bool operator +(S<T> x, int y) { return true; }
// public static bool? operator +(S<T>? x, int? y) { return false; }
// }
//
// bool? b = new S<int>?() + new int?();
//
// should reason as follows: the two applicable operators are the lifted
// form of the first operator and the unlifted second operator. The
// lifted form of the first operator is *more specific* because int?
// is more specific than T?. Therefore it should win. In fact the
// native compiler chooses the second operator, because it is unlifted.
//
// Roslyn follows the spec rules; if we decide to change the spec to match
// the native compiler, or decide to change Roslyn to match the native
// compiler, we should change the order of the checks here.
// SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq.
BetterResult result = MoreSpecificOperator(op1, op2, ref useSiteInfo);
if (result == BetterResult.Left || result == BetterResult.Right)
{
return result;
}
// SPEC: If one member is a non-lifted operator and the other is a lifted operator,
// SPEC: the non-lifted one is better.
bool lifted1 = op1.Kind.IsLifted();
bool lifted2 = op2.Kind.IsLifted();
if (lifted1 && !lifted2)
{
return BetterResult.Right;
}
else if (!lifted1 && lifted2)
{
return BetterResult.Left;
}
}
// Always prefer operators with val parameters over operators with in parameters:
BetterResult valOverInPreference;
if (op1.LeftRefKind == RefKind.None && op2.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Left;
}
else if (op2.LeftRefKind == RefKind.None && op1.LeftRefKind == RefKind.In)
{
valOverInPreference = BetterResult.Right;
}
else
{
valOverInPreference = BetterResult.Neither;
}
if (op1.RightRefKind == RefKind.None && op2.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Right)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Left;
}
}
else if (op2.RightRefKind == RefKind.None && op1.RightRefKind == RefKind.In)
{
if (valOverInPreference == BetterResult.Left)
{
return BetterResult.Neither;
}
else
{
valOverInPreference = BetterResult.Right;
}
}
return valOverInPreference;
}
private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
TypeSymbol op1Left, op1Right, op2Left, op2Right;
if ((object)op1.Method != null)
{
var p = op1.Method.OriginalDefinition.GetParameters();
op1Left = p[0].Type;
op1Right = p[1].Type;
if (op1.Kind.IsLifted())
{
op1Left = MakeNullable(op1Left);
op1Right = MakeNullable(op1Right);
}
}
else
{
op1Left = op1.LeftType;
op1Right = op1.RightType;
}
if ((object)op2.Method != null)
{
var p = op2.Method.OriginalDefinition.GetParameters();
op2Left = p[0].Type;
op2Right = p[1].Type;
if (op2.Kind.IsLifted())
{
op2Left = MakeNullable(op2Left);
op2Right = MakeNullable(op2Right);
}
}
else
{
op2Left = op2.LeftType;
op2Right = op2.RightType;
}
var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();
uninst1.Add(op1Left);
uninst1.Add(op1Right);
uninst2.Add(op2Left);
uninst2.Add(op2Right);
BetterResult result = MoreSpecificType(uninst1, uninst2, ref useSiteInfo);
uninst1.Free();
uninst2.Free();
return result;
}
[Conditional("DEBUG")]
private static void AssertNotChecked(BinaryOperatorKind kind)
{
Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked. Consider using .Operator() to mask.");
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/TestUtilities/Workspaces/NoCompilationContentTypeLanguageService.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 Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[ExportLanguageService(typeof(IContentTypeLanguageService), NoCompilationConstants.LanguageName, ServiceLayer.Test), Shared, PartNotDiscoverable]
internal class NoCompilationContentTypeLanguageService : IContentTypeLanguageService
{
private readonly IContentTypeRegistryService _contentTypeRegistry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public NoCompilationContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry)
=> _contentTypeRegistry = contentTypeRegistry;
public IContentType GetDefaultContentType()
=> _contentTypeRegistry.GetContentType(NoCompilationConstants.LanguageName);
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[ExportLanguageService(typeof(IContentTypeLanguageService), NoCompilationConstants.LanguageName, ServiceLayer.Test), Shared, PartNotDiscoverable]
internal class NoCompilationContentTypeLanguageService : IContentTypeLanguageService
{
private readonly IContentTypeRegistryService _contentTypeRegistry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public NoCompilationContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry)
=> _contentTypeRegistry = contentTypeRegistry;
public IContentType GetDefaultContentType()
=> _contentTypeRegistry.GetContentType(NoCompilationConstants.LanguageName);
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordInequalityOperator.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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows:
///
/// For record class:
/// public static bool operator==(R? left, R? right)
/// => (object) left == right || ((object)left != null && left.Equals(right));
/// public static bool operator !=(R? left, R? right)
/// => !(left == right);
///
/// For record struct:
/// public static bool operator==(R left, R right)
/// => left.Equals(right);
/// public static bool operator !=(R left, R right)
/// => !(left == right);
///
///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>).
///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly.
/// </summary>
internal sealed class SynthesizedRecordInequalityOperator : SynthesizedRecordEqualityOperatorBase
{
public SynthesizedRecordInequalityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.InequalityOperatorName, memberOffset, diagnostics)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
try
{
// => !(left == right);
F.CloseMethod(F.Block(F.Return(F.Not(F.Call(receiver: null, ContainingType.GetMembers(WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(),
F.Parameter(Parameters[0]), F.Parameter(Parameters[1]))))));
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
F.CloseMethod(F.ThrowNull());
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows:
///
/// For record class:
/// public static bool operator==(R? left, R? right)
/// => (object) left == right || ((object)left != null && left.Equals(right));
/// public static bool operator !=(R? left, R? right)
/// => !(left == right);
///
/// For record struct:
/// public static bool operator==(R left, R right)
/// => left.Equals(right);
/// public static bool operator !=(R left, R right)
/// => !(left == right);
///
///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>).
///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly.
/// </summary>
internal sealed class SynthesizedRecordInequalityOperator : SynthesizedRecordEqualityOperatorBase
{
public SynthesizedRecordInequalityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.InequalityOperatorName, memberOffset, diagnostics)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
try
{
// => !(left == right);
F.CloseMethod(F.Block(F.Return(F.Not(F.Call(receiver: null, ContainingType.GetMembers(WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(),
F.Parameter(Parameters[0]), F.Parameter(Parameters[1]))))));
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
F.CloseMethod(F.ThrowNull());
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int a = 1)
{
M();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int x, int a = 1)
{
M(1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x = 2)
{
M()
M(2);
M(x: 2);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, int x = 2)
{
M()
M(x: 2);
M(x: 2);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(params int[] p)
{
M();
M(1);
M(1, 2);
M(1, 2, 3);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, params int[] p)
{
M();
M(p: new int[] { 1 });
M(p: new int[] { 1, 2 });
M(p: new int[] { 1, 2, 3 });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor()
{
var markup = @"
[Some(1, 2, 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute$$(int a, int b, int y = 4)
{
}
}";
var permutation = new[] {
new AddedParameterOrExistingIndex(0),
new AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"),
new AddedParameterOrExistingIndex(2)};
var updatedCode = @"
[Some(1, 2, y: 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute(int a, int b, int x = 3, int y = 4)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int a = 1)
{
M();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int x, int a = 1)
{
M(1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x = 2)
{
M()
M(2);
M(x: 2);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, int x = 2)
{
M()
M(x: 2);
M(x: 2);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(params int[] p)
{
M();
M(1);
M(1, 2);
M(1, 2, 3);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, params int[] p)
{
M();
M(p: new int[] { 1 });
M(p: new int[] { 1, 2 });
M(p: new int[] { 1, 2, 3 });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor()
{
var markup = @"
[Some(1, 2, 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute$$(int a, int b, int y = 4)
{
}
}";
var permutation = new[] {
new AddedParameterOrExistingIndex(0),
new AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"),
new AddedParameterOrExistingIndex(2)};
var updatedCode = @"
[Some(1, 2, y: 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute(int a, int b, int x = 3, int y = 4)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.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.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.Test.Utilities
{
[UseExportProvider]
public abstract class AbstractLanguageServerProtocolTests
{
// TODO: remove WPF dependency (IEditorInlineRenameService)
private static readonly TestComposition s_composition = EditorTestCompositions.LanguageServerProtocolWpf
.AddParts(typeof(TestLspWorkspaceRegistrationService))
.AddParts(typeof(TestDocumentTrackingService))
.AddParts(typeof(TestExperimentationService))
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
[Export(typeof(ILspWorkspaceRegistrationService)), PartNotDiscoverable]
internal class TestLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations()
{
Contract.ThrowIfNull(_workspace, "No workspace has been registered");
return ImmutableArray.Create(_workspace);
}
public void Register(Workspace workspace)
{
Contract.ThrowIfTrue(_workspace != null);
_workspace = workspace;
}
}
private class TestSpanMapperProvider : IDocumentServiceProvider
{
TService IDocumentServiceProvider.GetService<TService>()
=> (TService)(object)new TestSpanMapper();
}
internal class TestSpanMapper : ISpanMappingService
{
private static readonly LinePositionSpan s_mappedLinePosition = new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 5));
private static readonly string s_mappedFilePath = "c:\\MappedFile.cs";
internal static readonly string GeneratedFileName = "GeneratedFile.cs";
internal static readonly LSP.Location MappedFileLocation = new LSP.Location
{
Range = ProtocolConversions.LinePositionToRange(s_mappedLinePosition),
Uri = new Uri(s_mappedFilePath)
};
/// <summary>
/// LSP tests are simulating the new razor system which does support mapping import directives.
/// </summary>
public bool SupportsMappingImportDirectives => true;
public Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
ImmutableArray<MappedSpanResult> mappedResult = default;
if (document.Name == GeneratedFileName)
{
mappedResult = spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))).ToImmutableArray();
}
return Task.FromResult(mappedResult);
}
public Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
protected class OrderLocations : Comparer<LSP.Location>
{
public override int Compare(LSP.Location x, LSP.Location y) => CompareLocations(x, y);
}
protected virtual TestComposition Composition => s_composition;
/// <summary>
/// Asserts two objects are equivalent by converting to JSON and ignoring whitespace.
/// </summary>
/// <typeparam name="T">the JSON object type.</typeparam>
/// <param name="expected">the expected object to be converted to JSON.</param>
/// <param name="actual">the actual object to be converted to JSON.</param>
public static void AssertJsonEquals<T>(T expected, T actual)
{
var expectedStr = JsonConvert.SerializeObject(expected);
var actualStr = JsonConvert.SerializeObject(actual);
AssertEqualIgnoringWhitespace(expectedStr, actualStr);
}
protected static void AssertEqualIgnoringWhitespace(string expected, string actual)
{
var expectedWithoutWhitespace = Regex.Replace(expected, @"\s+", string.Empty);
var actualWithoutWhitespace = Regex.Replace(actual, @"\s+", string.Empty);
Assert.Equal(expectedWithoutWhitespace, actualWithoutWhitespace);
}
/// <summary>
/// Assert that two location lists are equivalent.
/// Locations are not always returned in a consistent order so they must be sorted.
/// </summary>
protected static void AssertLocationsEqual(IEnumerable<LSP.Location> expectedLocations, IEnumerable<LSP.Location> actualLocations)
{
var orderedActualLocations = actualLocations.OrderBy(CompareLocations);
var orderedExpectedLocations = expectedLocations.OrderBy(CompareLocations);
AssertJsonEquals(orderedExpectedLocations, orderedActualLocations);
}
protected static int CompareLocations(LSP.Location l1, LSP.Location l2)
{
var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString);
var compareRange = CompareRange(l1.Range, l2.Range);
return compareDocument != 0 ? compareDocument : compareRange;
}
protected static int CompareRange(LSP.Range r1, LSP.Range r2)
{
var compareLine = r1.Start.Line.CompareTo(r2.Start.Line);
var compareChar = r1.Start.Character.CompareTo(r2.Start.Character);
return compareLine != 0 ? compareLine : compareChar;
}
protected static string ApplyTextEdits(LSP.TextEdit[] edits, SourceText originalMarkup)
{
var text = originalMarkup;
foreach (var edit in edits)
{
var lines = text.Lines;
var startPosition = ProtocolConversions.PositionToLinePosition(edit.Range.Start);
var endPosition = ProtocolConversions.PositionToLinePosition(edit.Range.End);
var textSpan = lines.GetTextSpan(new LinePositionSpan(startPosition, endPosition));
text = text.Replace(textSpan, edit.NewText);
}
return text.ToString();
}
internal static LSP.SymbolInformation CreateSymbolInformation(LSP.SymbolKind kind, string name, LSP.Location location, Glyph glyph, string? containerName = null)
{
var info = new LSP.VSSymbolInformation()
{
Kind = kind,
Name = name,
Location = location,
Icon = new ImageElement(glyph.GetImageId()),
};
if (containerName != null)
{
info.ContainerName = containerName;
}
return info;
}
protected static LSP.TextDocumentIdentifier CreateTextDocumentIdentifier(Uri uri, ProjectId? projectContext = null)
{
var documentIdentifier = new LSP.VSTextDocumentIdentifier { Uri = uri };
if (projectContext != null)
{
documentIdentifier.ProjectContext =
new LSP.ProjectContext { Id = ProtocolConversions.ProjectIdToProjectContextId(projectContext) };
}
return documentIdentifier;
}
protected static LSP.TextDocumentPositionParams CreateTextDocumentPositionParams(LSP.Location caret, ProjectId? projectContext = null)
=> new LSP.TextDocumentPositionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri, projectContext),
Position = caret.Range.Start
};
protected static LSP.MarkupContent CreateMarkupContent(LSP.MarkupKind kind, string value)
=> new LSP.MarkupContent()
{
Kind = kind,
Value = value
};
protected static LSP.CompletionParams CreateCompletionParams(
LSP.Location caret,
LSP.VSCompletionInvokeKind invokeKind,
string triggerCharacter,
LSP.CompletionTriggerKind triggerKind)
=> new LSP.CompletionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.VSCompletionContext()
{
InvokeKind = invokeKind,
TriggerCharacter = triggerCharacter,
TriggerKind = triggerKind,
}
};
protected static async Task<LSP.VSCompletionItem> CreateCompletionItemAsync(
string label,
LSP.CompletionItemKind kind,
string[] tags,
LSP.CompletionParams request,
Document document,
bool preselect = false,
ImmutableArray<char>? commitCharacters = null,
LSP.TextEdit? textEdit = null,
string? insertText = null,
string? sortText = null,
string? filterText = null,
long resultId = 0)
{
var position = await document.GetPositionFromLinePositionAsync(
ProtocolConversions.PositionToLinePosition(request.Position), CancellationToken.None).ConfigureAwait(false);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(
request.Context, document, position, CancellationToken.None).ConfigureAwait(false);
var item = new LSP.VSCompletionItem()
{
TextEdit = textEdit,
InsertText = insertText,
FilterText = filterText ?? label,
Label = label,
SortText = sortText ?? label,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = JObject.FromObject(new CompletionResolveData()
{
ResultId = resultId,
}),
Preselect = preselect
};
if (tags != null)
item.Icon = tags.ToImmutableArray().GetFirstGlyph().GetImageElement();
if (commitCharacters != null)
item.CommitCharacters = commitCharacters.Value.Select(c => c.ToString()).ToArray();
return item;
}
protected static LSP.TextEdit GenerateTextEdit(string newText, int startLine, int startChar, int endLine, int endChar)
=> new LSP.TextEdit
{
NewText = newText,
Range = new LSP.Range
{
Start = new LSP.Position { Line = startLine, Character = startChar },
End = new LSP.Position { Line = endLine, Character = endChar }
}
};
private protected static CodeActionResolveData CreateCodeActionResolveData(string uniqueIdentifier, LSP.Location location, IEnumerable<string>? customTags = null)
=> new CodeActionResolveData(uniqueIdentifier, customTags.ToImmutableArrayOrEmpty(), location.Range, CreateTextDocumentIdentifier(location.Uri));
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the markup.
/// </summary>
protected TestLspServer CreateTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.CSharp);
protected TestLspServer CreateVisualBasicTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.VisualBasic);
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the specified documents.
/// </summary>
protected TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(markups, out locations, LanguageNames.CSharp);
private TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations, string languageName)
{
var workspace = languageName switch
{
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markups, composition: Composition),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markups, composition: Composition),
_ => throw new ArgumentException($"language name {languageName} is not valid for a test workspace"),
};
RegisterWorkspaceForLsp(workspace);
var solution = workspace.CurrentSolution;
foreach (var document in workspace.Documents)
{
solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name));
}
workspace.ChangeSolution(solution);
locations = GetAnnotatedLocations(workspace, solution);
return new TestLspServer(workspace);
}
protected TestLspServer CreateXmlTestLspServer(string xmlContent, out Dictionary<string, IList<LSP.Location>> locations)
{
var workspace = TestWorkspace.Create(xmlContent, composition: Composition);
RegisterWorkspaceForLsp(workspace);
locations = GetAnnotatedLocations(workspace, workspace.CurrentSolution);
return new TestLspServer(workspace);
}
protected static void AddMappedDocument(Workspace workspace, string markup)
{
var generatedDocumentId = DocumentId.CreateNewId(workspace.CurrentSolution.ProjectIds.First());
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(SourceText.From(markup), version, TestSpanMapper.GeneratedFileName));
var generatedDocumentInfo = DocumentInfo.Create(generatedDocumentId, TestSpanMapper.GeneratedFileName, SpecializedCollections.EmptyReadOnlyList<string>(),
SourceCodeKind.Regular, loader, $"C:\\{TestSpanMapper.GeneratedFileName}", isGenerated: true, designTimeOnly: false, new TestSpanMapperProvider());
var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo);
workspace.TryApplyChanges(newSolution);
}
private protected static void RegisterWorkspaceForLsp(TestWorkspace workspace)
{
var provider = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
provider.Register(workspace);
}
public static Dictionary<string, IList<LSP.Location>> GetAnnotatedLocations(TestWorkspace workspace, Solution solution)
{
var locations = new Dictionary<string, IList<LSP.Location>>();
foreach (var testDocument in workspace.Documents)
{
var document = solution.GetRequiredDocument(testDocument.Id);
var text = document.GetTextSynchronously(CancellationToken.None);
foreach (var (name, spans) in testDocument.AnnotatedSpans)
{
var locationsForName = locations.GetValueOrDefault(name, new List<LSP.Location>());
locationsForName.AddRange(spans.Select(span => ConvertTextSpanWithTextToLocation(span, text, new Uri(document.FilePath))));
// Linked files will return duplicate annotated Locations for each document that links to the same file.
// Since the test output only cares about the actual file, make sure we de-dupe before returning.
locations[name] = locationsForName.Distinct().ToList();
}
}
return locations;
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = ProtocolConversions.TextSpanToRange(span, text),
};
return location;
}
}
private static RequestDispatcher CreateRequestDispatcher(TestWorkspace workspace)
{
var factory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
return factory.CreateRequestDispatcher();
}
private static RequestExecutionQueue CreateRequestQueue(TestWorkspace workspace)
{
var registrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
return new RequestExecutionQueue(NoOpLspLogger.Instance, registrationService, serverName: "Tests", "TestClient");
}
private static string GetDocumentFilePathFromName(string documentName)
=> "C:\\" + documentName;
private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams(
Uri documentUri,
ImmutableArray<(int startLine, int startColumn, int endLine, int endColumn, string text)> changes)
{
var changeEvents = changes.Select(change => new LSP.TextDocumentContentChangeEvent
{
Text = change.text,
Range = new LSP.Range
{
Start = new LSP.Position(change.startLine, change.startColumn),
End = new LSP.Position(change.endLine, change.endColumn)
}
}).ToArray();
return new LSP.DidChangeTextDocumentParams()
{
TextDocument = new LSP.VersionedTextDocumentIdentifier
{
Uri = documentUri
},
ContentChanges = changeEvents
};
}
private static LSP.DidOpenTextDocumentParams CreateDidOpenTextDocumentParams(Uri uri, string source)
=> new LSP.DidOpenTextDocumentParams
{
TextDocument = new LSP.TextDocumentItem
{
Text = source,
Uri = uri
}
};
private static LSP.DidCloseTextDocumentParams CreateDidCloseTextDocumentParams(Uri uri)
=> new LSP.DidCloseTextDocumentParams()
{
TextDocument = new LSP.TextDocumentIdentifier
{
Uri = uri
}
};
public sealed class TestLspServer : IDisposable
{
public readonly TestWorkspace TestWorkspace;
private readonly RequestDispatcher _requestDispatcher;
private readonly RequestExecutionQueue _executionQueue;
internal TestLspServer(TestWorkspace testWorkspace)
{
TestWorkspace = testWorkspace;
_requestDispatcher = CreateRequestDispatcher(testWorkspace);
_executionQueue = CreateRequestQueue(testWorkspace);
}
public Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(string methodName, RequestType request, LSP.ClientCapabilities clientCapabilities,
string? clientName, CancellationToken cancellationToken) where RequestType : class
{
return _requestDispatcher.ExecuteRequestAsync<RequestType, ResponseType>(
_executionQueue, methodName, request, clientCapabilities, clientName, cancellationToken);
}
public async Task OpenDocumentAsync(Uri documentUri)
{
// LSP open files don't care about the project context, just the file contents with the URI.
// So pick any of the linked documents to get the text from.
var text = await TestWorkspace.CurrentSolution.GetDocuments(documentUri).First().GetTextAsync(CancellationToken.None).ConfigureAwait(false);
var didOpenParams = CreateDidOpenTextDocumentParams(documentUri, text.ToString());
await ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(LSP.Methods.TextDocumentDidOpenName,
didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task InsertTextAsync(Uri documentUri, params (int line, int column, string text)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (startLine: change.line, startColumn: change.column, endLine: change.line, endColumn: change.column, change.text)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None);
}
public Task DeleteTextAsync(Uri documentUri, params (int startLine, int startColumn, int endLine, int endColumn)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (change.startLine, change.startColumn, change.endLine, change.endColumn, text: string.Empty)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task CloseDocumentAsync(Uri documentUri)
{
var didCloseParams = CreateDidCloseTextDocumentParams(documentUri);
return ExecuteRequestAsync<LSP.DidCloseTextDocumentParams, object>(LSP.Methods.TextDocumentDidCloseName,
didCloseParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Solution GetCurrentSolution() => TestWorkspace.CurrentSolution;
internal RequestExecutionQueue.TestAccessor GetQueueAccessor() => _executionQueue.GetTestAccessor();
internal RequestDispatcher.TestAccessor GetDispatcherAccessor() => _requestDispatcher.GetTestAccessor();
public void Dispose()
{
TestWorkspace.Dispose();
_executionQueue.Shutdown();
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.Test.Utilities
{
[UseExportProvider]
public abstract class AbstractLanguageServerProtocolTests
{
// TODO: remove WPF dependency (IEditorInlineRenameService)
private static readonly TestComposition s_composition = EditorTestCompositions.LanguageServerProtocolWpf
.AddParts(typeof(TestLspWorkspaceRegistrationService))
.AddParts(typeof(TestDocumentTrackingService))
.AddParts(typeof(TestExperimentationService))
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
[Export(typeof(ILspWorkspaceRegistrationService)), PartNotDiscoverable]
internal class TestLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations()
{
Contract.ThrowIfNull(_workspace, "No workspace has been registered");
return ImmutableArray.Create(_workspace);
}
public void Register(Workspace workspace)
{
Contract.ThrowIfTrue(_workspace != null);
_workspace = workspace;
}
}
private class TestSpanMapperProvider : IDocumentServiceProvider
{
TService IDocumentServiceProvider.GetService<TService>()
=> (TService)(object)new TestSpanMapper();
}
internal class TestSpanMapper : ISpanMappingService
{
private static readonly LinePositionSpan s_mappedLinePosition = new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 5));
private static readonly string s_mappedFilePath = "c:\\MappedFile.cs";
internal static readonly string GeneratedFileName = "GeneratedFile.cs";
internal static readonly LSP.Location MappedFileLocation = new LSP.Location
{
Range = ProtocolConversions.LinePositionToRange(s_mappedLinePosition),
Uri = new Uri(s_mappedFilePath)
};
/// <summary>
/// LSP tests are simulating the new razor system which does support mapping import directives.
/// </summary>
public bool SupportsMappingImportDirectives => true;
public Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
ImmutableArray<MappedSpanResult> mappedResult = default;
if (document.Name == GeneratedFileName)
{
mappedResult = spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))).ToImmutableArray();
}
return Task.FromResult(mappedResult);
}
public Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
protected class OrderLocations : Comparer<LSP.Location>
{
public override int Compare(LSP.Location x, LSP.Location y) => CompareLocations(x, y);
}
protected virtual TestComposition Composition => s_composition;
/// <summary>
/// Asserts two objects are equivalent by converting to JSON and ignoring whitespace.
/// </summary>
/// <typeparam name="T">the JSON object type.</typeparam>
/// <param name="expected">the expected object to be converted to JSON.</param>
/// <param name="actual">the actual object to be converted to JSON.</param>
public static void AssertJsonEquals<T>(T expected, T actual)
{
var expectedStr = JsonConvert.SerializeObject(expected);
var actualStr = JsonConvert.SerializeObject(actual);
AssertEqualIgnoringWhitespace(expectedStr, actualStr);
}
protected static void AssertEqualIgnoringWhitespace(string expected, string actual)
{
var expectedWithoutWhitespace = Regex.Replace(expected, @"\s+", string.Empty);
var actualWithoutWhitespace = Regex.Replace(actual, @"\s+", string.Empty);
Assert.Equal(expectedWithoutWhitespace, actualWithoutWhitespace);
}
/// <summary>
/// Assert that two location lists are equivalent.
/// Locations are not always returned in a consistent order so they must be sorted.
/// </summary>
protected static void AssertLocationsEqual(IEnumerable<LSP.Location> expectedLocations, IEnumerable<LSP.Location> actualLocations)
{
var orderedActualLocations = actualLocations.OrderBy(CompareLocations);
var orderedExpectedLocations = expectedLocations.OrderBy(CompareLocations);
AssertJsonEquals(orderedExpectedLocations, orderedActualLocations);
}
protected static int CompareLocations(LSP.Location l1, LSP.Location l2)
{
var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString);
var compareRange = CompareRange(l1.Range, l2.Range);
return compareDocument != 0 ? compareDocument : compareRange;
}
protected static int CompareRange(LSP.Range r1, LSP.Range r2)
{
var compareLine = r1.Start.Line.CompareTo(r2.Start.Line);
var compareChar = r1.Start.Character.CompareTo(r2.Start.Character);
return compareLine != 0 ? compareLine : compareChar;
}
protected static string ApplyTextEdits(LSP.TextEdit[] edits, SourceText originalMarkup)
{
var text = originalMarkup;
foreach (var edit in edits)
{
var lines = text.Lines;
var startPosition = ProtocolConversions.PositionToLinePosition(edit.Range.Start);
var endPosition = ProtocolConversions.PositionToLinePosition(edit.Range.End);
var textSpan = lines.GetTextSpan(new LinePositionSpan(startPosition, endPosition));
text = text.Replace(textSpan, edit.NewText);
}
return text.ToString();
}
internal static LSP.SymbolInformation CreateSymbolInformation(LSP.SymbolKind kind, string name, LSP.Location location, Glyph glyph, string? containerName = null)
{
var info = new LSP.VSSymbolInformation()
{
Kind = kind,
Name = name,
Location = location,
Icon = new ImageElement(glyph.GetImageId()),
};
if (containerName != null)
{
info.ContainerName = containerName;
}
return info;
}
protected static LSP.TextDocumentIdentifier CreateTextDocumentIdentifier(Uri uri, ProjectId? projectContext = null)
{
var documentIdentifier = new LSP.VSTextDocumentIdentifier { Uri = uri };
if (projectContext != null)
{
documentIdentifier.ProjectContext =
new LSP.ProjectContext { Id = ProtocolConversions.ProjectIdToProjectContextId(projectContext) };
}
return documentIdentifier;
}
protected static LSP.TextDocumentPositionParams CreateTextDocumentPositionParams(LSP.Location caret, ProjectId? projectContext = null)
=> new LSP.TextDocumentPositionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri, projectContext),
Position = caret.Range.Start
};
protected static LSP.MarkupContent CreateMarkupContent(LSP.MarkupKind kind, string value)
=> new LSP.MarkupContent()
{
Kind = kind,
Value = value
};
protected static LSP.CompletionParams CreateCompletionParams(
LSP.Location caret,
LSP.VSCompletionInvokeKind invokeKind,
string triggerCharacter,
LSP.CompletionTriggerKind triggerKind)
=> new LSP.CompletionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.VSCompletionContext()
{
InvokeKind = invokeKind,
TriggerCharacter = triggerCharacter,
TriggerKind = triggerKind,
}
};
protected static async Task<LSP.VSCompletionItem> CreateCompletionItemAsync(
string label,
LSP.CompletionItemKind kind,
string[] tags,
LSP.CompletionParams request,
Document document,
bool preselect = false,
ImmutableArray<char>? commitCharacters = null,
LSP.TextEdit? textEdit = null,
string? insertText = null,
string? sortText = null,
string? filterText = null,
long resultId = 0)
{
var position = await document.GetPositionFromLinePositionAsync(
ProtocolConversions.PositionToLinePosition(request.Position), CancellationToken.None).ConfigureAwait(false);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(
request.Context, document, position, CancellationToken.None).ConfigureAwait(false);
var item = new LSP.VSCompletionItem()
{
TextEdit = textEdit,
InsertText = insertText,
FilterText = filterText ?? label,
Label = label,
SortText = sortText ?? label,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = JObject.FromObject(new CompletionResolveData()
{
ResultId = resultId,
}),
Preselect = preselect
};
if (tags != null)
item.Icon = tags.ToImmutableArray().GetFirstGlyph().GetImageElement();
if (commitCharacters != null)
item.CommitCharacters = commitCharacters.Value.Select(c => c.ToString()).ToArray();
return item;
}
protected static LSP.TextEdit GenerateTextEdit(string newText, int startLine, int startChar, int endLine, int endChar)
=> new LSP.TextEdit
{
NewText = newText,
Range = new LSP.Range
{
Start = new LSP.Position { Line = startLine, Character = startChar },
End = new LSP.Position { Line = endLine, Character = endChar }
}
};
private protected static CodeActionResolveData CreateCodeActionResolveData(string uniqueIdentifier, LSP.Location location, IEnumerable<string>? customTags = null)
=> new CodeActionResolveData(uniqueIdentifier, customTags.ToImmutableArrayOrEmpty(), location.Range, CreateTextDocumentIdentifier(location.Uri));
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the markup.
/// </summary>
protected TestLspServer CreateTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.CSharp);
protected TestLspServer CreateVisualBasicTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.VisualBasic);
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the specified documents.
/// </summary>
protected TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(markups, out locations, LanguageNames.CSharp);
private TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations, string languageName)
{
var workspace = languageName switch
{
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markups, composition: Composition),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markups, composition: Composition),
_ => throw new ArgumentException($"language name {languageName} is not valid for a test workspace"),
};
RegisterWorkspaceForLsp(workspace);
var solution = workspace.CurrentSolution;
foreach (var document in workspace.Documents)
{
solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name));
}
workspace.ChangeSolution(solution);
locations = GetAnnotatedLocations(workspace, solution);
return new TestLspServer(workspace);
}
protected TestLspServer CreateXmlTestLspServer(string xmlContent, out Dictionary<string, IList<LSP.Location>> locations)
{
var workspace = TestWorkspace.Create(xmlContent, composition: Composition);
RegisterWorkspaceForLsp(workspace);
locations = GetAnnotatedLocations(workspace, workspace.CurrentSolution);
return new TestLspServer(workspace);
}
protected static void AddMappedDocument(Workspace workspace, string markup)
{
var generatedDocumentId = DocumentId.CreateNewId(workspace.CurrentSolution.ProjectIds.First());
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(SourceText.From(markup), version, TestSpanMapper.GeneratedFileName));
var generatedDocumentInfo = DocumentInfo.Create(generatedDocumentId, TestSpanMapper.GeneratedFileName, SpecializedCollections.EmptyReadOnlyList<string>(),
SourceCodeKind.Regular, loader, $"C:\\{TestSpanMapper.GeneratedFileName}", isGenerated: true, designTimeOnly: false, new TestSpanMapperProvider());
var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo);
workspace.TryApplyChanges(newSolution);
}
private protected static void RegisterWorkspaceForLsp(TestWorkspace workspace)
{
var provider = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
provider.Register(workspace);
}
public static Dictionary<string, IList<LSP.Location>> GetAnnotatedLocations(TestWorkspace workspace, Solution solution)
{
var locations = new Dictionary<string, IList<LSP.Location>>();
foreach (var testDocument in workspace.Documents)
{
var document = solution.GetRequiredDocument(testDocument.Id);
var text = document.GetTextSynchronously(CancellationToken.None);
foreach (var (name, spans) in testDocument.AnnotatedSpans)
{
var locationsForName = locations.GetValueOrDefault(name, new List<LSP.Location>());
locationsForName.AddRange(spans.Select(span => ConvertTextSpanWithTextToLocation(span, text, new Uri(document.FilePath))));
// Linked files will return duplicate annotated Locations for each document that links to the same file.
// Since the test output only cares about the actual file, make sure we de-dupe before returning.
locations[name] = locationsForName.Distinct().ToList();
}
}
return locations;
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = ProtocolConversions.TextSpanToRange(span, text),
};
return location;
}
}
private static RequestDispatcher CreateRequestDispatcher(TestWorkspace workspace)
{
var factory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
return factory.CreateRequestDispatcher();
}
private static RequestExecutionQueue CreateRequestQueue(TestWorkspace workspace)
{
var registrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
return new RequestExecutionQueue(NoOpLspLogger.Instance, registrationService, serverName: "Tests", "TestClient");
}
private static string GetDocumentFilePathFromName(string documentName)
=> "C:\\" + documentName;
private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams(
Uri documentUri,
ImmutableArray<(int startLine, int startColumn, int endLine, int endColumn, string text)> changes)
{
var changeEvents = changes.Select(change => new LSP.TextDocumentContentChangeEvent
{
Text = change.text,
Range = new LSP.Range
{
Start = new LSP.Position(change.startLine, change.startColumn),
End = new LSP.Position(change.endLine, change.endColumn)
}
}).ToArray();
return new LSP.DidChangeTextDocumentParams()
{
TextDocument = new LSP.VersionedTextDocumentIdentifier
{
Uri = documentUri
},
ContentChanges = changeEvents
};
}
private static LSP.DidOpenTextDocumentParams CreateDidOpenTextDocumentParams(Uri uri, string source)
=> new LSP.DidOpenTextDocumentParams
{
TextDocument = new LSP.TextDocumentItem
{
Text = source,
Uri = uri
}
};
private static LSP.DidCloseTextDocumentParams CreateDidCloseTextDocumentParams(Uri uri)
=> new LSP.DidCloseTextDocumentParams()
{
TextDocument = new LSP.TextDocumentIdentifier
{
Uri = uri
}
};
public sealed class TestLspServer : IDisposable
{
public readonly TestWorkspace TestWorkspace;
private readonly RequestDispatcher _requestDispatcher;
private readonly RequestExecutionQueue _executionQueue;
internal TestLspServer(TestWorkspace testWorkspace)
{
TestWorkspace = testWorkspace;
_requestDispatcher = CreateRequestDispatcher(testWorkspace);
_executionQueue = CreateRequestQueue(testWorkspace);
}
public Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(string methodName, RequestType request, LSP.ClientCapabilities clientCapabilities,
string? clientName, CancellationToken cancellationToken) where RequestType : class
{
return _requestDispatcher.ExecuteRequestAsync<RequestType, ResponseType>(
_executionQueue, methodName, request, clientCapabilities, clientName, cancellationToken);
}
public async Task OpenDocumentAsync(Uri documentUri)
{
// LSP open files don't care about the project context, just the file contents with the URI.
// So pick any of the linked documents to get the text from.
var text = await TestWorkspace.CurrentSolution.GetDocuments(documentUri).First().GetTextAsync(CancellationToken.None).ConfigureAwait(false);
var didOpenParams = CreateDidOpenTextDocumentParams(documentUri, text.ToString());
await ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(LSP.Methods.TextDocumentDidOpenName,
didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task InsertTextAsync(Uri documentUri, params (int line, int column, string text)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (startLine: change.line, startColumn: change.column, endLine: change.line, endColumn: change.column, change.text)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None);
}
public Task DeleteTextAsync(Uri documentUri, params (int startLine, int startColumn, int endLine, int endColumn)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (change.startLine, change.startColumn, change.endLine, change.endColumn, text: string.Empty)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task CloseDocumentAsync(Uri documentUri)
{
var didCloseParams = CreateDidCloseTextDocumentParams(documentUri);
return ExecuteRequestAsync<LSP.DidCloseTextDocumentParams, object>(LSP.Methods.TextDocumentDidCloseName,
didCloseParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Solution GetCurrentSolution() => TestWorkspace.CurrentSolution;
internal RequestExecutionQueue.TestAccessor GetQueueAccessor() => _executionQueue.GetTestAccessor();
internal RequestDispatcher.TestAccessor GetDispatcherAccessor() => _requestDispatcher.GetTestAccessor();
public void Dispose()
{
TestWorkspace.Dispose();
_executionQueue.Shutdown();
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/CSharp/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.Comparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class MemberDeclarationsOrganizer
{
private class Comparer : IComparer<MemberDeclarationSyntax>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum OuterOrdering
{
Fields,
EventFields,
Constructors,
Destructors,
Properties,
Events,
Indexers,
Operators,
ConversionOperators,
Methods,
Types,
Remaining
}
private enum InnerOrdering
{
StaticInstance,
Accessibility,
Name
}
private enum Accessibility
{
Public,
Protected,
ProtectedOrInternal,
Internal,
Private
}
public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y)
{
if (x == y)
{
return 0;
}
var xOuterOrdering = GetOuterOrdering(x);
var yOuterOrdering = GetOuterOrdering(y);
var compare = xOuterOrdering - yOuterOrdering;
if (compare != 0)
{
return compare;
}
if (xOuterOrdering == OuterOrdering.Remaining)
{
return 1;
}
else if (yOuterOrdering == OuterOrdering.Remaining)
{
return -1;
}
if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields)
{
// Fields with initializers can't be reordered relative to
// themselves due to ordering issues.
var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null);
var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null);
if (xHasInitializer && yHasInitializer)
{
return 0;
}
}
var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0)
{
return compare;
}
var xAccessibility = GetAccessibility(x);
var yAccessibility = GetAccessibility(y);
if ((compare = xAccessibility - yAccessibility) != 0)
{
return compare;
}
var xName = ShouldCompareByName(x) ? x.GetNameToken() : default;
var yName = ShouldCompareByName(y) ? y.GetNameToken() : default;
if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0)
{
return compare;
}
// Their names were the same. Order them by arity at this point.
return x.GetArity() - y.GetArity();
}
private static Accessibility GetAccessibility(MemberDeclarationSyntax x)
{
var xModifiers = x.GetModifiers();
if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return Accessibility.Public;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.ProtectedOrInternal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.Internal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return Accessibility.Protected;
}
else
{
return Accessibility.Private;
}
}
private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x)
{
switch (x.Kind())
{
case SyntaxKind.FieldDeclaration:
return OuterOrdering.Fields;
case SyntaxKind.EventFieldDeclaration:
return OuterOrdering.EventFields;
case SyntaxKind.ConstructorDeclaration:
return OuterOrdering.Constructors;
case SyntaxKind.DestructorDeclaration:
return OuterOrdering.Destructors;
case SyntaxKind.PropertyDeclaration:
return OuterOrdering.Properties;
case SyntaxKind.EventDeclaration:
return OuterOrdering.Events;
case SyntaxKind.IndexerDeclaration:
return OuterOrdering.Indexers;
case SyntaxKind.OperatorDeclaration:
return OuterOrdering.Operators;
case SyntaxKind.ConversionOperatorDeclaration:
return OuterOrdering.ConversionOperators;
case SyntaxKind.MethodDeclaration:
return OuterOrdering.Methods;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return OuterOrdering.Types;
default:
return OuterOrdering.Remaining;
}
}
private static bool ShouldCompareByName(MemberDeclarationSyntax x)
{
// Constructors, destructors, indexers and operators should not be sorted by name.
// Note: Conversion operators should not be sorted by name either, but it's not
// necessary to deal with that here, because GetNameToken cannot return a
// name for them (there's only a NameSyntax, not a Token).
switch (x.Kind())
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
return false;
default:
return true;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class MemberDeclarationsOrganizer
{
private class Comparer : IComparer<MemberDeclarationSyntax>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum OuterOrdering
{
Fields,
EventFields,
Constructors,
Destructors,
Properties,
Events,
Indexers,
Operators,
ConversionOperators,
Methods,
Types,
Remaining
}
private enum InnerOrdering
{
StaticInstance,
Accessibility,
Name
}
private enum Accessibility
{
Public,
Protected,
ProtectedOrInternal,
Internal,
Private
}
public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y)
{
if (x == y)
{
return 0;
}
var xOuterOrdering = GetOuterOrdering(x);
var yOuterOrdering = GetOuterOrdering(y);
var compare = xOuterOrdering - yOuterOrdering;
if (compare != 0)
{
return compare;
}
if (xOuterOrdering == OuterOrdering.Remaining)
{
return 1;
}
else if (yOuterOrdering == OuterOrdering.Remaining)
{
return -1;
}
if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields)
{
// Fields with initializers can't be reordered relative to
// themselves due to ordering issues.
var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null);
var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null);
if (xHasInitializer && yHasInitializer)
{
return 0;
}
}
var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0)
{
return compare;
}
var xAccessibility = GetAccessibility(x);
var yAccessibility = GetAccessibility(y);
if ((compare = xAccessibility - yAccessibility) != 0)
{
return compare;
}
var xName = ShouldCompareByName(x) ? x.GetNameToken() : default;
var yName = ShouldCompareByName(y) ? y.GetNameToken() : default;
if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0)
{
return compare;
}
// Their names were the same. Order them by arity at this point.
return x.GetArity() - y.GetArity();
}
private static Accessibility GetAccessibility(MemberDeclarationSyntax x)
{
var xModifiers = x.GetModifiers();
if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return Accessibility.Public;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.ProtectedOrInternal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.Internal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return Accessibility.Protected;
}
else
{
return Accessibility.Private;
}
}
private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x)
{
switch (x.Kind())
{
case SyntaxKind.FieldDeclaration:
return OuterOrdering.Fields;
case SyntaxKind.EventFieldDeclaration:
return OuterOrdering.EventFields;
case SyntaxKind.ConstructorDeclaration:
return OuterOrdering.Constructors;
case SyntaxKind.DestructorDeclaration:
return OuterOrdering.Destructors;
case SyntaxKind.PropertyDeclaration:
return OuterOrdering.Properties;
case SyntaxKind.EventDeclaration:
return OuterOrdering.Events;
case SyntaxKind.IndexerDeclaration:
return OuterOrdering.Indexers;
case SyntaxKind.OperatorDeclaration:
return OuterOrdering.Operators;
case SyntaxKind.ConversionOperatorDeclaration:
return OuterOrdering.ConversionOperators;
case SyntaxKind.MethodDeclaration:
return OuterOrdering.Methods;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return OuterOrdering.Types;
default:
return OuterOrdering.Remaining;
}
}
private static bool ShouldCompareByName(MemberDeclarationSyntax x)
{
// Constructors, destructors, indexers and operators should not be sorted by name.
// Note: Conversion operators should not be sorted by name either, but it's not
// necessary to deal with that here, because GetNameToken cannot return a
// name for them (there's only a NameSyntax, not a Token).
switch (x.Kind())
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
return false;
default:
return true;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Projekt wird erstellt</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">Fehler beim Umbenennen: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktive Hostprozessplattform</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target>
<note />
</trans-unit>
<trans-unit id="Regex_Comment">
<source>Regex - Comment</source>
<target state="translated">RegEx - Kommentar</target>
<note />
</trans-unit>
<trans-unit id="Regex_Character_Class">
<source>Regex - Character Class</source>
<target state="translated">RegEx - Zeichenklasse</target>
<note />
</trans-unit>
<trans-unit id="Regex_Alternation">
<source>Regex - Alternation</source>
<target state="translated">RegEx - Wechsel</target>
<note />
</trans-unit>
<trans-unit id="Regex_Anchor">
<source>Regex - Anchor</source>
<target state="translated">RegEx - Anker</target>
<note />
</trans-unit>
<trans-unit id="Regex_Quantifier">
<source>Regex - Quantifier</source>
<target state="translated">RegEx - Quantifizierer</target>
<note />
</trans-unit>
<trans-unit id="Regex_SelfEscapedCharacter">
<source>Regex - Self Escaped Character</source>
<target state="translated">RegEx - Selbstständiges Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Regex_Grouping">
<source>Regex - Grouping</source>
<target state="translated">RegEx - Gruppierung</target>
<note />
</trans-unit>
<trans-unit id="Regex_Text">
<source>Regex - Text</source>
<target state="translated">RegEx - Text</target>
<note />
</trans-unit>
<trans-unit id="Regex_OtherEscape">
<source>Regex - Other Escape</source>
<target state="translated">RegEx - Anderes Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Interactives Element wird zurückgesetzt</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Projekt wird erstellt</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target>
<note />
</trans-unit>
<trans-unit id="Error_performing_rename_0">
<source>Error performing rename: '{0}'</source>
<target state="translated">Fehler beim Umbenennen: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktive Hostprozessplattform</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target>
<note />
</trans-unit>
<trans-unit id="Regex_Comment">
<source>Regex - Comment</source>
<target state="translated">RegEx - Kommentar</target>
<note />
</trans-unit>
<trans-unit id="Regex_Character_Class">
<source>Regex - Character Class</source>
<target state="translated">RegEx - Zeichenklasse</target>
<note />
</trans-unit>
<trans-unit id="Regex_Alternation">
<source>Regex - Alternation</source>
<target state="translated">RegEx - Wechsel</target>
<note />
</trans-unit>
<trans-unit id="Regex_Anchor">
<source>Regex - Anchor</source>
<target state="translated">RegEx - Anker</target>
<note />
</trans-unit>
<trans-unit id="Regex_Quantifier">
<source>Regex - Quantifier</source>
<target state="translated">RegEx - Quantifizierer</target>
<note />
</trans-unit>
<trans-unit id="Regex_SelfEscapedCharacter">
<source>Regex - Self Escaped Character</source>
<target state="translated">RegEx - Selbstständiges Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Regex_Grouping">
<source>Regex - Grouping</source>
<target state="translated">RegEx - Gruppierung</target>
<note />
</trans-unit>
<trans-unit id="Regex_Text">
<source>Regex - Text</source>
<target state="translated">RegEx - Text</target>
<note />
</trans-unit>
<trans-unit id="Regex_OtherEscape">
<source>Regex - Other Escape</source>
<target state="translated">RegEx - Anderes Escapezeichen</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Interactives Element wird zurückgesetzt</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbol.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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourceConstructorSymbol : SourceConstructorSymbolBase
{
private readonly bool _isExpressionBodied;
private readonly bool _hasThisInitializer;
public static SourceConstructorSymbol CreateConstructorSymbol(
SourceMemberContainerTypeSymbol containingType,
ConstructorDeclarationSyntax syntax,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics)
{
var methodKind = syntax.Modifiers.Any(SyntaxKind.StaticKeyword) ? MethodKind.StaticConstructor : MethodKind.Constructor;
return new SourceConstructorSymbol(containingType, syntax.Identifier.GetLocation(), syntax, methodKind, isNullableAnalysisEnabled, diagnostics);
}
private SourceConstructorSymbol(
SourceMemberContainerTypeSymbol containingType,
Location location,
ConstructorDeclarationSyntax syntax,
MethodKind methodKind,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics) :
base(containingType, location, syntax, SyntaxFacts.HasYieldOperations(syntax))
{
bool hasBlockBody = syntax.Body != null;
_isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null;
bool hasBody = hasBlockBody || _isExpressionBodied;
_hasThisInitializer = syntax.Initializer?.Kind() == SyntaxKind.ThisConstructorInitializer;
bool modifierErrors;
var declarationModifiers = this.MakeModifiers(syntax.Modifiers, methodKind, hasBody, location, diagnostics, out modifierErrors);
this.MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled);
if (syntax.Identifier.ValueText != containingType.Name)
{
// This is probably a method declaration with the type missing.
diagnostics.Add(ErrorCode.ERR_MemberNeedsType, location);
}
if (IsExtern)
{
if (methodKind == MethodKind.Constructor && syntax.Initializer != null)
{
diagnostics.Add(ErrorCode.ERR_ExternHasConstructorInitializer, location, this);
}
if (hasBody)
{
diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this);
}
}
if (methodKind == MethodKind.StaticConstructor)
{
CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics);
}
var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(info, location);
}
if (!modifierErrors)
{
this.CheckModifiers(methodKind, hasBody, location, diagnostics);
}
CheckForBlockAndExpressionBody(
syntax.Body, syntax.ExpressionBody, syntax, diagnostics);
}
internal ConstructorDeclarationSyntax GetSyntax()
{
Debug.Assert(syntaxReferenceOpt != null);
return (ConstructorDeclarationSyntax)syntaxReferenceOpt.GetSyntax();
}
protected override ParameterListSyntax GetParameterList()
{
return GetSyntax().ParameterList;
}
protected override CSharpSyntaxNode GetInitializer()
{
return GetSyntax().Initializer;
}
private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors)
{
var defaultAccess = (methodKind == MethodKind.StaticConstructor) ? DeclarationModifiers.None : DeclarationModifiers.Private;
// Check that the set of modifiers is allowed
const DeclarationModifiers allowedModifiers =
DeclarationModifiers.AccessibilityMask |
DeclarationModifiers.Static |
DeclarationModifiers.Extern |
DeclarationModifiers.Unsafe;
var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors);
this.CheckUnsafeModifier(mods, diagnostics);
if (methodKind == MethodKind.StaticConstructor)
{
// Don't report ERR_StaticConstructorWithAccessModifiers if the ctor symbol name doesn't match the containing type name.
// This avoids extra unnecessary errors.
// There will already be a diagnostic saying Method must have a return type.
if ((mods & DeclarationModifiers.AccessibilityMask) != 0 &&
ContainingType.Name == ((ConstructorDeclarationSyntax)this.SyntaxNode).Identifier.ValueText)
{
diagnostics.Add(ErrorCode.ERR_StaticConstructorWithAccessModifiers, location, this);
mods = mods & ~DeclarationModifiers.AccessibilityMask;
modifierErrors = true;
}
mods |= DeclarationModifiers.Private; // we mark static constructors private in the symbol table
if (this.ContainingType.IsInterface)
{
ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods,
DeclarationModifiers.Extern,
location, diagnostics);
}
}
return mods;
}
private void CheckModifiers(MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics)
{
if (!hasBody && !IsExtern)
{
diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this);
}
else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride)
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this);
}
else if (ContainingType.IsStatic && methodKind == MethodKind.Constructor)
{
diagnostics.Add(ErrorCode.ERR_ConstructorInStaticClass, location);
}
}
internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations()
{
return OneOrMany.Create(((ConstructorDeclarationSyntax)this.SyntaxNode).AttributeLists);
}
internal override bool IsExpressionBodied
{
get
{
return _isExpressionBodied;
}
}
internal override bool IsNullableAnalysisEnabled()
{
return _hasThisInitializer ?
flags.IsNullableAnalysisEnabled :
((SourceMemberContainerTypeSymbol)ContainingType).IsNullableEnabledForConstructorsAndInitializers(IsStatic);
}
protected override bool AllowRefOrOut
{
get
{
return true;
}
}
protected override bool IsWithinExpressionOrBlockBody(int position, out int offset)
{
ConstructorDeclarationSyntax ctorSyntax = GetSyntax();
if (ctorSyntax.Body?.Span.Contains(position) == true)
{
offset = position - ctorSyntax.Body.Span.Start;
return true;
}
else if (ctorSyntax.ExpressionBody?.Span.Contains(position) == true)
{
offset = position - ctorSyntax.ExpressionBody.Span.Start;
return true;
}
offset = -1;
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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourceConstructorSymbol : SourceConstructorSymbolBase
{
private readonly bool _isExpressionBodied;
private readonly bool _hasThisInitializer;
public static SourceConstructorSymbol CreateConstructorSymbol(
SourceMemberContainerTypeSymbol containingType,
ConstructorDeclarationSyntax syntax,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics)
{
var methodKind = syntax.Modifiers.Any(SyntaxKind.StaticKeyword) ? MethodKind.StaticConstructor : MethodKind.Constructor;
return new SourceConstructorSymbol(containingType, syntax.Identifier.GetLocation(), syntax, methodKind, isNullableAnalysisEnabled, diagnostics);
}
private SourceConstructorSymbol(
SourceMemberContainerTypeSymbol containingType,
Location location,
ConstructorDeclarationSyntax syntax,
MethodKind methodKind,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics) :
base(containingType, location, syntax, SyntaxFacts.HasYieldOperations(syntax))
{
bool hasBlockBody = syntax.Body != null;
_isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null;
bool hasBody = hasBlockBody || _isExpressionBodied;
_hasThisInitializer = syntax.Initializer?.Kind() == SyntaxKind.ThisConstructorInitializer;
bool modifierErrors;
var declarationModifiers = this.MakeModifiers(syntax.Modifiers, methodKind, hasBody, location, diagnostics, out modifierErrors);
this.MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled);
if (syntax.Identifier.ValueText != containingType.Name)
{
// This is probably a method declaration with the type missing.
diagnostics.Add(ErrorCode.ERR_MemberNeedsType, location);
}
if (IsExtern)
{
if (methodKind == MethodKind.Constructor && syntax.Initializer != null)
{
diagnostics.Add(ErrorCode.ERR_ExternHasConstructorInitializer, location, this);
}
if (hasBody)
{
diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this);
}
}
if (methodKind == MethodKind.StaticConstructor)
{
CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics);
}
var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(info, location);
}
if (!modifierErrors)
{
this.CheckModifiers(methodKind, hasBody, location, diagnostics);
}
CheckForBlockAndExpressionBody(
syntax.Body, syntax.ExpressionBody, syntax, diagnostics);
}
internal ConstructorDeclarationSyntax GetSyntax()
{
Debug.Assert(syntaxReferenceOpt != null);
return (ConstructorDeclarationSyntax)syntaxReferenceOpt.GetSyntax();
}
protected override ParameterListSyntax GetParameterList()
{
return GetSyntax().ParameterList;
}
protected override CSharpSyntaxNode GetInitializer()
{
return GetSyntax().Initializer;
}
private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors)
{
var defaultAccess = (methodKind == MethodKind.StaticConstructor) ? DeclarationModifiers.None : DeclarationModifiers.Private;
// Check that the set of modifiers is allowed
const DeclarationModifiers allowedModifiers =
DeclarationModifiers.AccessibilityMask |
DeclarationModifiers.Static |
DeclarationModifiers.Extern |
DeclarationModifiers.Unsafe;
var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors);
this.CheckUnsafeModifier(mods, diagnostics);
if (methodKind == MethodKind.StaticConstructor)
{
// Don't report ERR_StaticConstructorWithAccessModifiers if the ctor symbol name doesn't match the containing type name.
// This avoids extra unnecessary errors.
// There will already be a diagnostic saying Method must have a return type.
if ((mods & DeclarationModifiers.AccessibilityMask) != 0 &&
ContainingType.Name == ((ConstructorDeclarationSyntax)this.SyntaxNode).Identifier.ValueText)
{
diagnostics.Add(ErrorCode.ERR_StaticConstructorWithAccessModifiers, location, this);
mods = mods & ~DeclarationModifiers.AccessibilityMask;
modifierErrors = true;
}
mods |= DeclarationModifiers.Private; // we mark static constructors private in the symbol table
if (this.ContainingType.IsInterface)
{
ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods,
DeclarationModifiers.Extern,
location, diagnostics);
}
}
return mods;
}
private void CheckModifiers(MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics)
{
if (!hasBody && !IsExtern)
{
diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this);
}
else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride)
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this);
}
else if (ContainingType.IsStatic && methodKind == MethodKind.Constructor)
{
diagnostics.Add(ErrorCode.ERR_ConstructorInStaticClass, location);
}
}
internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations()
{
return OneOrMany.Create(((ConstructorDeclarationSyntax)this.SyntaxNode).AttributeLists);
}
internal override bool IsExpressionBodied
{
get
{
return _isExpressionBodied;
}
}
internal override bool IsNullableAnalysisEnabled()
{
return _hasThisInitializer ?
flags.IsNullableAnalysisEnabled :
((SourceMemberContainerTypeSymbol)ContainingType).IsNullableEnabledForConstructorsAndInitializers(IsStatic);
}
protected override bool AllowRefOrOut
{
get
{
return true;
}
}
protected override bool IsWithinExpressionOrBlockBody(int position, out int offset)
{
ConstructorDeclarationSyntax ctorSyntax = GetSyntax();
if (ctorSyntax.Body?.Span.Contains(position) == true)
{
offset = position - ctorSyntax.Body.Span.Start;
return true;
}
else if (ctorSyntax.ExpressionBody?.Span.Contains(position) == true)
{
offset = position - ctorSyntax.ExpressionBody.Span.Start;
return true;
}
offset = -1;
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./scripts/PublicApi/README.md | Mark Shipped Tool
========
This tool should be run after every supported release that has API changes. It will
merge the collection of PublicApi.Shipped.txt files with the PublicApi.Unshipped.txt
versions. This will take into account `*REMOVED*` elements when updating the files.
Usage:
``` cmd
mark-shipped.cmd
```
| Mark Shipped Tool
========
This tool should be run after every supported release that has API changes. It will
merge the collection of PublicApi.Shipped.txt files with the PublicApi.Unshipped.txt
versions. This will take into account `*REMOVED*` elements when updating the files.
Usage:
``` cmd
mark-shipped.cmd
```
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/CodeAnalysisTest/Text/StringTextTests_Default.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.IO;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class StringTextTest_Default
{
private Encoding _currentEncoding;
protected byte[] GetBytes(Encoding encoding, string source)
{
_currentEncoding = encoding;
return encoding.GetBytesWithPreamble(source);
}
protected virtual SourceText Create(string source)
{
byte[] buffer = GetBytes(Encoding.Default, source);
using (var stream = new MemoryStream(buffer, 0, buffer.Length, writable: false, publiclyVisible: true))
{
return EncodedStringText.Create(stream);
}
}
/// <summary>
/// Empty string case
/// </summary>
[Fact]
public void Ctor2()
{
var data = Create(string.Empty);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(0, data.Lines[0].Span.Length);
}
[Fact]
public void Indexer1()
{
var data = Create(String.Empty);
Assert.Throws<IndexOutOfRangeException>(
() => { var value = data[-1]; });
}
[Fact]
public void NewLines1()
{
string newLine = Environment.NewLine;
var data = Create("goo" + newLine + " bar");
Assert.Equal(2, data.Lines.Count);
Assert.Equal(3, data.Lines[0].Span.Length);
Assert.Equal(3 + newLine.Length, data.Lines[1].Span.Start);
}
[Fact]
public void NewLines2()
{
var text =
@"goo
bar
baz";
var data = Create(text);
Assert.Equal(3, data.Lines.Count);
Assert.Equal("goo", data.ToString(data.Lines[0].Span));
Assert.Equal("bar", data.ToString(data.Lines[1].Span));
Assert.Equal("baz", data.ToString(data.Lines[2].Span));
}
[Fact]
public void NewLines3()
{
var data = Create("goo\r\nbar");
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.ToString(data.Lines[0].Span));
Assert.Equal("bar", data.ToString(data.Lines[1].Span));
}
[Fact]
public void NewLines4()
{
var data = Create("goo\n\rbar");
Assert.Equal(3, data.Lines.Count);
}
[Fact]
public void LinesGetText1()
{
var data = Create(
@"goo
bar baz");
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.Lines[0].ToString());
Assert.Equal("bar baz", data.Lines[1].ToString());
}
[Fact]
public void LinesGetText2()
{
var data = Create("goo");
Assert.Equal("goo", data.Lines[0].ToString());
}
#if false
[Fact]
public void TextLine1()
{
var text = Create("goo" + Environment.NewLine);
var span = new TextSpan(0, 3);
var line = new TextLine(text, 0, 0, text.Length);
Assert.Equal(span, line.Extent);
Assert.Equal(5, line.EndIncludingLineBreak);
Assert.Equal(0, line.LineNumber);
}
[Fact]
public void GetText1()
{
var text = Create("goo");
var line = new TextLine(text, 0, 0, 2);
Assert.Equal("fo", line.ToString());
Assert.Equal(0, line.LineNumber);
}
[Fact]
public void GetText2()
{
var text = Create("abcdef");
var line = new TextLine(text, 0, 1, 2);
Assert.Equal("bc", line.ToString());
Assert.Equal(0, line.LineNumber);
}
#endif
[Fact]
public void GetExtendedAsciiText()
{
var originalText = Encoding.Default.GetString(new byte[] { 0xAB, 0xCD, 0xEF });
var encodedText = Create(originalText);
Assert.Equal(originalText, encodedText.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.
#nullable disable
using System;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class StringTextTest_Default
{
private Encoding _currentEncoding;
protected byte[] GetBytes(Encoding encoding, string source)
{
_currentEncoding = encoding;
return encoding.GetBytesWithPreamble(source);
}
protected virtual SourceText Create(string source)
{
byte[] buffer = GetBytes(Encoding.Default, source);
using (var stream = new MemoryStream(buffer, 0, buffer.Length, writable: false, publiclyVisible: true))
{
return EncodedStringText.Create(stream);
}
}
/// <summary>
/// Empty string case
/// </summary>
[Fact]
public void Ctor2()
{
var data = Create(string.Empty);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(0, data.Lines[0].Span.Length);
}
[Fact]
public void Indexer1()
{
var data = Create(String.Empty);
Assert.Throws<IndexOutOfRangeException>(
() => { var value = data[-1]; });
}
[Fact]
public void NewLines1()
{
string newLine = Environment.NewLine;
var data = Create("goo" + newLine + " bar");
Assert.Equal(2, data.Lines.Count);
Assert.Equal(3, data.Lines[0].Span.Length);
Assert.Equal(3 + newLine.Length, data.Lines[1].Span.Start);
}
[Fact]
public void NewLines2()
{
var text =
@"goo
bar
baz";
var data = Create(text);
Assert.Equal(3, data.Lines.Count);
Assert.Equal("goo", data.ToString(data.Lines[0].Span));
Assert.Equal("bar", data.ToString(data.Lines[1].Span));
Assert.Equal("baz", data.ToString(data.Lines[2].Span));
}
[Fact]
public void NewLines3()
{
var data = Create("goo\r\nbar");
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.ToString(data.Lines[0].Span));
Assert.Equal("bar", data.ToString(data.Lines[1].Span));
}
[Fact]
public void NewLines4()
{
var data = Create("goo\n\rbar");
Assert.Equal(3, data.Lines.Count);
}
[Fact]
public void LinesGetText1()
{
var data = Create(
@"goo
bar baz");
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.Lines[0].ToString());
Assert.Equal("bar baz", data.Lines[1].ToString());
}
[Fact]
public void LinesGetText2()
{
var data = Create("goo");
Assert.Equal("goo", data.Lines[0].ToString());
}
#if false
[Fact]
public void TextLine1()
{
var text = Create("goo" + Environment.NewLine);
var span = new TextSpan(0, 3);
var line = new TextLine(text, 0, 0, text.Length);
Assert.Equal(span, line.Extent);
Assert.Equal(5, line.EndIncludingLineBreak);
Assert.Equal(0, line.LineNumber);
}
[Fact]
public void GetText1()
{
var text = Create("goo");
var line = new TextLine(text, 0, 0, 2);
Assert.Equal("fo", line.ToString());
Assert.Equal(0, line.LineNumber);
}
[Fact]
public void GetText2()
{
var text = Create("abcdef");
var line = new TextLine(text, 0, 1, 2);
Assert.Equal("bc", line.ToString());
Assert.Equal(0, line.LineNumber);
}
#endif
[Fact]
public void GetExtendedAsciiText()
{
var originalText = Encoding.Default.GetString(new byte[] { 0xAB, 0xCD, 0xEF });
var encodedText = Create(originalText);
Assert.Equal(originalText, encodedText.ToString());
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/WithKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class WithKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public WithKeywordRecommender()
: base(SyntaxKind.WithKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class WithKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public WithKeywordRecommender()
: base(SyntaxKind.WithKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> !context.IsInNonUserCode && context.IsIsOrAsOrSwitchOrWithExpressionContext;
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/VisualStudio/Core/Def/Implementation/Workspace/GlobalUndoServiceFactory.NoOpUndoPrimitive.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class GlobalUndoServiceFactory
{
/// <summary>
/// no op undo primitive
/// </summary>
private class NoOpUndoPrimitive : ITextUndoPrimitive
{
public ITextUndoTransaction Parent { get; set; }
public bool CanRedo { get { return true; } }
public bool CanUndo { get { return true; } }
public void Do() { }
public void Undo() { }
public bool CanMerge(ITextUndoPrimitive older) => true;
public ITextUndoPrimitive Merge(ITextUndoPrimitive older) => older;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class GlobalUndoServiceFactory
{
/// <summary>
/// no op undo primitive
/// </summary>
private class NoOpUndoPrimitive : ITextUndoPrimitive
{
public ITextUndoTransaction Parent { get; set; }
public bool CanRedo { get { return true; } }
public bool CanUndo { get { return true; } }
public void Do() { }
public void Undo() { }
public bool CanMerge(ITextUndoPrimitive older) => true;
public ITextUndoPrimitive Merge(ITextUndoPrimitive older) => older;
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateMethod/GenerateMethodTests.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.VisualBasic.CodeFixes.GenerateMethod
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateMethod
Public Class GenerateMethodTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateParameterizedMemberCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationIntoSameType() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
<WorkItem(11518, "https://github.com/dotnet/roslyn/issues/11518")>
Public Async Function TestNameMatchesNamespaceName() As Task
Await TestInRegularAndScriptAsync(
"Namespace N
Module Module1
Sub Main()
[|N|]()
End Sub
End Module
End Namespace",
"Imports System
Namespace N
Module Module1
Sub Main()
N()
End Sub
Private Sub N()
Throw New NotImplementedException()
End Sub
End Module
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationOffOfMe() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Me.[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Me.Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationOffOfType() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
C.[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
C.Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationValueExpressionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](0)
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(0)
End Sub
Private Sub Goo(v As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationMultipleValueExpressionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](0, 0)
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(0, 0)
End Sub
Private Sub Goo(v1 As Integer, v2 As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationValueArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](i)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(i)
End Sub
Private Sub Goo(i As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationNamedValueArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](bar:=i)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(bar:=i)
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateAfterMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]()
End Sub
Sub NextMethod()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
Sub NextMethod()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInterfaceNaming() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod())
End Sub
Function NextMethod() As IGoo
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod())
End Sub
Private Sub Goo(goo As IGoo)
Throw New NotImplementedException()
End Sub
Function NextMethod() As IGoo
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFuncArg0() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Function NextMethod() As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As String)
Throw New NotImplementedException()
End Sub
Function NextMethod() As String
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFuncArg1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As Func(Of Integer, String))
Throw New NotImplementedException()
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class")
End Function
<WpfFact(Skip:="528229"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestAddressOf1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](AddressOf NextMethod)
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(AddressOf NextMethod)
End Sub
Private Sub Goo(nextMethod As Global.System.Func(Of Integer, String))
Throw New NotImplementedException()
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestActionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod) End Sub
Sub NextMethod()
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod) End Sub
Private Sub Goo(nextMethod As Object)
Throw New NotImplementedException()
End Sub
Sub NextMethod()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestActionArg1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Sub NextMethod(i As Integer)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As Action(Of Integer))
Throw New NotImplementedException()
End Sub
Sub NextMethod(i As Integer)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeInference() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
If [|Goo|]()
End If
End Sub
End Class",
"Imports System
Class C
Sub M()
If Goo()
End If
End Sub
Private Function Goo() As Boolean
Throw New NotImplementedException()
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMemberAccessArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](Me.Bar)
End Sub
Dim Bar As Integer
End Class",
"Imports System
Class C
Sub M()
Goo(Me.Bar)
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
Dim Bar As Integer
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParenthesizedArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]((Bar))
End Sub
Dim Bar As Integer
End Class",
"Imports System
Class C
Sub M()
Goo((Bar))
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
Dim Bar As Integer
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCastedArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](DirectCast(Me.Baz, Bar))
End Sub
End Class
Class Bar
End Class",
"Imports System
Class C
Sub M()
Goo(DirectCast(Me.Baz, Bar))
End Sub
Private Sub Goo(baz As Bar)
Throw New NotImplementedException()
End Sub
End Class
Class Bar
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDuplicateNames() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](DirectCast(Me.Baz, Bar), Me.Baz)
End Sub
Dim Baz As Integer
End Class
Class Bar
End Class",
"Imports System
Class C
Sub M()
Goo(DirectCast(Me.Baz, Bar), Me.Baz)
End Sub
Private Sub Goo(baz1 As Bar, baz2 As Integer)
Throw New NotImplementedException()
End Sub
Dim Baz As Integer
End Class
Class Bar
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgs1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo(Of Integer)|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(Of Integer)()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgs2() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo(Of Integer, String)|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(Of Integer, String)()
End Sub
Private Sub Goo(Of T1, T2)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgsFromMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(x As X, y As Y)
[|Goo|](x)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(x As X, y As Y)
Goo(x)
End Sub
Private Sub Goo(Of X)(x1 As X)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgThatIsTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X)(y1 As X(), x1 As System.Func(Of X))
[|Goo(Of X)|](y1, x1)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X)(y1 As X(), x1 As System.Func(Of X))
Goo(Of X)(y1, x1)
End Sub
Private Sub Goo(Of X)(y1() As X, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsThatAreTypeParameters() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(y1 As Y(), x1 As System.Func(Of X))
[|Goo(Of X, Y)|](y1, x1)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(y1 As Y(), x1 As System.Func(Of X))
Goo(Of X, Y)(y1, x1)
End Sub
Private Sub Goo(Of X, Y)(y1() As Y, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsFromMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(x As X, y As Y)
[|Goo|](x, y)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(x As X, y As Y)
Goo(x, y)
End Sub
Private Sub Goo(Of X, Y)(x1 As X, y1 As Y)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsFromMethod2() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(y As Y(), x As System.Func(Of X))
[|Goo|](y, x)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(y As Y(), x As System.Func(Of X))
Goo(y, x)
End Sub
Private Sub Goo(Of Y, X)(y1() As Y, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoOuterThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class Outer
Class C
Sub M(o As Outer)
o.[|Goo|]()
End Sub
End Class
End Class",
"Imports System
Class Outer
Class C
Sub M(o As Outer)
o.Goo()
End Sub
End Class
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoOuterThroughClass() As Task
Await TestInRegularAndScriptAsync(
"Class Outer
Class C
Sub M(o As Outer)
Outer.[|Goo|]()
End Sub
End Class
End Class",
"Imports System
Class Outer
Class C
Sub M(o As Outer)
Outer.Goo()
End Sub
End Class
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoSiblingThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As Sibling)
s.[|Goo|]()
End Sub
End Class
Class Sibling
End Class",
"Imports System
Class C
Sub M(s As Sibling)
s.Goo()
End Sub
End Class
Class Sibling
Friend Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoSiblingThroughClass() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As Sibling)
[|Sibling.Goo|]()
End Sub
End Class
Class Sibling
End Class",
"Imports System
Class C
Sub M(s As Sibling)
Sibling.Goo()
End Sub
End Class
Class Sibling
Friend Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoInterfaceThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As ISibling)
s.[|Goo|]()
End Sub
End Class
Interface ISibling
End Interface",
"Class C
Sub M(s As ISibling)
s.Goo()
End Sub
End Class
Interface ISibling
Sub Goo()
End Interface")
End Function
<WorkItem(29584, "https://github.com/dotnet/roslyn/issues/29584")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateAbstractIntoSameType() As Task
Await TestInRegularAndScriptAsync(
"MustInherit Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"MustInherit Class C
Sub M()
Goo()
End Sub
Protected MustOverride Sub Goo()
End Class",
index:=1)
End Function
<WorkItem(539297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539297")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoModule() As Task
Await TestInRegularAndScriptAsync(
"Module Class C
Sub M()
[|Goo|]()
End Sub
End Module",
"Imports System
Module Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(539506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539506")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInference1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Do While [|Goo|]()
Loop
End Sub
End Class",
"Imports System
Class C
Sub M()
Do While Goo()
Loop
End Sub
Private Function Goo() As Boolean
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539505")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestEscaping1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|[Sub]|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
[Sub]()
End Sub
Private Sub [Sub]()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539504")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestExplicitCall() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Call [|S|]
End Sub
End Class",
"Imports System
Class C
Sub M()
Call S
End Sub
Private Sub S()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539504")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestImplicitCall() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S|]
End Sub
End Class",
"Imports System
Class C
Sub M()
S
End Sub
Private Sub S()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539537")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArrayAccess1() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(x As Integer())
Goo([|x|](4))
End Sub
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterInteger() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S%|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S%()
End Sub
Private Function S() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterLong() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S&|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S&()
End Sub
Private Function S() As Long
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterDecimal() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S@|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S@()
End Sub
Private Function S() As Decimal
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterSingle() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S!|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S!()
End Sub
Private Function S() As Single
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterDouble() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S#|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S#()
End Sub
Private Function S() As Double
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterString() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S$|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S$()
End Sub
Private Function S() As String
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539283")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNewLines() As Task
Await TestInRegularAndScriptAsync(
<text>Public Class C
Sub M()
[|Goo|]()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Public Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(539283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539283")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNewLines2() As Task
Await TestInRegularAndScriptAsync(
<text>Public Class C
Sub M()
D.[|Goo|]()
End Sub
End Class
Public Class D
End Class</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Public Class C
Sub M()
D.Goo()
End Sub
End Class
Public Class D
Friend Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArgumentTypeVoid() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
Dim v As Void
[|Goo|](v)
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Dim v As Void
Goo(v)
End Sub
Private Sub Goo(v As Object)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateFromImplementsClause() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Bip(i As Integer) As String Implements [|IGoo.Snarf|]
End Function
End Class
Interface IGoo
End Interface",
"Class Program
Implements IGoo
Public Function Bip(i As Integer) As String Implements IGoo.Snarf
End Function
End Class
Interface IGoo
Function Snarf(i As Integer) As String
End Interface")
End Function
<WorkItem(537929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537929")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInScript1() As Task
Await TestAsync(
"Imports System
Shared Sub Main(args As String())
[|Goo|]()
End Sub",
"Imports System
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
",
parseOptions:=GetScriptOptions())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInTopLevelImplicitClass1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Shared Sub Main(args As String())
[|Goo|]()
End Sub",
"Imports System
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInNamespaceImplicitClass1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Namespace N
Shared Sub Main(args As String())
[|Goo|]()
End Sub
End Namespace",
"Imports System
Namespace N
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInNamespaceImplicitClass_FieldInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Namespace N
Dim a As Integer = [|Goo|]()
End Namespace",
"Imports System
Namespace N
Dim a As Integer = Goo()
Private Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod1() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Blah() As String Implements [|IGoo.Blah|]
End Function
End Class
Interface IGoo
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod2() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Blah() As String Implements [|IGoo.Blah|]
End Function
End Class
Interface IGoo
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod3() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Snarf() Implements [|IGoo.Blah|]
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
End Interface",
"Class C
Implements IGoo
Sub Snarf() Implements IGoo.Blah
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod4() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Snarf(i As String) Implements [|IGoo.Blah|]
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
End Interface",
"Class C
Implements IGoo
Sub Snarf(i As String) Implements IGoo.Blah
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
Sub Blah(i As String)
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod5() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Blah(i As Integer) Implements [|IGoo.Snarf|]
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As String)
End Interface",
"Class C
Implements IGoo
Sub Blah(i As Integer) Implements IGoo.Snarf
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As String)
Sub Snarf(i As Integer)
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod6() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Blah(i As Integer, s As String) Implements [|IGoo.Snarf|]
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As Integer, b As Boolean)
End Interface",
"Class C
Implements IGoo
Sub Blah(i As Integer, s As String) Implements IGoo.Snarf
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As Integer, b As Boolean)
Sub Snarf(i As Integer, s As String)
End Interface")
End Function
<WorkItem(539708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539708")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNoStaticGenerationIntoInterface() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class Program
Sub Main
IGoo.[|Bar|]
End Sub
End Class")
End Function
<WorkItem(539821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539821")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestEscapeParameterName() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim [string] As String = ""hello""
[|[Me]|]([string])
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim [string] As String = ""hello""
[Me]([string])
End Sub
Private Sub [Me]([string] As String)
Throw New System.NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(539810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539810")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotUseUnavailableTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Class Test
Sub M(Of T)(x As T)
[|Goo(Of Integer)|](x)
End Sub
End Class",
"Imports System
Class Test
Sub M(Of T)(x As T)
Goo(Of Integer)(x)
End Sub
Private Sub Goo(Of T)(x As T)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539808")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotUseTypeParametersFromContainingType() As Task
Await TestInRegularAndScriptAsync(
"Class Test(Of T)
Sub M()
[|Method(Of T)|]()
End Sub
End Class",
"Imports System
Class Test(Of T)
Sub M()
Method(Of T)()
End Sub
Private Sub Method(Of T1)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNameSimplification1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539809")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFormattingOfMembers() As Task
Await TestInRegularAndScriptAsync(
<Text>Class Test
Private id As Integer
Private name As String
Sub M()
[|Goo|](id)
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Imports System
Class Test
Private id As Integer
Private name As String
Sub M()
Goo(id)
End Sub
Private Sub Goo(id As Integer)
Throw New NotImplementedException()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(540013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540013")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInAddressOfExpression1() As Task
Await TestInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf [|Method|])
End Sub
End Class",
"Imports System
Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf Method)
End Sub
Private Sub Method(x As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(527986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527986")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOfferedForInferredGenericMethodArgs() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Goo(Of T)
Sub Main(Of T, X)(k As Goo(Of T))
[|Bar|](k)
End Sub
Private Sub Bar(Of T)(k As Goo(Of T))
End Sub
End Class")
End Function
<WorkItem(540740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540740")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDelegateInAsClause() As Task
Await TestInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Private Sub M()
Dim d As New D(AddressOf [|Test|])
End Sub
End Class",
"Imports System
Delegate Sub D(x As Integer)
Class C
Private Sub M()
Dim d As New D(AddressOf Test)
End Sub
Private Sub Test(x As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(541405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541405")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMissingOnImplementedInterfaceMethod() As Task
Await TestMissingInRegularAndScriptAsync(
"Class C(Of U)
Implements ITest
Public Sub Method(x As U) Implements [|ITest.Method|]
End Sub
End Class
Friend Interface ITest
Sub Method(x As Object)
End Interface")
End Function
<WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOnConstructorInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"Class C
Sub New
Me.[|New|](1)
End Sub
End Class")
End Function
<WorkItem(542838, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542838")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleImportsAdded() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
For Each v As Integer In [|HERE|]() : Next
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
For Each v As Integer In HERE() : Next
End Sub
Private Function HERE() As IEnumerable(Of Integer)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(543007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543007")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCompilationMemberImports() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For Each v As Integer In [|HERE|]() : Next
End Sub
End Module",
"Module Program
Sub Main(args As String())
For Each v As Integer In HERE() : Next
End Sub
Private Function HERE() As IEnumerable(Of Integer)
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections.Generic")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestForEachWithNoControlVariableType() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For Each v In [|HERE|] : Next
End Sub
End Module",
"Module Program
Sub Main(args As String())
For Each v In HERE : Next
End Sub
Private Function HERE() As IEnumerable(Of Object)
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections.Generic")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestElseIfStatement() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
If x Then
ElseIf [|HERE|] Then
End If
End Sub
End Module",
"Module Program
Sub Main(args As String())
If x Then
ElseIf HERE Then
End If
End Sub
Private Function HERE() As Boolean
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestForStatement() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For x As Integer = 1 To [|HERE|]
End Sub
End Module",
"Module Program
Sub Main(args As String())
For x As Integer = 1 To HERE
End Sub
Private Function HERE() As Integer
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System")))
End Function
<WorkItem(543216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543216")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArrayOfAnonymousTypes() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = """", Key .Price = 0}
Dim products = ToList(product)
[|HERE|](products)
End Sub
Function ToList(Of T)(a As T) As IEnumerable(Of T)
Return Nothing
End Function
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = """", Key .Price = 0}
Dim products = ToList(product)
HERE(products)
End Sub
Private Sub HERE(products As IEnumerable(Of Object))
Throw New NotImplementedException()
End Sub
Function ToList(Of T)(a As T) As IEnumerable(Of T)
Return Nothing
End Function
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMissingOnHiddenType() As Task
Await TestMissingInRegularAndScriptAsync(
<text>
#externalsource("file", num)
class C
sub Goo()
D.[|Bar|]()
end sub
end class
#end externalsource
class D
EndClass
</text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion1_NoImports() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
Sub Goo()
Bar()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion1_WithImports() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Imports System.Threading
#End ExternalSource
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Imports System
Imports System.Threading
#End ExternalSource
#ExternalSource ("file", num)
Class C
Private Sub Bar()
Throw New NotImplementedException()
End Sub
Sub Goo()
Bar()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion2() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
Bar()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion3() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Sub Quux()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
Bar()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
Sub Quux()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestAddressOfInference1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main(ByVal args As String())
Dim v As Func(Of String) = Nothing
Dim a1 = If(False, v, AddressOf [|TestMethod|])
End Sub
End Module",
"Imports System
Module Program
Sub Main(ByVal args As String())
Dim v As Func(Of String) = Nothing
Dim a1 = If(False, v, AddressOf TestMethod)
End Sub
Private Function TestMethod() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClassStatementTerminators1() As Task
Await TestInRegularAndScriptAsync(
"Class C : End Class
Class B
Sub Goo()
C.[|Bar|]()
End Sub
End Class",
"Imports System
Class C
Friend Shared Sub Bar()
Throw New NotImplementedException()
End Sub
End Class
Class B
Sub Goo()
C.Bar()
End Sub
End Class")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](,,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(,,)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional p2 As Object = Nothing, Optional p3 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1,,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1,,)
End Sub
Private Sub goo(v As Integer, Optional p1 As Object = Nothing, Optional p2 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](, 1,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(, 1,)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional v As Integer = Nothing, Optional p2 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments4() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](,, 1)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(,, 1)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional p2 As Object = Nothing, Optional v As Integer = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments5() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1,, 1)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1,, 1)
End Sub
Private Sub goo(v1 As Integer, Optional p As Object = Nothing, Optional v2 As Integer = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments6() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1, 1, )
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1, 1, )
End Sub
Private Sub goo(v1 As Integer, v2 As Integer, Optional p As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546683")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOnMissingMethodName() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M()
Me.[||]
End Sub
End Class")
End Function
<WorkItem(546684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546684")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateFromEventHandler() As Task
Await TestInRegularAndScriptAsync(
"Module Module1
Sub Main()
Dim c1 As New Class1
AddHandler c1.AnEvent, AddressOf [|EventHandler1|]
End Sub
Public Class Class1
Public Event AnEvent()
End Class
End Module",
"Imports System
Module Module1
Sub Main()
Dim c1 As New Class1
AddHandler c1.AnEvent, AddressOf EventHandler1
End Sub
Private Sub EventHandler1()
Throw New NotImplementedException()
End Sub
Public Class Class1
Public Event AnEvent()
End Class
End Module")
End Function
<WorkItem(530814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530814")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCapturedMethodTypeParameterThroughLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T, S)(x As List(Of T), y As List(Of S))
[|Bar|](x, Function() y) ' Generate Bar
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T, S)(x As List(Of T), y As List(Of S))
Bar(x, Function() y) ' Generate Bar
End Sub
Private Sub Bar(Of T, S)(x As List(Of T), p As Func(Of List(Of S)))
Throw New NotImplementedException()
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeParameterAndParameterConflict1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.[|Bar|](T:=x)
End Sub
End Class
Module M
End Module",
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.Bar(T:=x)
End Sub
End Class
Module M
Friend Sub Bar(Of T1)(T As T1)
End Sub
End Module")
End Function
<WorkItem(530968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530968")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeParameterAndParameterConflict2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.[|Bar|](t:=x) ' Generate Bar
End Sub
End Class
Module M
End Module",
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.Bar(t:=x) ' Generate Bar
End Sub
End Class
Module M
Friend Sub Bar(Of T1)(t As T1)
End Sub
End Module")
End Function
<WorkItem(546850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546850")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCollectionInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main(args As String())
[|Bar|](1, {1})
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
Bar(1, {1})
End Sub
Private Sub Bar(v As Integer, p() As Integer)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546925")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCollectionInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module M
Sub Main()
[|Goo|]({{1}})
End Sub
End Module",
"Imports System
Module M
Sub Main()
Goo({{1}})
End Sub
Private Sub Goo(p(,) As Integer)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(530818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530818")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParameterizedProperty1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
[|Prop|](1) = 2
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Prop(1) = 2
End Sub
Private Function Prop(v As Integer) As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(530818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530818")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParameterizedProperty2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
[|Prop|](1) = 2
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Prop(1) = 2
End Sub
Private Property Prop(v As Integer) As Integer
Get
Throw New NotImplementedException()
End Get
Set(value As Integer)
Throw New NotImplementedException()
End Set
End Property
End Module",
index:=1)
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_1() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
Baz([|Function()
Return ""
End Function|])
End Sub
Public Sub Baz()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_2() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
Baz([|Function()
Return ""
End Function|])
End Sub
Public Sub Baz(one As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz(one As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_3() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
[|Baz|](Function()
Return ""
End Function)
End Sub
Public Sub Baz(one As Func(Of String), two As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz(one As Func(Of String), two As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForDifferentParameterName() As Task
Await TestInRegularAndScriptAsync(
<text>
Class Program
Sub M()
[|M|](x:=3)
End Sub
Sub M(y As Integer)
M()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class Program
Sub M()
M(x:=3)
End Sub
Private Sub M(x As Integer)
Throw New NotImplementedException()
End Sub
Sub M(y As Integer)
M()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(769760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769760")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForSameNamedButGenericUsage_1() As Task
Await TestInRegularAndScriptAsync(
<text>
Class Program
Sub Main(args As String())
Goo()
[|Goo(Of Integer)|]()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Class Program
Sub Main(args As String())
Goo()
Goo(Of Integer)()
End Sub
Private Sub Goo(Of T)()
Throw New System.NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(769760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769760")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForSameNamedButGenericUsage_2() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Class Program
Sub Main(args As String())
Goo()
[|Goo(Of Integer, Integer)|]()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Sub Main(args As String())
Goo()
Goo(Of Integer, Integer)()
End Sub
Private Sub Goo(Of T1, T2)()
Throw New NotImplementedException()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(935731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/935731")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForAwaitWithoutParenthesis() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Async Sub Method_ASub()
Dim x = [|Await Goo|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Module Module1
Async Sub Method_ASub()
Dim x = Await Goo
End Sub
Private Function Goo() As Task(Of Object)
Throw New NotImplementedException()
End Function
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTooManyArgs1() As Task
Await TestInRegularAndScriptAsync(
<text>Module M1
Sub Main()
[|test("CC", 15, 45)|]
End Sub
Sub test(ByVal name As String, ByVal age As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module M1
Sub Main()
test("CC", 15, 45)
End Sub
Private Sub test(v1 As String, v2 As Integer, v3 As Integer)
Throw New NotImplementedException()
End Sub
Sub test(ByVal name As String, ByVal age As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNamespaceNotExpression1() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Module M1
Sub Goo()
[|Text|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module M1
Sub Goo()
Text
End Sub
Private Sub Text()
Throw New NotImplementedException()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoArgumentCountOverloadCandidates1() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0
Public whichOne As String
Sub Goo(ByVal t1 As String)
whichOne = "T"
End Sub
End Class
Class C1
Inherits C0
Overloads Sub Goo(ByVal y1 As String)
whichOne = "Y"
End Sub
End Class
Sub test()
Dim clsNarg2get As C1 = New C1()
[|clsNarg2get.Goo(1, y1:=2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0
Public whichOne As String
Sub Goo(ByVal t1 As String)
whichOne = "T"
End Sub
End Class
Class C1
Inherits C0
Overloads Sub Goo(ByVal y1 As String)
whichOne = "Y"
End Sub
Friend Sub Goo(v As Integer, y1 As Integer)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim clsNarg2get As C1 = New C1()
clsNarg2get.Goo(1, y1:=2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodFunctionResultCannotBeIndexed1() As Task
Await TestInRegularAndScriptAsync(
<text>Imports Microsoft.VisualBasic.FileSystem
Module M1
Sub goo()
If [|FreeFile(1)|] = 255 Then
End If
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports Microsoft.VisualBasic.FileSystem
Module M1
Sub goo()
If FreeFile(1) = 255 Then
End If
End Sub
Private Function FreeFile(v As Integer) As Integer
Throw New NotImplementedException()
End Function
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoCallableOverloadCandidates2() As Task
Await TestInRegularAndScriptAsync(
<text>Class M1
Sub sub1(Of U, V)(ByVal p1 As U, ByVal p2 As V)
End Sub
Sub sub1(Of U, V)(ByVal p1() As V, ByVal p2() As U)
End Sub
Sub GenMethod6210()
[|sub1(Of Integer, String)|](New Integer() {1, 2, 3}, New String() {"a", "b"})
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class M1
Sub sub1(Of U, V)(ByVal p1 As U, ByVal p2 As V)
End Sub
Sub sub1(Of U, V)(ByVal p1() As V, ByVal p2() As U)
End Sub
Sub GenMethod6210()
sub1(Of Integer, String)(New Integer() {1, 2, 3}, New String() {"a", "b"})
End Sub
Private Sub sub1(Of T1, T2)(vs1() As T1, vs2() As T2)
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates2() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Structure S1
Dim i As Integer
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
Return New C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
Return New S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Call [|tc2.Goo(New Scenario11)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
Friend Sub Goo(scenario11 As Scenario11)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
Dim i As Integer
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
Return New C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
Return New S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Call tc2.Goo(New Scenario11)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates3() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Dim sc11 As New Scenario11
Call [|tc2.Goo(sc11)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
Friend Sub Goo(sc11 As Scenario11)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Dim sc11 As New Scenario11
Call tc2.Goo(sc11)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates4() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim dTmp As Decimal = CDec(2000000)
Dim tc3 As New C1(Of Short, Long)
Call [|tc3.Goo(dTmp)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
Friend Sub Goo(dTmp As Decimal)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim dTmp As Decimal = CDec(2000000)
Dim tc3 As New C1(Of Short, Long)
Call tc3.Goo(dTmp)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sample7C1(Of Long).E.e1)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e1 As sample7C1(Of Long).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sample7C1(Of Long).E.e1)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing2() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sample7C1(Of Short).E.e2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e2 As sample7C1(Of Short).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sample7C1(Of Short).E.e2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing3() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sc7.E.e3)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e3 As sample7C1(Of Byte).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sc7.E.e3)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoMostSpecificOverload2() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
End Class
Structure S1
End Structure
Class C2
Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer)
End Operator
Public Shared Widening Operator CType(ByVal Arg As C2) As S1
End Operator
End Class
Sub test()
Dim C As New C1(Of S1, C1(Of Integer, Integer))
Call [|C.Goo(New C2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Friend Sub Goo(c2 As C2)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class C2
Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer)
End Operator
Public Shared Widening Operator CType(ByVal Arg As C2) As S1
End Operator
End Class
Sub test()
Dim C As New C1(Of S1, C1(Of Integer, Integer))
Call C.Goo(New C2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInsideNameOf() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Class C
Sub M()
Dim x = NameOf ([|Z|])
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
Dim x = NameOf (Z)
End Sub
Private Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInsideNameOf2() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Class C
Sub M()
Dim x = NameOf ([|Z.X.Y|])
End Sub
End Class
Namespace Z
Class X
End Class
End Namespace
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
Dim x = NameOf (Z.X.Y)
End Sub
End Class
Namespace Z
Class X
Friend Shared Function Y() As Object
Throw New NotImplementedException()
End Function
End Class
End Namespace
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithNameOfArgument() As Task
Await TestInRegularAndScriptAsync(
<text>
Class C
Sub M()
[|M2(NameOf(M))|]
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
M2(NameOf(M))
End Sub
Private Sub M2(v As String)
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambdaAndNameOfArgument() As Task
Await TestInRegularAndScriptAsync(
<text>
Class C
Sub M()
[|M2(Function() NameOf(M))|]
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
M2(Function() NameOf(M))
End Sub
Private Sub M2(p As Func(Of String))
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B
End Sub
Private Function B() As Object
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis5() As Task
Await TestInRegularAndScriptAsync(
"Option Strict On
Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Option Strict On
Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis6() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis7() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis8() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As C
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis9() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis10() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis11() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B()
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B()
End Sub
Private Function B() As Object
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B()
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B()
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B()
End Sub
Private ReadOnly Property B As C
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B()
End Sub
Private ReadOnly Property B As Object
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B()
End Sub
Private ReadOnly Property B As Integer
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B()
End Sub
Private ReadOnly Property B As C
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(39001, "https://github.com/dotnet/roslyn/issues/39001")>
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess5() As Task
Await TestInRegularAndScriptAsync(
"Public Structure C
Sub Main(a As C?)
Dim x As Integer? = a?[|.B|]()
End Sub
End Structure",
"Imports System
Public Structure C
Sub Main(a As C?)
Dim x As Integer? = a?.B()
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Structure")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Module Program
Property a As Integer = y
Private Function y() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalInPropertyInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Property a As Integer = [|y|]()
End Module",
"Imports System
Module Program
Property a As Integer = y()
Private Function y() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Imports System
Module C
Sub Test()
If TypeOf B Is String Then
End If
End Sub
Private Function B() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTypeOf2() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|]() Is String Then
End If
End Sub
End Module",
"Imports System
Module C
Sub Test()
If TypeOf B() Is String Then
End If
End Sub
Private Function B() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConfigureAwaitFalse() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await [|Goo|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await Goo().ConfigureAwait(False)
End Sub
Private Function Goo() As Task(Of Boolean)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConfigureAwaitFalse() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await [|Goo|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await Goo().ConfigureAwait(False)
End Sub
Private ReadOnly Property Goo As Task(Of Boolean)
Get
Throw New NotImplementedException()
End Get
End Property
End Module",
index:=1)
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithMethodChaining() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Linq
Module M
Async Sub T()
Dim x As Boolean = Await [|F|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Linq
Imports System.Threading.Tasks
Module M
Async Sub T()
Dim x As Boolean = Await F().ConfigureAwait(False)
End Sub
Private Function F() As Task(Of Boolean)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
Private Function Prop() As TypeOfIsNotDerived
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInCollectionInitializers1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New List(Of Integer) From {[|T|]()}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New List(Of Integer) From {T()}
End Sub
Private Function T() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInCollectionInitializers2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New Dictionary(Of Integer, Boolean) From {{1, [|T|]()}}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New Dictionary(Of Integer, Boolean) From {{1, T()}}
End Sub
Private Function T() As Boolean
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(10004, "https://github.com/dotnet/roslyn/issues/10004")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithMultipleOfSameGenericType() As Task
Await TestInRegularAndScriptAsync(
<text>
Namespace TestClasses
Public Class C
End Class
Module Ex
Public Function M(Of T As C)(a As T) As T
Return [|a.Test(Of T, T)()|]
End Function
End Module
End Namespace
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Namespace TestClasses
Public Class C
Friend Function Test(Of T1 As C, T2 As C)() As T2
End Function
End Class
Module Ex
Public Function M(Of T As C)(a As T) As T
Return a.Test(Of T, T)()
End Function
End Module
End Namespace
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(11461, "https://github.com/dotnet/roslyn/issues/11461")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodOffOfExistingProperty() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Public NotInheritable Class Repository
Shared ReadOnly Property agreementtype As AgreementType
Get
End Get
End Property
End Class
Public Class Agreementtype
End Class
Class C
Shared Sub TestError()
[|Repository.AgreementType.NewFunction|]("", "")
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Public NotInheritable Class Repository
Shared ReadOnly Property agreementtype As AgreementType
Get
End Get
End Property
End Class
Public Class Agreementtype
Friend Sub NewFunction(v1 As String, v2 As String)
Throw New NotImplementedException()
End Sub
End Class
Class C
Shared Sub TestError()
Repository.AgreementType.NewFunction("", "")
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTuple() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (Integer, String) = [|NewMethod|]((1, ""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (Integer, String) = NewMethod((1, ""hello""))
End Sub
Private Shared Function NewMethod(p As (Integer, String)) As (Integer, String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TupleElement1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = ([|Goo|](), """")
End Sub
End Class
",
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (Goo(), """")
End Sub
Private Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
")
End Function
<WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TupleElement2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (0, [|Goo|]())
End Sub
End Class
",
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (0, Goo())
End Sub
Private Function Goo() As String
Throw New NotImplementedException()
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTupleWithNames() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, b As String) = [|NewMethod|]((c:=1, d:=""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, b As String) = NewMethod((c:=1, d:=""hello""))
End Sub
Private Shared Function NewMethod(p As (c As Integer, d As String)) As (a As Integer, b As String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTupleWithOneName() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, String) = [|NewMethod|]((c:=1, ""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, String) = NewMethod((c:=1, ""hello""))
End Sub
Private Shared Function NewMethod(p As (c As Integer, String)) As (a As Integer, String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Enum Goo
One
End Enum",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Enum Goo
One
End Enum")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Delegate Sub Goo()",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Delegate Sub Goo()")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Class Goo
End Class",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Class Goo
End Class")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Structure Goo
End Structure",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Structure Goo
End Structure")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName5() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Interface Goo
End Interface",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Interface Goo
End Interface")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName6() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Namespace Goo
End Namespace",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Namespace Goo
End Namespace")
End Function
Public Class GenerateConversionTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateConversionCodeFixProvider())
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionGenericClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = CType([|1|], C(Of Integer))
End Sub
End Class
Class C(Of T)
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = CType(1, C(Of Integer))
End Sub
End Class
Class C(Of T)
Public Shared Narrowing Operator CType(v As Integer) As C(Of T)
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C = CType([|1|], C)
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C = CType(1, C)
End Sub
End Class
Class C
Public Shared Narrowing Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionAwaitExpression() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = CType([|Await a|], C)
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = CType(Await a, C)
End Sub
End Class
Class C
Public Shared Narrowing Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionTargetTypeNotInSource() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = [|dig|]
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = dig
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
Public Shared Widening Operator CType(v As Digit) As Double
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionGenericClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = [|1|]
End Sub
End Class
Class C(Of T)
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = 1
End Sub
End Class
Class C(Of T)
Public Shared Widening Operator CType(v As Integer) As C(Of T)
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C = [|1|]
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C = 1
End Sub
End Class
Class C
Public Shared Widening Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionAwaitExpression() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = [|Await a|]
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = Await a
End Sub
End Class
Class C
Public Shared Widening Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionTargetTypeNotInSource() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = CType([|dig|], Double)
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = CType(dig, Double)
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
Public Shared Narrowing Operator CType(v As Digit) As Double
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateMethod
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateMethod
Public Class GenerateMethodTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateParameterizedMemberCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationIntoSameType() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
<WorkItem(11518, "https://github.com/dotnet/roslyn/issues/11518")>
Public Async Function TestNameMatchesNamespaceName() As Task
Await TestInRegularAndScriptAsync(
"Namespace N
Module Module1
Sub Main()
[|N|]()
End Sub
End Module
End Namespace",
"Imports System
Namespace N
Module Module1
Sub Main()
N()
End Sub
Private Sub N()
Throw New NotImplementedException()
End Sub
End Module
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationOffOfMe() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Me.[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Me.Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationOffOfType() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
C.[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
C.Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationValueExpressionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](0)
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(0)
End Sub
Private Sub Goo(v As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationMultipleValueExpressionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](0, 0)
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(0, 0)
End Sub
Private Sub Goo(v1 As Integer, v2 As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationValueArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](i)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(i)
End Sub
Private Sub Goo(i As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestSimpleInvocationNamedValueArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](bar:=i)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(bar:=i)
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateAfterMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]()
End Sub
Sub NextMethod()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
Sub NextMethod()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInterfaceNaming() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod())
End Sub
Function NextMethod() As IGoo
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod())
End Sub
Private Sub Goo(goo As IGoo)
Throw New NotImplementedException()
End Sub
Function NextMethod() As IGoo
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFuncArg0() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Function NextMethod() As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As String)
Throw New NotImplementedException()
End Sub
Function NextMethod() As String
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFuncArg1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As Func(Of Integer, String))
Throw New NotImplementedException()
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class")
End Function
<WpfFact(Skip:="528229"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestAddressOf1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](AddressOf NextMethod)
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(AddressOf NextMethod)
End Sub
Private Sub Goo(nextMethod As Global.System.Func(Of Integer, String))
Throw New NotImplementedException()
End Sub
Function NextMethod(i As Integer) As String
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestActionArg() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod) End Sub
Sub NextMethod()
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod) End Sub
Private Sub Goo(nextMethod As Object)
Throw New NotImplementedException()
End Sub
Sub NextMethod()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestActionArg1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(i As Integer)
[|Goo|](NextMethod)
End Sub
Sub NextMethod(i As Integer)
End Sub
End Class",
"Imports System
Class C
Sub M(i As Integer)
Goo(NextMethod)
End Sub
Private Sub Goo(nextMethod As Action(Of Integer))
Throw New NotImplementedException()
End Sub
Sub NextMethod(i As Integer)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeInference() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
If [|Goo|]()
End If
End Sub
End Class",
"Imports System
Class C
Sub M()
If Goo()
End If
End Sub
Private Function Goo() As Boolean
Throw New NotImplementedException()
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMemberAccessArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](Me.Bar)
End Sub
Dim Bar As Integer
End Class",
"Imports System
Class C
Sub M()
Goo(Me.Bar)
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
Dim Bar As Integer
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParenthesizedArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|]((Bar))
End Sub
Dim Bar As Integer
End Class",
"Imports System
Class C
Sub M()
Goo((Bar))
End Sub
Private Sub Goo(bar As Integer)
Throw New NotImplementedException()
End Sub
Dim Bar As Integer
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCastedArgumentName() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](DirectCast(Me.Baz, Bar))
End Sub
End Class
Class Bar
End Class",
"Imports System
Class C
Sub M()
Goo(DirectCast(Me.Baz, Bar))
End Sub
Private Sub Goo(baz As Bar)
Throw New NotImplementedException()
End Sub
End Class
Class Bar
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDuplicateNames() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo|](DirectCast(Me.Baz, Bar), Me.Baz)
End Sub
Dim Baz As Integer
End Class
Class Bar
End Class",
"Imports System
Class C
Sub M()
Goo(DirectCast(Me.Baz, Bar), Me.Baz)
End Sub
Private Sub Goo(baz1 As Bar, baz2 As Integer)
Throw New NotImplementedException()
End Sub
Dim Baz As Integer
End Class
Class Bar
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgs1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo(Of Integer)|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(Of Integer)()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgs2() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|Goo(Of Integer, String)|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo(Of Integer, String)()
End Sub
Private Sub Goo(Of T1, T2)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgsFromMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(x As X, y As Y)
[|Goo|](x)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(x As X, y As Y)
Goo(x)
End Sub
Private Sub Goo(Of X)(x1 As X)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenericArgThatIsTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X)(y1 As X(), x1 As System.Func(Of X))
[|Goo(Of X)|](y1, x1)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X)(y1 As X(), x1 As System.Func(Of X))
Goo(Of X)(y1, x1)
End Sub
Private Sub Goo(Of X)(y1() As X, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsThatAreTypeParameters() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(y1 As Y(), x1 As System.Func(Of X))
[|Goo(Of X, Y)|](y1, x1)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(y1 As Y(), x1 As System.Func(Of X))
Goo(Of X, Y)(y1, x1)
End Sub
Private Sub Goo(Of X, Y)(y1() As Y, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsFromMethod() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(x As X, y As Y)
[|Goo|](x, y)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(x As X, y As Y)
Goo(x, y)
End Sub
Private Sub Goo(Of X, Y)(x1 As X, y1 As Y)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539984")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleGenericArgsFromMethod2() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(Of X, Y)(y As Y(), x As System.Func(Of X))
[|Goo|](y, x)
End Sub
End Class",
"Imports System
Class C
Sub M(Of X, Y)(y As Y(), x As System.Func(Of X))
Goo(y, x)
End Sub
Private Sub Goo(Of Y, X)(y1() As Y, x1 As Func(Of X))
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoOuterThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class Outer
Class C
Sub M(o As Outer)
o.[|Goo|]()
End Sub
End Class
End Class",
"Imports System
Class Outer
Class C
Sub M(o As Outer)
o.Goo()
End Sub
End Class
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoOuterThroughClass() As Task
Await TestInRegularAndScriptAsync(
"Class Outer
Class C
Sub M(o As Outer)
Outer.[|Goo|]()
End Sub
End Class
End Class",
"Imports System
Class Outer
Class C
Sub M(o As Outer)
Outer.Goo()
End Sub
End Class
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoSiblingThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As Sibling)
s.[|Goo|]()
End Sub
End Class
Class Sibling
End Class",
"Imports System
Class C
Sub M(s As Sibling)
s.Goo()
End Sub
End Class
Class Sibling
Friend Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoSiblingThroughClass() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As Sibling)
[|Sibling.Goo|]()
End Sub
End Class
Class Sibling
End Class",
"Imports System
Class C
Sub M(s As Sibling)
Sibling.Goo()
End Sub
End Class
Class Sibling
Friend Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoInterfaceThroughInstance() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M(s As ISibling)
s.[|Goo|]()
End Sub
End Class
Interface ISibling
End Interface",
"Class C
Sub M(s As ISibling)
s.Goo()
End Sub
End Class
Interface ISibling
Sub Goo()
End Interface")
End Function
<WorkItem(29584, "https://github.com/dotnet/roslyn/issues/29584")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateAbstractIntoSameType() As Task
Await TestInRegularAndScriptAsync(
"MustInherit Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"MustInherit Class C
Sub M()
Goo()
End Sub
Protected MustOverride Sub Goo()
End Class",
index:=1)
End Function
<WorkItem(539297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539297")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateIntoModule() As Task
Await TestInRegularAndScriptAsync(
"Module Class C
Sub M()
[|Goo|]()
End Sub
End Module",
"Imports System
Module Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(539506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539506")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInference1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Do While [|Goo|]()
Loop
End Sub
End Class",
"Imports System
Class C
Sub M()
Do While Goo()
Loop
End Sub
Private Function Goo() As Boolean
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539505")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestEscaping1() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|[Sub]|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
[Sub]()
End Sub
Private Sub [Sub]()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539504")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestExplicitCall() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
Call [|S|]
End Sub
End Class",
"Imports System
Class C
Sub M()
Call S
End Sub
Private Sub S()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539504")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestImplicitCall() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S|]
End Sub
End Class",
"Imports System
Class C
Sub M()
S
End Sub
Private Sub S()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539537")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArrayAccess1() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M(x As Integer())
Goo([|x|](4))
End Sub
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterInteger() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S%|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S%()
End Sub
Private Function S() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterLong() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S&|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S&()
End Sub
Private Function S() As Long
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterDecimal() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S@|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S@()
End Sub
Private Function S() As Decimal
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterSingle() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S!|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S!()
End Sub
Private Function S() As Single
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterDouble() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S#|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S#()
End Sub
Private Function S() As Double
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539560")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeCharacterString() As Task
Await TestInRegularAndScriptAsync(
"Class C
Sub M()
[|S$|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
S$()
End Sub
Private Function S() As String
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(539283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539283")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNewLines() As Task
Await TestInRegularAndScriptAsync(
<text>Public Class C
Sub M()
[|Goo|]()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Public Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(539283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539283")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNewLines2() As Task
Await TestInRegularAndScriptAsync(
<text>Public Class C
Sub M()
D.[|Goo|]()
End Sub
End Class
Public Class D
End Class</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Public Class C
Sub M()
D.Goo()
End Sub
End Class
Public Class D
Friend Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Class</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArgumentTypeVoid() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
Dim v As Void
[|Goo|](v)
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Dim v As Void
Goo(v)
End Sub
Private Sub Goo(v As Object)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateFromImplementsClause() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Bip(i As Integer) As String Implements [|IGoo.Snarf|]
End Function
End Class
Interface IGoo
End Interface",
"Class Program
Implements IGoo
Public Function Bip(i As Integer) As String Implements IGoo.Snarf
End Function
End Class
Interface IGoo
Function Snarf(i As Integer) As String
End Interface")
End Function
<WorkItem(537929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537929")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInScript1() As Task
Await TestAsync(
"Imports System
Shared Sub Main(args As String())
[|Goo|]()
End Sub",
"Imports System
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
",
parseOptions:=GetScriptOptions())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInTopLevelImplicitClass1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Shared Sub Main(args As String())
[|Goo|]()
End Sub",
"Imports System
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInNamespaceImplicitClass1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Namespace N
Shared Sub Main(args As String())
[|Goo|]()
End Sub
End Namespace",
"Imports System
Namespace N
Shared Sub Main(args As String())
Goo()
End Sub
Private Shared Sub Goo()
Throw New NotImplementedException()
End Sub
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInNamespaceImplicitClass_FieldInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Namespace N
Dim a As Integer = [|Goo|]()
End Namespace",
"Imports System
Namespace N
Dim a As Integer = Goo()
Private Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod1() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Blah() As String Implements [|IGoo.Blah|]
End Function
End Class
Interface IGoo
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod2() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Program
Implements IGoo
Public Function Blah() As String Implements [|IGoo.Blah|]
End Function
End Class
Interface IGoo
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod3() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Snarf() Implements [|IGoo.Blah|]
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
End Interface",
"Class C
Implements IGoo
Sub Snarf() Implements IGoo.Blah
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
Sub Blah()
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod4() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Snarf(i As String) Implements [|IGoo.Blah|]
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
End Interface",
"Class C
Implements IGoo
Sub Snarf(i As String) Implements IGoo.Blah
End Sub
End Class
Interface IGoo
Sub Blah(ByRef i As Integer)
Sub Blah(i As String)
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod5() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Blah(i As Integer) Implements [|IGoo.Snarf|]
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As String)
End Interface",
"Class C
Implements IGoo
Sub Blah(i As Integer) Implements IGoo.Snarf
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As String)
Sub Snarf(i As Integer)
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClashesWithMethod6() As Task
Await TestInRegularAndScriptAsync(
"Class C
Implements IGoo
Sub Blah(i As Integer, s As String) Implements [|IGoo.Snarf|]
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As Integer, b As Boolean)
End Interface",
"Class C
Implements IGoo
Sub Blah(i As Integer, s As String) Implements IGoo.Snarf
End Sub
End Class
Friend Interface IGoo
Sub Snarf(i As Integer, b As Boolean)
Sub Snarf(i As Integer, s As String)
End Interface")
End Function
<WorkItem(539708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539708")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNoStaticGenerationIntoInterface() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class Program
Sub Main
IGoo.[|Bar|]
End Sub
End Class")
End Function
<WorkItem(539821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539821")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestEscapeParameterName() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim [string] As String = ""hello""
[|[Me]|]([string])
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim [string] As String = ""hello""
[Me]([string])
End Sub
Private Sub [Me]([string] As String)
Throw New System.NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(539810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539810")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotUseUnavailableTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Class Test
Sub M(Of T)(x As T)
[|Goo(Of Integer)|](x)
End Sub
End Class",
"Imports System
Class Test
Sub M(Of T)(x As T)
Goo(Of Integer)(x)
End Sub
Private Sub Goo(Of T)(x As T)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539808")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotUseTypeParametersFromContainingType() As Task
Await TestInRegularAndScriptAsync(
"Class Test(Of T)
Sub M()
[|Method(Of T)|]()
End Sub
End Class",
"Imports System
Class Test(Of T)
Sub M()
Method(Of T)()
End Sub
Private Sub Method(Of T1)()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNameSimplification1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
[|Goo|]()
End Sub
End Class",
"Imports System
Class C
Sub M()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(539809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539809")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestFormattingOfMembers() As Task
Await TestInRegularAndScriptAsync(
<Text>Class Test
Private id As Integer
Private name As String
Sub M()
[|Goo|](id)
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Imports System
Class Test
Private id As Integer
Private name As String
Sub M()
Goo(id)
End Sub
Private Sub Goo(id As Integer)
Throw New NotImplementedException()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(540013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540013")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInAddressOfExpression1() As Task
Await TestInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf [|Method|])
End Sub
End Class",
"Imports System
Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf Method)
End Sub
Private Sub Method(x As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(527986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527986")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOfferedForInferredGenericMethodArgs() As Task
Await TestMissingInRegularAndScriptAsync(
"Class Goo(Of T)
Sub Main(Of T, X)(k As Goo(Of T))
[|Bar|](k)
End Sub
Private Sub Bar(Of T)(k As Goo(Of T))
End Sub
End Class")
End Function
<WorkItem(540740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540740")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDelegateInAsClause() As Task
Await TestInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Private Sub M()
Dim d As New D(AddressOf [|Test|])
End Sub
End Class",
"Imports System
Delegate Sub D(x As Integer)
Class C
Private Sub M()
Dim d As New D(AddressOf Test)
End Sub
Private Sub Test(x As Integer)
Throw New NotImplementedException()
End Sub
End Class")
End Function
<WorkItem(541405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541405")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMissingOnImplementedInterfaceMethod() As Task
Await TestMissingInRegularAndScriptAsync(
"Class C(Of U)
Implements ITest
Public Sub Method(x As U) Implements [|ITest.Method|]
End Sub
End Class
Friend Interface ITest
Sub Method(x As Object)
End Interface")
End Function
<WorkItem(542098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542098")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOnConstructorInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"Class C
Sub New
Me.[|New|](1)
End Sub
End Class")
End Function
<WorkItem(542838, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542838")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMultipleImportsAdded() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
For Each v As Integer In [|HERE|]() : Next
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
For Each v As Integer In HERE() : Next
End Sub
Private Function HERE() As IEnumerable(Of Integer)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(543007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543007")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCompilationMemberImports() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For Each v As Integer In [|HERE|]() : Next
End Sub
End Module",
"Module Program
Sub Main(args As String())
For Each v As Integer In HERE() : Next
End Sub
Private Function HERE() As IEnumerable(Of Integer)
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections.Generic")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestForEachWithNoControlVariableType() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For Each v In [|HERE|] : Next
End Sub
End Module",
"Module Program
Sub Main(args As String())
For Each v In HERE : Next
End Sub
Private Function HERE() As IEnumerable(Of Object)
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections.Generic")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestElseIfStatement() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
If x Then
ElseIf [|HERE|] Then
End If
End Sub
End Module",
"Module Program
Sub Main(args As String())
If x Then
ElseIf HERE Then
End If
End Sub
Private Function HERE() As Boolean
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System")))
End Function
<WorkItem(531301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531301")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestForStatement() As Task
Await TestAsync(
"Module Program
Sub Main(args As String())
For x As Integer = 1 To [|HERE|]
End Sub
End Module",
"Module Program
Sub Main(args As String())
For x As Integer = 1 To HERE
End Sub
Private Function HERE() As Integer
Throw New NotImplementedException()
End Function
End Module",
parseOptions:=Nothing,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithGlobalImports(GlobalImport.Parse("System")))
End Function
<WorkItem(543216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543216")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestArrayOfAnonymousTypes() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = """", Key .Price = 0}
Dim products = ToList(product)
[|HERE|](products)
End Sub
Function ToList(Of T)(a As T) As IEnumerable(Of T)
Return Nothing
End Function
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim product = New With {Key .Name = """", Key .Price = 0}
Dim products = ToList(product)
HERE(products)
End Sub
Private Sub HERE(products As IEnumerable(Of Object))
Throw New NotImplementedException()
End Sub
Function ToList(Of T)(a As T) As IEnumerable(Of T)
Return Nothing
End Function
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestMissingOnHiddenType() As Task
Await TestMissingInRegularAndScriptAsync(
<text>
#externalsource("file", num)
class C
sub Goo()
D.[|Bar|]()
end sub
end class
#end externalsource
class D
EndClass
</text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion1_NoImports() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
Sub Goo()
Bar()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion1_WithImports() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Imports System.Threading
#End ExternalSource
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Imports System
Imports System.Threading
#End ExternalSource
#ExternalSource ("file", num)
Class C
Private Sub Bar()
Throw New NotImplementedException()
End Sub
Sub Goo()
Bar()
#End ExternalSource
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion2() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
Bar()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestDoNotGenerateIntoHiddenRegion3() As Task
Await TestInRegularAndScriptAsync(
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
[|Bar|]()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Sub Quux()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf),
<text>
#ExternalSource ("file", num)
Class C
Sub Goo()
Bar()
#End ExternalSource
End Sub
Sub Baz()
#ExternalSource ("file", num)
End Sub
Private Sub Bar()
Throw New System.NotImplementedException()
End Sub
Sub Quux()
End Sub
End Class
#End ExternalSource
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestAddressOfInference1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main(ByVal args As String())
Dim v As Func(Of String) = Nothing
Dim a1 = If(False, v, AddressOf [|TestMethod|])
End Sub
End Module",
"Imports System
Module Program
Sub Main(ByVal args As String())
Dim v As Func(Of String) = Nothing
Dim a1 = If(False, v, AddressOf TestMethod)
End Sub
Private Function TestMethod() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(544641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544641")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestClassStatementTerminators1() As Task
Await TestInRegularAndScriptAsync(
"Class C : End Class
Class B
Sub Goo()
C.[|Bar|]()
End Sub
End Class",
"Imports System
Class C
Friend Shared Sub Bar()
Throw New NotImplementedException()
End Sub
End Class
Class B
Sub Goo()
C.Bar()
End Sub
End Class")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](,,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(,,)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional p2 As Object = Nothing, Optional p3 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1,,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1,,)
End Sub
Private Sub goo(v As Integer, Optional p1 As Object = Nothing, Optional p2 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](, 1,)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(, 1,)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional v As Integer = Nothing, Optional p2 As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments4() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](,, 1)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(,, 1)
End Sub
Private Sub goo(Optional p1 As Object = Nothing, Optional p2 As Object = Nothing, Optional v As Integer = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments5() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1,, 1)
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1,, 1)
End Sub
Private Sub goo(v1 As Integer, Optional p As Object = Nothing, Optional v2 As Integer = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546037")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestOmittedArguments6() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|goo|](1, 1, )
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
goo(1, 1, )
End Sub
Private Sub goo(v1 As Integer, v2 As Integer, Optional p As Object = Nothing)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546683")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestNotOnMissingMethodName() As Task
Await TestMissingInRegularAndScriptAsync("Class C
Sub M()
Me.[||]
End Sub
End Class")
End Function
<WorkItem(546684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546684")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateFromEventHandler() As Task
Await TestInRegularAndScriptAsync(
"Module Module1
Sub Main()
Dim c1 As New Class1
AddHandler c1.AnEvent, AddressOf [|EventHandler1|]
End Sub
Public Class Class1
Public Event AnEvent()
End Class
End Module",
"Imports System
Module Module1
Sub Main()
Dim c1 As New Class1
AddHandler c1.AnEvent, AddressOf EventHandler1
End Sub
Private Sub EventHandler1()
Throw New NotImplementedException()
End Sub
Public Class Class1
Public Event AnEvent()
End Class
End Module")
End Function
<WorkItem(530814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530814")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCapturedMethodTypeParameterThroughLambda() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T, S)(x As List(Of T), y As List(Of S))
[|Bar|](x, Function() y) ' Generate Bar
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T, S)(x As List(Of T), y As List(Of S))
Bar(x, Function() y) ' Generate Bar
End Sub
Private Sub Bar(Of T, S)(x As List(Of T), p As Func(Of List(Of S)))
Throw New NotImplementedException()
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeParameterAndParameterConflict1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.[|Bar|](T:=x)
End Sub
End Class
Module M
End Module",
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.Bar(T:=x)
End Sub
End Class
Module M
Friend Sub Bar(Of T1)(T As T1)
End Sub
End Module")
End Function
<WorkItem(530968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530968")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestTypeParameterAndParameterConflict2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.[|Bar|](t:=x) ' Generate Bar
End Sub
End Class
Module M
End Module",
"Imports System
Class C(Of T)
Sub Goo(x As T)
M.Bar(t:=x) ' Generate Bar
End Sub
End Class
Module M
Friend Sub Bar(Of T1)(t As T1)
End Sub
End Module")
End Function
<WorkItem(546850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546850")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCollectionInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main(args As String())
[|Bar|](1, {1})
End Sub
End Module",
"Imports System
Module Program
Sub Main(args As String())
Bar(1, {1})
End Sub
Private Sub Bar(v As Integer, p() As Integer)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(546925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546925")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestCollectionInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module M
Sub Main()
[|Goo|]({{1}})
End Sub
End Module",
"Imports System
Module M
Sub Main()
Goo({{1}})
End Sub
Private Sub Goo(p(,) As Integer)
Throw New NotImplementedException()
End Sub
End Module")
End Function
<WorkItem(530818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530818")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParameterizedProperty1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
[|Prop|](1) = 2
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Prop(1) = 2
End Sub
Private Function Prop(v As Integer) As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(530818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530818")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestParameterizedProperty2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main()
[|Prop|](1) = 2
End Sub
End Module",
"Imports System
Module Program
Sub Main()
Prop(1) = 2
End Sub
Private Property Prop(v As Integer) As Integer
Get
Throw New NotImplementedException()
End Get
Set(value As Integer)
Throw New NotImplementedException()
End Set
End Property
End Module",
index:=1)
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_1() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
Baz([|Function()
Return ""
End Function|])
End Sub
Public Sub Baz()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_2() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
Baz([|Function()
Return ""
End Function|])
End Sub
Public Sub Baz(one As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz(one As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(907612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907612")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambda_3() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Module Program
Public Sub CallIt()
[|Baz|](Function()
Return ""
End Function)
End Sub
Public Sub Baz(one As Func(Of String), two As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Module Program
Public Sub CallIt()
Baz(Function()
Return ""
End Function)
End Sub
Private Sub Baz(p As Func(Of String))
Throw New NotImplementedException()
End Sub
Public Sub Baz(one As Func(Of String), two As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForDifferentParameterName() As Task
Await TestInRegularAndScriptAsync(
<text>
Class Program
Sub M()
[|M|](x:=3)
End Sub
Sub M(y As Integer)
M()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class Program
Sub M()
M(x:=3)
End Sub
Private Sub M(x As Integer)
Throw New NotImplementedException()
End Sub
Sub M(y As Integer)
M()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(769760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769760")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForSameNamedButGenericUsage_1() As Task
Await TestInRegularAndScriptAsync(
<text>
Class Program
Sub Main(args As String())
Goo()
[|Goo(Of Integer)|]()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Class Program
Sub Main(args As String())
Goo()
Goo(Of Integer)()
End Sub
Private Sub Goo(Of T)()
Throw New System.NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(769760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769760")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForSameNamedButGenericUsage_2() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Class Program
Sub Main(args As String())
Goo()
[|Goo(Of Integer, Integer)|]()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Sub Main(args As String())
Goo()
Goo(Of Integer, Integer)()
End Sub
Private Sub Goo(Of T1, T2)()
Throw New NotImplementedException()
End Sub
Private Sub Goo(Of T)()
Throw New NotImplementedException()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(935731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/935731")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodForAwaitWithoutParenthesis() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Async Sub Method_ASub()
Dim x = [|Await Goo|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Module Module1
Async Sub Method_ASub()
Dim x = Await Goo
End Sub
Private Function Goo() As Task(Of Object)
Throw New NotImplementedException()
End Function
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTooManyArgs1() As Task
Await TestInRegularAndScriptAsync(
<text>Module M1
Sub Main()
[|test("CC", 15, 45)|]
End Sub
Sub test(ByVal name As String, ByVal age As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module M1
Sub Main()
test("CC", 15, 45)
End Sub
Private Sub test(v1 As String, v2 As Integer, v3 As Integer)
Throw New NotImplementedException()
End Sub
Sub test(ByVal name As String, ByVal age As Integer)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNamespaceNotExpression1() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Module M1
Sub Goo()
[|Text|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module M1
Sub Goo()
Text
End Sub
Private Sub Text()
Throw New NotImplementedException()
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoArgumentCountOverloadCandidates1() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0
Public whichOne As String
Sub Goo(ByVal t1 As String)
whichOne = "T"
End Sub
End Class
Class C1
Inherits C0
Overloads Sub Goo(ByVal y1 As String)
whichOne = "Y"
End Sub
End Class
Sub test()
Dim clsNarg2get As C1 = New C1()
[|clsNarg2get.Goo(1, y1:=2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0
Public whichOne As String
Sub Goo(ByVal t1 As String)
whichOne = "T"
End Sub
End Class
Class C1
Inherits C0
Overloads Sub Goo(ByVal y1 As String)
whichOne = "Y"
End Sub
Friend Sub Goo(v As Integer, y1 As Integer)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim clsNarg2get As C1 = New C1()
clsNarg2get.Goo(1, y1:=2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodFunctionResultCannotBeIndexed1() As Task
Await TestInRegularAndScriptAsync(
<text>Imports Microsoft.VisualBasic.FileSystem
Module M1
Sub goo()
If [|FreeFile(1)|] = 255 Then
End If
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports Microsoft.VisualBasic.FileSystem
Module M1
Sub goo()
If FreeFile(1) = 255 Then
End If
End Sub
Private Function FreeFile(v As Integer) As Integer
Throw New NotImplementedException()
End Function
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoCallableOverloadCandidates2() As Task
Await TestInRegularAndScriptAsync(
<text>Class M1
Sub sub1(Of U, V)(ByVal p1 As U, ByVal p2 As V)
End Sub
Sub sub1(Of U, V)(ByVal p1() As V, ByVal p2() As U)
End Sub
Sub GenMethod6210()
[|sub1(Of Integer, String)|](New Integer() {1, 2, 3}, New String() {"a", "b"})
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class M1
Sub sub1(Of U, V)(ByVal p1 As U, ByVal p2 As V)
End Sub
Sub sub1(Of U, V)(ByVal p1() As V, ByVal p2() As U)
End Sub
Sub GenMethod6210()
sub1(Of Integer, String)(New Integer() {1, 2, 3}, New String() {"a", "b"})
End Sub
Private Sub sub1(Of T1, T2)(vs1() As T1, vs2() As T2)
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates2() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Structure S1
Dim i As Integer
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
Return New C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
Return New S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Call [|tc2.Goo(New Scenario11)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
Get
End Get
Set(ByVal Value As Integer)
End Set
End Property
Friend Sub Goo(scenario11 As Scenario11)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
Dim i As Integer
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
Return New C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
Return New S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Call tc2.Goo(New Scenario11)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates3() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Dim sc11 As New Scenario11
Call [|tc2.Goo(sc11)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
Friend Sub Goo(sc11 As Scenario11)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim tc2 As New C1(Of S1, C1(Of Integer, Integer))
Dim sc11 As New Scenario11
Call tc2.Goo(sc11)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoNonNarrowingOverloadCandidates4() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim dTmp As Decimal = CDec(2000000)
Dim tc3 As New C1(Of Short, Long)
Call [|tc3.Goo(dTmp)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Public whichOne As String
Sub Goo(ByVal t1 As T)
End Sub
Default Property Prop1(ByVal t1 As T) As Integer
End Property
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Default Overloads Property Prop1(ByVal y1 As Y) As Integer
End Property
Friend Sub Goo(dTmp As Decimal)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class Scenario11
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As C1(Of Integer, Integer)
End Operator
Public Shared Narrowing Operator CType(ByVal Arg As Scenario11) As S1
End Operator
End Class
Sub GenUnif0060()
Dim dTmp As Decimal = CDec(2000000)
Dim tc3 As New C1(Of Short, Long)
Call tc3.Goo(dTmp)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sample7C1(Of Long).E.e1)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e1 As sample7C1(Of Long).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sample7C1(Of Long).E.e1)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing2() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sample7C1(Of Short).E.e2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e2 As sample7C1(Of Short).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sample7C1(Of Short).E.e2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodArgumentNarrowing3() As Task
Await TestInRegularAndScriptAsync(
<text>Option Strict Off
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call [|tc7.Goo(sc7.E.e3)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Option Strict Off
Imports System
Module Module1
Class sample7C1(Of X)
Enum E
e1
e2
e3
End Enum
End Class
Class sample7C2(Of T, Y)
Public whichOne As String
Sub Goo(ByVal p1 As sample7C1(Of T).E)
whichOne = "1"
End Sub
Sub Goo(ByVal p1 As sample7C1(Of Y).E)
whichOne = "2"
End Sub
Sub Scenario8(ByVal p1 As sample7C1(Of T).E)
Call Me.Goo(p1)
End Sub
Friend Sub Goo(e3 As sample7C1(Of Byte).E)
Throw New NotImplementedException()
End Sub
End Class
Sub test()
Dim tc7 As New sample7C2(Of Integer, Integer)
Dim sc7 As New sample7C1(Of Byte)
Call tc7.Goo(sc7.E.e3)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(939941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939941")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodNoMostSpecificOverload2() As Task
Await TestInRegularAndScriptAsync(
<text>Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
End Class
Structure S1
End Structure
Class C2
Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer)
End Operator
Public Shared Widening Operator CType(ByVal Arg As C2) As S1
End Operator
End Class
Sub test()
Dim C As New C1(Of S1, C1(Of Integer, Integer))
Call [|C.Goo(New C2)|]
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Module Module1
Class C0(Of T)
Sub Goo(ByVal t1 As T)
End Sub
End Class
Class C1(Of T, Y)
Inherits C0(Of T)
Overloads Sub Goo(ByVal y1 As Y)
End Sub
Friend Sub Goo(c2 As C2)
Throw New NotImplementedException()
End Sub
End Class
Structure S1
End Structure
Class C2
Public Shared Widening Operator CType(ByVal Arg As C2) As C1(Of Integer, Integer)
End Operator
Public Shared Widening Operator CType(ByVal Arg As C2) As S1
End Operator
End Class
Sub test()
Dim C As New C1(Of S1, C1(Of Integer, Integer))
Call C.Goo(New C2)
End Sub
End Module
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInsideNameOf() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Class C
Sub M()
Dim x = NameOf ([|Z|])
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
Dim x = NameOf (Z)
End Sub
Private Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInsideNameOf2() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Class C
Sub M()
Dim x = NameOf ([|Z.X.Y|])
End Sub
End Class
Namespace Z
Class X
End Class
End Namespace
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
Dim x = NameOf (Z.X.Y)
End Sub
End Class
Namespace Z
Class X
Friend Shared Function Y() As Object
Throw New NotImplementedException()
End Function
End Class
End Namespace
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithNameOfArgument() As Task
Await TestInRegularAndScriptAsync(
<text>
Class C
Sub M()
[|M2(NameOf(M))|]
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
M2(NameOf(M))
End Sub
Private Sub M2(v As String)
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithLambdaAndNameOfArgument() As Task
Await TestInRegularAndScriptAsync(
<text>
Class C
Sub M()
[|M2(Function() NameOf(M))|]
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Class C
Sub M()
M2(Function() NameOf(M))
End Sub
Private Sub M2(p As Func(Of String))
Throw New NotImplementedException()
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B
End Sub
Private Function B() As Object
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis5() As Task
Await TestInRegularAndScriptAsync(
"Option Strict On
Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Option Strict On
Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis6() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis7() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis8() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As C
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis9() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis10() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Integer
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccessNoParenthesis11() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Function Z() As Object
Throw New NotImplementedException()
End Function
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B()
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B()
End Sub
Private Function B() As Object
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B()
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B()
End Sub
Private Function B() As C
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B()
End Sub
Private ReadOnly Property B As C
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B()
End Sub
Private ReadOnly Property B As Object
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B()
End Sub
Private ReadOnly Property B As Integer
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConditionalAccess4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]()
End Sub
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C? = a?.B()
End Sub
Private ReadOnly Property B As C
Get
Throw New NotImplementedException()
End Get
End Property
End Class",
index:=1)
End Function
<WorkItem(39001, "https://github.com/dotnet/roslyn/issues/39001")>
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalAccess5() As Task
Await TestInRegularAndScriptAsync(
"Public Structure C
Sub Main(a As C?)
Dim x As Integer? = a?[|.B|]()
End Sub
End Structure",
"Imports System
Public Structure C
Sub Main(a As C?)
Dim x As Integer? = a?.B()
End Sub
Private Function B() As Integer
Throw New NotImplementedException()
End Function
End Structure")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Module Program
Property a As Integer = y
Private Function y() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConditionalInPropertyInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Property a As Integer = [|y|]()
End Module",
"Imports System
Module Program
Property a As Integer = y()
Private Function y() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Imports System
Module C
Sub Test()
If TypeOf B Is String Then
End If
End Sub
Private Function B() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodTypeOf2() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|]() Is String Then
End If
End Sub
End Module",
"Imports System
Module C
Sub Test()
If TypeOf B() Is String Then
End If
End Sub
Private Function B() As String
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodConfigureAwaitFalse() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await [|Goo|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await Goo().ConfigureAwait(False)
End Sub
Private Function Goo() As Task(Of Boolean)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyConfigureAwaitFalse() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await [|Goo|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Module Program
Async Sub Main(args As String())
Dim x As Boolean = Await Goo().ConfigureAwait(False)
End Sub
Private ReadOnly Property Goo As Task(Of Boolean)
Get
Throw New NotImplementedException()
End Get
End Property
End Module",
index:=1)
End Function
<WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithMethodChaining() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Linq
Module M
Async Sub T()
Dim x As Boolean = Await [|F|]().ConfigureAwait(False)
End Sub
End Module",
"Imports System
Imports System.Linq
Imports System.Threading.Tasks
Module M
Async Sub T()
Dim x As Boolean = Await F().ConfigureAwait(False)
End Sub
Private Function F() As Task(Of Boolean)
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
Private Function Prop() As TypeOfIsNotDerived
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInCollectionInitializers1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New List(Of Integer) From {[|T|]()}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New List(Of Integer) From {T()}
End Sub
Private Function T() As Integer
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestInCollectionInitializers2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New Dictionary(Of Integer, Boolean) From {{1, [|T|]()}}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Module Program
Sub M()
Dim x = New Dictionary(Of Integer, Boolean) From {{1, T()}}
End Sub
Private Function T() As Boolean
Throw New NotImplementedException()
End Function
End Module")
End Function
<WorkItem(10004, "https://github.com/dotnet/roslyn/issues/10004")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodWithMultipleOfSameGenericType() As Task
Await TestInRegularAndScriptAsync(
<text>
Namespace TestClasses
Public Class C
End Class
Module Ex
Public Function M(Of T As C)(a As T) As T
Return [|a.Test(Of T, T)()|]
End Function
End Module
End Namespace
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Namespace TestClasses
Public Class C
Friend Function Test(Of T1 As C, T2 As C)() As T2
End Function
End Class
Module Ex
Public Function M(Of T As C)(a As T) As T
Return a.Test(Of T, T)()
End Function
End Module
End Namespace
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(11461, "https://github.com/dotnet/roslyn/issues/11461")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateMethodOffOfExistingProperty() As Task
Await TestInRegularAndScriptAsync(
<text>
Imports System
Public NotInheritable Class Repository
Shared ReadOnly Property agreementtype As AgreementType
Get
End Get
End Property
End Class
Public Class Agreementtype
End Class
Class C
Shared Sub TestError()
[|Repository.AgreementType.NewFunction|]("", "")
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>
Imports System
Public NotInheritable Class Repository
Shared ReadOnly Property agreementtype As AgreementType
Get
End Get
End Property
End Class
Public Class Agreementtype
Friend Sub NewFunction(v1 As String, v2 As String)
Throw New NotImplementedException()
End Sub
End Class
Class C
Shared Sub TestError()
Repository.AgreementType.NewFunction("", "")
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTuple() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (Integer, String) = [|NewMethod|]((1, ""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (Integer, String) = NewMethod((1, ""hello""))
End Sub
Private Shared Function NewMethod(p As (Integer, String)) As (Integer, String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TupleElement1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = ([|Goo|](), """")
End Sub
End Class
",
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (Goo(), """")
End Sub
Private Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
")
End Function
<WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TupleElement2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (0, [|Goo|]())
End Sub
End Class
",
"
Imports System
Public Class Q
Sub Main()
Dim x As (Integer, String) = (0, Goo())
End Sub
Private Function Goo() As String
Throw New NotImplementedException()
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTupleWithNames() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, b As String) = [|NewMethod|]((c:=1, d:=""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, b As String) = NewMethod((c:=1, d:=""hello""))
End Sub
Private Shared Function NewMethod(p As (c As Integer, d As String)) As (a As Integer, b As String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function MethodWithTupleWithOneName() As Task
Await TestInRegularAndScriptAsync(
"Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, String) = [|NewMethod|]((c:=1, ""hello""))
End Sub
End Class",
"Imports System
Class Program
Private Shared Async Sub Main(args As String())
Dim d As (a As Integer, String) = NewMethod((c:=1, ""hello""))
End Sub
Private Shared Function NewMethod(p As (c As Integer, String)) As (a As Integer, String)
Throw New NotImplementedException()
End Function
End Class")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Enum Goo
One
End Enum",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Enum Goo
One
End Enum")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Delegate Sub Goo()",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Delegate Sub Goo()")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Class Goo
End Class",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Class Goo
End Class")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Structure Goo
End Structure",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Structure Goo
End Structure")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName5() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Interface Goo
End Interface",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Interface Goo
End Interface")
End Function
<WorkItem(16975, "https://github.com/dotnet/roslyn/issues/16975")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestWithSameMethodNameAsTypeName6() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub Bar()
[|Goo|]()
End Sub
End Class
Namespace Goo
End Namespace",
"Imports System
Class C
Sub Bar()
Goo()
End Sub
Private Sub Goo()
Throw New NotImplementedException()
End Sub
End Class
Namespace Goo
End Namespace")
End Function
Public Class GenerateConversionTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateConversionCodeFixProvider())
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionGenericClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = CType([|1|], C(Of Integer))
End Sub
End Class
Class C(Of T)
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = CType(1, C(Of Integer))
End Sub
End Class
Class C(Of T)
Public Shared Narrowing Operator CType(v As Integer) As C(Of T)
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C = CType([|1|], C)
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C = CType(1, C)
End Sub
End Class
Class C
Public Shared Narrowing Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionAwaitExpression() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = CType([|Await a|], C)
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = CType(Await a, C)
End Sub
End Class
Class C
Public Shared Narrowing Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionTargetTypeNotInSource() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = [|dig|]
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = dig
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
Public Shared Widening Operator CType(v As Digit) As Double
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionGenericClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = [|1|]
End Sub
End Class
Class C(Of T)
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C(Of Integer) = 1
End Sub
End Class
Class C(Of T)
Public Shared Widening Operator CType(v As Integer) As C(Of T)
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionClass() As Task
Await TestInRegularAndScriptAsync(
<text>Class Program
Private Shared Sub Main(args As String())
Dim a As C = [|1|]
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Class Program
Private Shared Sub Main(args As String())
Dim a As C = 1
End Sub
End Class
Class C
Public Shared Widening Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateImplicitConversionAwaitExpression() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = [|Await a|]
End Sub
End Class
Class C
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim a = Task.FromResult(1)
Dim b As C = Await a
End Sub
End Class
Class C
Public Shared Widening Operator CType(v As Integer) As C
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGenerateExplicitConversionTargetTypeNotInSource() As Task
Await TestInRegularAndScriptAsync(
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = CType([|dig|], Double)
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
End Class
</text>.Value.Replace(vbLf, vbCrLf),
<text>Imports System
Imports System.Threading.Tasks
Class Program
Private Shared Async Sub Main(args As String())
Dim dig As Digit = New Digit(7)
Dim number As Double = CType(dig, Double)
End Sub
End Class
Class Digit
Private val As Double
Public Sub New(v As Double)
Me.val = v
End Sub
Public Shared Narrowing Operator CType(v As Digit) As Double
Throw New NotImplementedException()
End Operator
End Class
</text>.Value.Replace(vbLf, vbCrLf))
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/BinaryConditionalExpressionDocumentation.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.Utilities.IntrinsicOperators
Friend NotInheritable Class BinaryConditionalExpressionDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing
End Get
End Property
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing
Case 1
Return VBWorkspaceResources.Evaluated_and_returned_if_expression_evaluates_to_Nothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.expression
Case 1
Return VBWorkspaceResources.expressionIfNothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 2
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "If"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")}
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.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Friend NotInheritable Class BinaryConditionalExpressionDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing
End Get
End Property
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing
Case 1
Return VBWorkspaceResources.Evaluated_and_returned_if_expression_evaluates_to_Nothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.expression
Case 1
Return VBWorkspaceResources.expressionIfNothing
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 2
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "If"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")}
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Test/Semantic/Semantics/BindingAwaitTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAwaitTests : CompilingTestBase
{
[WorkItem(547172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547172")]
[Fact, WorkItem(531516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531516")]
public void Bug18241()
{
var tree = SyntaxFactory.ParseSyntaxTree(" class C { void M() { await X() on ");
SourceText text = tree.GetText();
TextSpan span = new TextSpan(text.Length, 0);
TextChange change = new TextChange(span, "/*comment*/");
SourceText newText = text.WithChanges(change);
// This line caused an assertion and then crashed in the parser.
var newTree = tree.WithChangedText(newText);
}
[Fact]
public void AwaitBadExpression()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await goo;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,15): error CS0103: The name 'goo' does not exist in the current context
// await goo;
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
}
[Fact]
public void MissingGetAwaiterInstanceMethod()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS1061: 'A' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?)
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new A()").WithArguments("A", "GetAwaiter")
);
}
[Fact]
public void InaccessibleGetAwaiterInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
}
}
class A
{
Awaiter GetAwaiter() { return new Awaiter(); }
}
class B
{
private Awaiter GetAwaiter() { return new Awaiter(); }
}
class C
{
protected Awaiter GetAwaiter() { return new Awaiter(); }
}
class D
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0122: 'A.GetAwaiter()' is inaccessible due to its protection level
// await new A();
Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("A.GetAwaiter()"),
// (11,9): error CS0122: 'B.GetAwaiter()' is inaccessible due to its protection level
// await new B();
Diagnostic(ErrorCode.ERR_BadAccess, "await new B()").WithArguments("B.GetAwaiter()"),
// (12,9): error CS0122: 'C.GetAwaiter()' is inaccessible due to its protection level
// await new C();
Diagnostic(ErrorCode.ERR_BadAccess, "await new C()").WithArguments("C.GetAwaiter()")
);
}
[Fact]
public void StaticGetAwaiterMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class B
{
public static Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type B have a suitable GetAwaiter method
// await new B();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new B()").WithArguments("B")
);
}
[Fact]
public void GetAwaiterFieldOrProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B(null);
}
}
class A
{
Awaiter GetAwaiter { get { return new Awaiter(); } }
}
class B
{
public Awaiter GetAwaiter;
public B(Awaiter getAwaiter)
{
this.GetAwaiter = getAwaiter;
}
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1955: Non-invocable member 'A.GetAwaiter' cannot be used like a method.
// await new A();
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new A()").WithArguments("A.GetAwaiter"),
// (11,9): error CS1955: Non-invocable member 'B.GetAwaiter' cannot be used like a method.
// await new B(null);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new B(null)").WithArguments("B.GetAwaiter")
);
}
[Fact]
public void GetAwaiterParams()
{
var source = @"
using System;
public class A
{
public Awaiter GetAwaiter(params object[] xs) { throw new Exception(); }
}
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (22,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void VoidReturningGetAwaiterMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public void GetAwaiter() { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void InaccessibleGetAwaiterExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
}
}
class A { }
class B { }
class C { }
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
private static Awaiter GetAwaiter(this B a)
{
return new Awaiter();
}
public static Awaiter GetAwaiter(this C a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,15): error CS1929: 'A' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C'
// await new A();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new A()").WithArguments("A", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C"),
// (11,15): error CS1929: 'B' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C'
// await new B();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new B()").WithArguments("B", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C")
);
}
[Fact]
public void GetAwaiterExtensionMethodLookup()
{
var source = @"
using System;
class A { }
class B { }
class C { }
static class Test
{
static async void F()
{
new A().GetAwaiter();
new B().GetAwaiter();
new C().GetAwaiter();
await new A();
await new B();
await new C();
}
static Awaiter GetAwaiter(this A a) { throw new Exception(); }
static void GetAwaiter(this B a) { throw new Exception(); }
}
static class E
{
public static void GetAwaiter(this A a) { throw new Exception(); }
public static Awaiter GetAwaiter(this B a) { throw new Exception(); }
public static Awaiter GetAwaiter(this C a) { throw new Exception(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// new A().GetAwaiter();
Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"),
// (15,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)'
// new B().GetAwaiter();
Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)"),
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"),
// (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)'
// await new B();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new B()").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)")
);
}
[Fact]
public void ExtensionDuellingLookup()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class E
{
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (31,9): error CS0121: The call is ambiguous between the following methods or properties: 'E.GetAwaiter(I1)' and 'E.GetAwaiter(I2)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E.GetAwaiter(I1)", "E.GetAwaiter(I2)")
);
}
[Fact]
public void ExtensionDuellingMoreDerivedMoreOptional()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionDuellingLessDerivedLessOptional()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static void GetAwaiter(this A a, object o = null) { throw new Exception(); }
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionSiblingLookupOnExtraOptionalParam()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a, object o = null) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnVoidReturn()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"));
}
[Fact]
public void ExtensionSiblingLookupOnInapplicable()
{
var source = @"
using System;
public class A { }
public class B { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this B a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnOptional()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this object a, object o = null) { throw new Exception(); }
}
public static class E
{
public static void GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionSiblingDuellingLookupOne()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
public static class E1
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionSiblingDuellingLookupTwo()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
public static class E1
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionSiblingLookupOnLessDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnEquallyDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this object a) { throw new Exception(); }
}
public static class EE
{
public static void GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)")
);
}
[Fact]
public void ExtensionSiblingBadLookupOnEquallyDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
public static class EE
{
public static Awaiter GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)")
);
}
[Fact]
public void ExtensionParentNamespaceLookupOnOnReturnTypeMismatch()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,17): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceLookupOnOnInapplicableCandidate()
{
var source = @"
using System;
public class A { }
public class B { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this B a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionParentNamespaceLookupOnOptional()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); }
}
}
public static class EE
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceLookupOnLessDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
}
public static class EE
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceDuellingLookupBad()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
public static class E1
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionParentNamespaceDuellingLookupWasGoodNowBad()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
public static class E1
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionParentNamespaceSingleClassDuel()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void TruncateExtensionMethodLookupAfterFirstNamespace()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
public static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void BadTruncateExtensionMethodLookupAfterFirstNamespace()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
public static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void FallbackToGetAwaiterExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
private Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void BadFallbackToGetAwaiterExtensionMethodInPresenceOfInstanceGetAwaiterMethodWithOptionalParameter()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter(object o = null) { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void GetAwaiterMethodWithNonZeroArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
await new E();
}
}
class A
{
public Awaiter GetAwaiter(object o = null) { return null; }
}
class B
{
public Awaiter GetAwaiter(object o) { return null; }
}
class C
{
}
class D
{
}
class E
{
public Awaiter GetAwaiter() { return null; }
public Awaiter GetAwaiter(object o = null) { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this C a, object o = null)
{
return new Awaiter();
}
public static Awaiter GetAwaiter(this D a, object o)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A").WithLocation(10, 9),
// (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'B.GetAwaiter(object)'
// await new B();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "await new B()").WithArguments("o", "B.GetAwaiter(object)").WithLocation(11, 9),
// (12,9): error CS1986: 'await' requires that the type C have a suitable GetAwaiter method
// await new C();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new C()").WithArguments("C").WithLocation(12, 9),
// (13,15): error CS1929: 'D' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C, object)' requires a receiver of type 'C'
// await new D();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new D()").WithArguments("D", "GetAwaiter", "MyExtensions.GetAwaiter(C, object)", "C").WithLocation(13, 15));
}
[Fact]
public void GetAwaiterMethodWithNonZeroTypeParameterArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter<T>() { return null; }
}
class B
{
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter<T>(this B a)
{
return null;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'A.GetAwaiter<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new A();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("A.GetAwaiter<T>()"),
// (11,9): error CS0411: The type arguments for method 'MyExtensions.GetAwaiter<T>(B)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new B();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new B()").WithArguments("MyExtensions.GetAwaiter<T>(B)")
);
}
[Fact]
public void AwaiterImplementsINotifyCompletion()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
}
}
class A
{
public Awaiter1 GetAwaiter() { return null; }
}
class B
{
public Awaiter2 GetAwaiter() { return null; }
}
class C
{
public Awaiter3 GetAwaiter() { return null; }
}
class D
{
public Awaiter4 GetAwaiter() { return null; }
}
class Awaiter1 : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
class OnCompletedImpl : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
}
class Awaiter2 : OnCompletedImpl
{
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
interface OnCompletedInterface : System.Runtime.CompilerServices.INotifyCompletion
{
}
class Awaiter3 : OnCompletedInterface
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
class Awaiter4
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (13,9): error CS4027: 'Awaiter4' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new D();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new D()").WithArguments("Awaiter4", "System.Runtime.CompilerServices.INotifyCompletion"));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_Constraint()
{
var source =
@"using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA
{
bool IsCompleted { get; }
object GetResult();
}
interface IB : IA, INotifyCompletion
{
}
class A
{
public void OnCompleted(System.Action a) { }
internal bool IsCompleted { get { return true; } }
internal object GetResult() { return null; }
}
class B : A, INotifyCompletion
{
}
class C
{
static async void F<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()
where T1 : IA
where T2 : IA, INotifyCompletion
where T3 : IB
where T4 : T1, INotifyCompletion
where T5 : T3
where T6 : A
where T7 : A, INotifyCompletion
where T8 : B
where T9 : T6, INotifyCompletion
where T10 : T8
{
await new Awaitable<T1>();
await new Awaitable<T2>();
await new Awaitable<T3>();
await new Awaitable<T4>();
await new Awaitable<T5>();
await new Awaitable<T6>();
await new Awaitable<T7>();
await new Awaitable<T8>();
await new Awaitable<T9>();
await new Awaitable<T10>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (37,9): error CS4027: 'T1' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<T1>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T1>()").WithArguments("T1", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(37, 9),
// (42,9): error CS4027: 'T6' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<T6>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T6>()").WithArguments("T6", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(42, 9));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_InheritedConstraint()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA
{
bool IsCompleted { get; }
object GetResult();
}
interface IB : IA, INotifyCompletion
{
}
class B : IA, INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
struct S : IA, INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class C<T> where T : IA
{
internal virtual async void F<U>() where U : T
{
await new Awaitable<U>();
}
}
class D1 : C<IB>
{
internal override async void F<T1>()
{
await new Awaitable<T1>();
}
}
class D2 : C<B>
{
internal override async void F<T2>()
{
await new Awaitable<T2>();
}
}
class D3 : C<S>
{
internal override async void F<T3>()
{
await new Awaitable<T3>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (31,9): error CS4027: 'U' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<U>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<U>()").WithArguments("U", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(31, 9),
// (52,9): error CS0117: 'T3' does not contain a definition for 'IsCompleted'
// await new Awaitable<T3>();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new Awaitable<T3>()").WithArguments("T3", "IsCompleted").WithLocation(52, 9));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_UserDefinedConversion()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA : INotifyCompletion
{
bool IsCompleted { get; }
object GetResult();
}
class A : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class B
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public static implicit operator A(B b) { return default(A); }
}
class B<T> where T : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public static implicit operator T(B<T> b) { return default(T); }
}
class C
{
async void F()
{
await new Awaitable<B>();
await new Awaitable<B<IA>>();
await new Awaitable<B<A>>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (34,9): error CS4027: 'B' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B>()").WithArguments("B", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(34, 9),
// (35,9): error CS4027: 'B<IA>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B<IA>>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<IA>>()").WithArguments("B<IA>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(35, 9),
// (36,9): error CS4027: 'B<A>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B<A>>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<A>>()").WithArguments("B<A>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(36, 9));
}
/// <summary>
/// Should call ICriticalNotifyCompletion.UnsafeOnCompleted
/// if the awaiter type implements ICriticalNotifyCompletion.
/// </summary>
[Fact]
public void AwaiterImplementsICriticalNotifyCompletion_Constraint()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
class A : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class B : A, ICriticalNotifyCompletion
{
public void UnsafeOnCompleted(Action a) { }
}
class C
{
static async void F<T1, T2, T3, T4, T5, T6>()
where T1 : A
where T2 : A, ICriticalNotifyCompletion
where T3 : B
where T4 : T1
where T5 : T2
where T6 : T1, ICriticalNotifyCompletion
{
await new Awaitable<T1>();
await new Awaitable<T2>();
await new Awaitable<T3>();
await new Awaitable<T4>();
await new Awaitable<T5>();
await new Awaitable<T6>();
}
}";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var verifier = CompileAndVerify(compilation);
var actualIL = verifier.VisualizeIL("C.<F>d__0<T1, T2, T3, T4, T5, T6>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()");
var calls = actualIL.Split(new[] { '\n', '\r' }, System.StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("OnCompleted")).ToArray();
Assert.Equal(6, calls.Length);
Assert.Equal(" IL_0056: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T1, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T1, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[0]);
Assert.Equal(" IL_00b9: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T2, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T2, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[1]);
Assert.Equal(" IL_011c: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T3, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T3, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[2]);
Assert.Equal(" IL_0182: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T4, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T4, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[3]);
Assert.Equal(" IL_01ea: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T5, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T5, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[4]);
Assert.Equal(" IL_0252: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T6, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T6, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[5]);
}
[Fact]
public void ConditionalOnCompletedImplementation()
{
var source = @"
using System;
using System.Diagnostics;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class B
{
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
[Conditional(""Condition"")]
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this B a)
{
return null;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (28,17): error CS0629: Conditional member 'Awaiter.OnCompleted(System.Action)' cannot implement interface member 'System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)' in type 'Awaiter'
// public void OnCompleted(Action x) { }
Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "OnCompleted").WithArguments("Awaiter.OnCompleted(System.Action)", "System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)", "Awaiter"));
}
[Fact]
public void MissingIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void InaccessibleIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void StaticIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void StaticWriteonlyIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void StaticAccessorlessIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (25,24): error CS0548: 'Awaiter.IsCompleted': property or indexer must have at least one accessor
// public static bool IsCompleted { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "IsCompleted").WithArguments("Awaiter.IsCompleted"),
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void NonBooleanIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public int IsCompleted { get { return -1; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void WriteonlyIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted"));
}
[Fact]
public void WriteonlyNonBooleanIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public int IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted"));
}
[Fact]
public void MissingGetResultInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult"));
}
[Fact]
public void InaccessibleGetResultInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
private bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0122: 'Awaiter.GetResult()' is inaccessible due to its protection level
// await new A();
Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("Awaiter.GetResult()")
);
}
[Fact]
public void StaticResultMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public static bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.GetResult()"));
}
[Fact]
public void GetResultExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool IsCompleted { get { return false; } }
}
static class MyExtensions
{
public static bool GetResult(this Awaiter a)
{
throw new Exception();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult"));
}
[Fact]
public void GetResultWithNonZeroArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult(object o = null) { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void GetResultWithNonZeroTypeParameterArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult<T>() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'Awaiter.GetResult<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new A();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("Awaiter.GetResult<T>()")
);
}
[Fact]
public void ConditionalGetResult()
{
var source = @"
using System;
using System.Diagnostics;
static class Program
{
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
[Conditional(""X"")]
public void GetResult() { Console.WriteLine(""unconditional""); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (15,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void Missing_IsCompleted_INotifyCompletion_GetResult()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion
{
//public void OnCompleted(Action x) { }
//public bool GetResult() { throw new Exception(); }
//public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void Missing_INotifyCompletion_GetResult()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion
{
//public void OnCompleted(Action x) { }
//public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS4027: 'Awaiter' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new A();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new A()").WithArguments("Awaiter", "System.Runtime.CompilerServices.INotifyCompletion"));
}
[Fact]
public void BadAwaitArg_NeedSystem()
{
var source = @"
// using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
class App {
static void Main() {
EnumDevices().Wait();
}
private static async Task EnumDevices() {
await DeviceInformation.FindAllAsync();
return;
}
}";
CreateCompilationWithWinRT(source).VerifyDiagnostics(
// (12,9): error CS4035: 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' could be found (are you missing a using directive for 'System'?)
// await DeviceInformation.FindAllAsync();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, "await DeviceInformation.FindAllAsync()").WithArguments("Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>", "GetAwaiter", "System")
);
}
[Fact]
public void ErrorInAwaitSubexpression()
{
var source = @"
class C
{
async void M()
{
using (await goo())
{
}
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,22): error CS0103: The name 'goo' does not exist in the current context
// using (await goo())
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
}
[Fact]
public void BadAwaitArgIntrinsic()
{
var source = @"
class Test
{
public void goo() { }
public async void awaitVoid()
{
await goo();
}
public async void awaitNull()
{
await null;
}
public async void awaitMethodGroup()
{
await goo;
}
public async void awaitLambda()
{
await (x => x);
}
public static void Main() { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS4008: Cannot await 'void'
// await goo();
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"),
// (13,9): error CS4001: Cannot await '<null>;'
// await null;
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await null").WithArguments("<null>"),
// (18,9): error CS4001: Cannot await 'method group'
// await goo;
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await goo").WithArguments("method group"),
// (23,9): error CS4001: Cannot await 'lambda expression'
// await (x => x);
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await (x => x)").WithArguments("lambda expression"));
}
[Fact]
public void BadAwaitArgVoidCall()
{
var source = @"
using System.Threading.Tasks;
class Test
{
public async void goo()
{
await Task.Factory.StartNew(() => { });
}
public async void bar()
{
await goo();
}
public static void Main() { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4008: Cannot await 'void'
// await goo();
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"));
}
[Fact, WorkItem(531356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531356")]
public void Repro_17997()
{
var source = @"
class C
{
public IVsTask ResolveReferenceAsync()
{
return this.VsTasksService.InvokeAsync(async delegate
{
return null;
});
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,12): error CS0246: The type or namespace name 'IVsTask' could not be found (are you missing a using directive or an assembly reference?)
// public IVsTask ResolveReferenceAsync()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVsTask").WithArguments("IVsTask").WithLocation(4, 12),
// (6,21): error CS1061: 'C' does not contain a definition for 'VsTasksService' and no extension method 'VsTasksService' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// return this.VsTasksService.InvokeAsync(async delegate
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "VsTasksService").WithArguments("C", "VsTasksService").WithLocation(6, 21),
// (6,54): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// return this.VsTasksService.InvokeAsync(async delegate
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(6, 54));
}
[Fact, WorkItem(627123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627123")]
public void Repro_627123()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
interface IA : INotifyCompletion
{
bool IsCompleted { get; }
void GetResult();
}
interface IB : IA
{
new Action GetResult { get; }
}
interface IC
{
IB GetAwaiter();
}
class D
{
Action<IC> a = async x => await x;
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,31): error CS0118: 'GetResult' is a property but is used like a method
// Action<IC> a = async x => await x;
Diagnostic(ErrorCode.ERR_BadSKknown, "await x").WithArguments("GetResult", "property", "method")
);
}
[Fact, WorkItem(1091911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091911")]
public void Repro_1091911()
{
const string source = @"
using System;
using System.Threading.Tasks;
class Repro
{
int Boom { get { return 42; } }
static Task<dynamic> Compute()
{
return Task.FromResult<dynamic>(new Repro());
}
static async Task<int> Bug()
{
dynamic results = await Compute().ConfigureAwait(false);
var x = results.Boom;
return (int)x;
}
static void Main()
{
Console.WriteLine(Bug().Result);
}
}";
var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void DynamicResultTypeCustomAwaiter()
{
const string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
public struct MyTask
{
public readonly Task task;
private readonly Func<dynamic> getResult;
public MyTask(Task task, Func<dynamic> getResult)
{
this.task = task;
this.getResult = getResult;
}
public dynamic Result { get { return this.getResult(); } }
}
public struct MyAwaiter : INotifyCompletion
{
private readonly MyTask task;
public MyAwaiter(MyTask task)
{
this.task = task;
}
public bool IsCompleted { get { return true; } }
public dynamic GetResult() { Console.Write(""dynamic""); return task.Result; }
public void OnCompleted(System.Action continuation) { task.task.ContinueWith(_ => continuation()); }
}
public static class TaskAwaiter
{
public static MyAwaiter GetAwaiter(this MyTask task)
{
return new MyAwaiter(task);
}
}
class Repro
{
int Boom { get { return 42; } }
static MyTask Compute()
{
var task = Task.FromResult(new Repro());
return new MyTask(task, () => task.Result);
}
static async Task<int> Bug()
{
return (await Compute()).Boom;
}
static void Main()
{
Console.WriteLine(Bug().Result);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, new[] { TestMetadata.Net40.SystemCore, TestMetadata.Net40.MicrosoftCSharp }, TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// warning CS1685: The predefined type 'ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
Diagnostic(ErrorCode.WRN_MultiplePredefTypes).WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(1, 1));
var compiled = CompileAndVerify(comp, expectedOutput: "dynamic42", verify: Verification.Fails);
compiled.VerifyIL("MyAwaiter.OnCompleted(System.Action)", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (MyAwaiter.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""MyAwaiter.<>c__DisplayClass5_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.1
IL_0008: stfld ""System.Action MyAwaiter.<>c__DisplayClass5_0.continuation""
IL_000d: ldarg.0
IL_000e: ldflda ""MyTask MyAwaiter.task""
IL_0013: ldfld ""System.Threading.Tasks.Task MyTask.task""
IL_0018: ldloc.0
IL_0019: ldftn ""void MyAwaiter.<>c__DisplayClass5_0.<OnCompleted>b__0(System.Threading.Tasks.Task)""
IL_001f: newobj ""System.Action<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)""
IL_0024: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.Task.ContinueWith(System.Action<System.Threading.Tasks.Task>)""
IL_0029: pop
IL_002a: 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.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAwaitTests : CompilingTestBase
{
[WorkItem(547172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547172")]
[Fact, WorkItem(531516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531516")]
public void Bug18241()
{
var tree = SyntaxFactory.ParseSyntaxTree(" class C { void M() { await X() on ");
SourceText text = tree.GetText();
TextSpan span = new TextSpan(text.Length, 0);
TextChange change = new TextChange(span, "/*comment*/");
SourceText newText = text.WithChanges(change);
// This line caused an assertion and then crashed in the parser.
var newTree = tree.WithChangedText(newText);
}
[Fact]
public void AwaitBadExpression()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await goo;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,15): error CS0103: The name 'goo' does not exist in the current context
// await goo;
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
}
[Fact]
public void MissingGetAwaiterInstanceMethod()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS1061: 'A' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?)
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await new A()").WithArguments("A", "GetAwaiter")
);
}
[Fact]
public void InaccessibleGetAwaiterInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
}
}
class A
{
Awaiter GetAwaiter() { return new Awaiter(); }
}
class B
{
private Awaiter GetAwaiter() { return new Awaiter(); }
}
class C
{
protected Awaiter GetAwaiter() { return new Awaiter(); }
}
class D
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0122: 'A.GetAwaiter()' is inaccessible due to its protection level
// await new A();
Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("A.GetAwaiter()"),
// (11,9): error CS0122: 'B.GetAwaiter()' is inaccessible due to its protection level
// await new B();
Diagnostic(ErrorCode.ERR_BadAccess, "await new B()").WithArguments("B.GetAwaiter()"),
// (12,9): error CS0122: 'C.GetAwaiter()' is inaccessible due to its protection level
// await new C();
Diagnostic(ErrorCode.ERR_BadAccess, "await new C()").WithArguments("C.GetAwaiter()")
);
}
[Fact]
public void StaticGetAwaiterMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class B
{
public static Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type B have a suitable GetAwaiter method
// await new B();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new B()").WithArguments("B")
);
}
[Fact]
public void GetAwaiterFieldOrProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B(null);
}
}
class A
{
Awaiter GetAwaiter { get { return new Awaiter(); } }
}
class B
{
public Awaiter GetAwaiter;
public B(Awaiter getAwaiter)
{
this.GetAwaiter = getAwaiter;
}
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1955: Non-invocable member 'A.GetAwaiter' cannot be used like a method.
// await new A();
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new A()").WithArguments("A.GetAwaiter"),
// (11,9): error CS1955: Non-invocable member 'B.GetAwaiter' cannot be used like a method.
// await new B(null);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "await new B(null)").WithArguments("B.GetAwaiter")
);
}
[Fact]
public void GetAwaiterParams()
{
var source = @"
using System;
public class A
{
public Awaiter GetAwaiter(params object[] xs) { throw new Exception(); }
}
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (22,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void VoidReturningGetAwaiterMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public void GetAwaiter() { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void InaccessibleGetAwaiterExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
}
}
class A { }
class B { }
class C { }
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
private static Awaiter GetAwaiter(this B a)
{
return new Awaiter();
}
public static Awaiter GetAwaiter(this C a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,15): error CS1929: 'A' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C'
// await new A();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new A()").WithArguments("A", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C"),
// (11,15): error CS1929: 'B' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C)' requires a receiver of type 'C'
// await new B();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new B()").WithArguments("B", "GetAwaiter", "MyExtensions.GetAwaiter(C)", "C")
);
}
[Fact]
public void GetAwaiterExtensionMethodLookup()
{
var source = @"
using System;
class A { }
class B { }
class C { }
static class Test
{
static async void F()
{
new A().GetAwaiter();
new B().GetAwaiter();
new C().GetAwaiter();
await new A();
await new B();
await new C();
}
static Awaiter GetAwaiter(this A a) { throw new Exception(); }
static void GetAwaiter(this B a) { throw new Exception(); }
}
static class E
{
public static void GetAwaiter(this A a) { throw new Exception(); }
public static Awaiter GetAwaiter(this B a) { throw new Exception(); }
public static Awaiter GetAwaiter(this C a) { throw new Exception(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// new A().GetAwaiter();
Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"),
// (15,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)'
// new B().GetAwaiter();
Diagnostic(ErrorCode.ERR_AmbigCall, "GetAwaiter").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)"),
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"),
// (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(B)' and 'E.GetAwaiter(B)'
// await new B();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new B()").WithArguments("Test.GetAwaiter(B)", "E.GetAwaiter(B)")
);
}
[Fact]
public void ExtensionDuellingLookup()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class E
{
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this I2 a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (31,9): error CS0121: The call is ambiguous between the following methods or properties: 'E.GetAwaiter(I1)' and 'E.GetAwaiter(I2)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E.GetAwaiter(I1)", "E.GetAwaiter(I2)")
);
}
[Fact]
public void ExtensionDuellingMoreDerivedMoreOptional()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionDuellingLessDerivedLessOptional()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
public static void GetAwaiter(this A a, object o = null) { throw new Exception(); }
public static Awaiter GetAwaiter(this I1 a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionSiblingLookupOnExtraOptionalParam()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a, object o = null) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnVoidReturn()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(A)' and 'E.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(A)", "E.GetAwaiter(A)"));
}
[Fact]
public void ExtensionSiblingLookupOnInapplicable()
{
var source = @"
using System;
public class A { }
public class B { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this B a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnOptional()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this object a, object o = null) { throw new Exception(); }
}
public static class E
{
public static void GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionSiblingDuellingLookupOne()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
public static class E1
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionSiblingDuellingLookupTwo()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
public static class E1
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (20,9): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionSiblingLookupOnLessDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
public static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionSiblingLookupOnEquallyDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this object a) { throw new Exception(); }
}
public static class EE
{
public static void GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)")
);
}
[Fact]
public void ExtensionSiblingBadLookupOnEquallyDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
public static class EE
{
public static Awaiter GetAwaiter(this object a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.GetAwaiter(object)' and 'EE.GetAwaiter(object)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("Test.GetAwaiter(object)", "EE.GetAwaiter(object)")
);
}
[Fact]
public void ExtensionParentNamespaceLookupOnOnReturnTypeMismatch()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this A a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (24,17): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceLookupOnOnInapplicableCandidate()
{
var source = @"
using System;
public class A { }
public class B { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static async void F()
{
await new A();
}
public static void GetAwaiter(this B a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void ExtensionParentNamespaceLookupOnOptional()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static Awaiter GetAwaiter(this A a, object o = null) { throw new Exception(); }
}
}
public static class EE
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceLookupOnLessDerived()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
static class Test
{
static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this object a) { throw new Exception(); }
}
}
public static class EE
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void ExtensionParentNamespaceDuellingLookupBad()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
public static class E1
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionParentNamespaceDuellingLookupWasGoodNowBad()
{
var source = @"
using System;
public class A { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
public static class E1
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
public static class E2
{
public static void GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,13): error CS0121: The call is ambiguous between the following methods or properties: 'E1.GetAwaiter(A)' and 'E2.GetAwaiter(A)'
// await new A();
Diagnostic(ErrorCode.ERR_AmbigCall, "await new A()").WithArguments("E1.GetAwaiter(A)", "E2.GetAwaiter(A)")
);
}
[Fact]
public void ExtensionParentNamespaceSingleClassDuel()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
static async void F()
{
await new A();
}
static void Main()
{
F();
}
}
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void TruncateExtensionMethodLookupAfterFirstNamespace()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
public static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void BadTruncateExtensionMethodLookupAfterFirstNamespace()
{
var source = @"
using System;
public interface I1 { }
public interface I2 { }
public class A : I1, I2 { }
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(System.Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
namespace parent
{
namespace child
{
public static class Test
{
public static void Main()
{
F();
}
static async void F()
{
await new A();
}
public static void GetAwaiter(this I1 a) { throw new Exception(); }
}
}
public static class E
{
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}
}
public static class E2
{
public static void GetAwaiter(this I1 a) { throw new Exception(); }
public static Awaiter GetAwaiter(this A a) { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (11,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void FallbackToGetAwaiterExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
private Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
}
[Fact]
public void BadFallbackToGetAwaiterExtensionMethodInPresenceOfInstanceGetAwaiterMethodWithOptionalParameter()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter(object o = null) { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this A a)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A"));
}
[Fact]
public void GetAwaiterMethodWithNonZeroArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
await new E();
}
}
class A
{
public Awaiter GetAwaiter(object o = null) { return null; }
}
class B
{
public Awaiter GetAwaiter(object o) { return null; }
}
class C
{
}
class D
{
}
class E
{
public Awaiter GetAwaiter() { return null; }
public Awaiter GetAwaiter(object o = null) { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this C a, object o = null)
{
return new Awaiter();
}
public static Awaiter GetAwaiter(this D a, object o)
{
return new Awaiter();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS1986: 'await' requires that the type A have a suitable GetAwaiter method
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new A()").WithArguments("A").WithLocation(10, 9),
// (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'B.GetAwaiter(object)'
// await new B();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "await new B()").WithArguments("o", "B.GetAwaiter(object)").WithLocation(11, 9),
// (12,9): error CS1986: 'await' requires that the type C have a suitable GetAwaiter method
// await new C();
Diagnostic(ErrorCode.ERR_BadAwaitArg, "await new C()").WithArguments("C").WithLocation(12, 9),
// (13,15): error CS1929: 'D' does not contain a definition for 'GetAwaiter' and the best extension method overload 'MyExtensions.GetAwaiter(C, object)' requires a receiver of type 'C'
// await new D();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new D()").WithArguments("D", "GetAwaiter", "MyExtensions.GetAwaiter(C, object)", "C").WithLocation(13, 15));
}
[Fact]
public void GetAwaiterMethodWithNonZeroTypeParameterArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter<T>() { return null; }
}
class B
{
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter<T>(this B a)
{
return null;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'A.GetAwaiter<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new A();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("A.GetAwaiter<T>()"),
// (11,9): error CS0411: The type arguments for method 'MyExtensions.GetAwaiter<T>(B)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new B();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new B()").WithArguments("MyExtensions.GetAwaiter<T>(B)")
);
}
[Fact]
public void AwaiterImplementsINotifyCompletion()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
await new C();
await new D();
}
}
class A
{
public Awaiter1 GetAwaiter() { return null; }
}
class B
{
public Awaiter2 GetAwaiter() { return null; }
}
class C
{
public Awaiter3 GetAwaiter() { return null; }
}
class D
{
public Awaiter4 GetAwaiter() { return null; }
}
class Awaiter1 : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
class OnCompletedImpl : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
}
class Awaiter2 : OnCompletedImpl
{
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
interface OnCompletedInterface : System.Runtime.CompilerServices.INotifyCompletion
{
}
class Awaiter3 : OnCompletedInterface
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
class Awaiter4
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (13,9): error CS4027: 'Awaiter4' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new D();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new D()").WithArguments("Awaiter4", "System.Runtime.CompilerServices.INotifyCompletion"));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_Constraint()
{
var source =
@"using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA
{
bool IsCompleted { get; }
object GetResult();
}
interface IB : IA, INotifyCompletion
{
}
class A
{
public void OnCompleted(System.Action a) { }
internal bool IsCompleted { get { return true; } }
internal object GetResult() { return null; }
}
class B : A, INotifyCompletion
{
}
class C
{
static async void F<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()
where T1 : IA
where T2 : IA, INotifyCompletion
where T3 : IB
where T4 : T1, INotifyCompletion
where T5 : T3
where T6 : A
where T7 : A, INotifyCompletion
where T8 : B
where T9 : T6, INotifyCompletion
where T10 : T8
{
await new Awaitable<T1>();
await new Awaitable<T2>();
await new Awaitable<T3>();
await new Awaitable<T4>();
await new Awaitable<T5>();
await new Awaitable<T6>();
await new Awaitable<T7>();
await new Awaitable<T8>();
await new Awaitable<T9>();
await new Awaitable<T10>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (37,9): error CS4027: 'T1' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<T1>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T1>()").WithArguments("T1", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(37, 9),
// (42,9): error CS4027: 'T6' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<T6>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<T6>()").WithArguments("T6", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(42, 9));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_InheritedConstraint()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA
{
bool IsCompleted { get; }
object GetResult();
}
interface IB : IA, INotifyCompletion
{
}
class B : IA, INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
struct S : IA, INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class C<T> where T : IA
{
internal virtual async void F<U>() where U : T
{
await new Awaitable<U>();
}
}
class D1 : C<IB>
{
internal override async void F<T1>()
{
await new Awaitable<T1>();
}
}
class D2 : C<B>
{
internal override async void F<T2>()
{
await new Awaitable<T2>();
}
}
class D3 : C<S>
{
internal override async void F<T3>()
{
await new Awaitable<T3>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (31,9): error CS4027: 'U' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<U>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<U>()").WithArguments("U", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(31, 9),
// (52,9): error CS0117: 'T3' does not contain a definition for 'IsCompleted'
// await new Awaitable<T3>();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new Awaitable<T3>()").WithArguments("T3", "IsCompleted").WithLocation(52, 9));
}
[WorkItem(770448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770448")]
[Fact]
public void AwaiterImplementsINotifyCompletion_UserDefinedConversion()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
interface IA : INotifyCompletion
{
bool IsCompleted { get; }
object GetResult();
}
class A : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class B
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public static implicit operator A(B b) { return default(A); }
}
class B<T> where T : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public static implicit operator T(B<T> b) { return default(T); }
}
class C
{
async void F()
{
await new Awaitable<B>();
await new Awaitable<B<IA>>();
await new Awaitable<B<A>>();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (34,9): error CS4027: 'B' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B>()").WithArguments("B", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(34, 9),
// (35,9): error CS4027: 'B<IA>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B<IA>>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<IA>>()").WithArguments("B<IA>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(35, 9),
// (36,9): error CS4027: 'B<A>' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new Awaitable<B<A>>();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new Awaitable<B<A>>()").WithArguments("B<A>", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(36, 9));
}
/// <summary>
/// Should call ICriticalNotifyCompletion.UnsafeOnCompleted
/// if the awaiter type implements ICriticalNotifyCompletion.
/// </summary>
[Fact]
public void AwaiterImplementsICriticalNotifyCompletion_Constraint()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Awaitable<T>
{
internal T GetAwaiter() { return default(T); }
}
class A : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted { get { return true; } }
public object GetResult() { return null; }
}
class B : A, ICriticalNotifyCompletion
{
public void UnsafeOnCompleted(Action a) { }
}
class C
{
static async void F<T1, T2, T3, T4, T5, T6>()
where T1 : A
where T2 : A, ICriticalNotifyCompletion
where T3 : B
where T4 : T1
where T5 : T2
where T6 : T1, ICriticalNotifyCompletion
{
await new Awaitable<T1>();
await new Awaitable<T2>();
await new Awaitable<T3>();
await new Awaitable<T4>();
await new Awaitable<T5>();
await new Awaitable<T6>();
}
}";
var compilation = CreateCompilationWithMscorlib45(source).VerifyDiagnostics();
var verifier = CompileAndVerify(compilation);
var actualIL = verifier.VisualizeIL("C.<F>d__0<T1, T2, T3, T4, T5, T6>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()");
var calls = actualIL.Split(new[] { '\n', '\r' }, System.StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("OnCompleted")).ToArray();
Assert.Equal(6, calls.Length);
Assert.Equal(" IL_0056: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T1, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T1, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[0]);
Assert.Equal(" IL_00b9: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T2, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T2, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[1]);
Assert.Equal(" IL_011c: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T3, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T3, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[2]);
Assert.Equal(" IL_0182: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<T4, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T4, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[3]);
Assert.Equal(" IL_01ea: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T5, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T5, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[4]);
Assert.Equal(" IL_0252: call \"void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<T6, C.<F>d__0<T1, T2, T3, T4, T5, T6>>(ref T6, ref C.<F>d__0<T1, T2, T3, T4, T5, T6>)\"", calls[5]);
}
[Fact]
public void ConditionalOnCompletedImplementation()
{
var source = @"
using System;
using System.Diagnostics;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
await new B();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class B
{
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
[Conditional(""Condition"")]
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}
static class MyExtensions
{
public static Awaiter GetAwaiter(this B a)
{
return null;
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (28,17): error CS0629: Conditional member 'Awaiter.OnCompleted(System.Action)' cannot implement interface member 'System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)' in type 'Awaiter'
// public void OnCompleted(Action x) { }
Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "OnCompleted").WithArguments("Awaiter.OnCompleted(System.Action)", "System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)", "Awaiter"));
}
[Fact]
public void MissingIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void InaccessibleIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void StaticIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void StaticWriteonlyIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void StaticAccessorlessIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public static bool IsCompleted { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (25,24): error CS0548: 'Awaiter.IsCompleted': property or indexer must have at least one accessor
// public static bool IsCompleted { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "IsCompleted").WithArguments("Awaiter.IsCompleted"),
// (10,9): error CS0176: Member 'Awaiter.IsCompleted' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.IsCompleted")
);
}
[Fact]
public void NonBooleanIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public int IsCompleted { get { return -1; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void WriteonlyIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public bool IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted"));
}
[Fact]
public void WriteonlyNonBooleanIsCompletedProperty()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult() { throw new Exception(); }
public int IsCompleted { set { } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'A' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "await new A()").WithArguments("Awaiter.IsCompleted"));
}
[Fact]
public void MissingGetResultInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult"));
}
[Fact]
public void InaccessibleGetResultInstanceMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
private bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0122: 'Awaiter.GetResult()' is inaccessible due to its protection level
// await new A();
Diagnostic(ErrorCode.ERR_BadAccess, "await new A()").WithArguments("Awaiter.GetResult()")
);
}
[Fact]
public void StaticResultMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public static bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0176: Member 'Awaiter.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead
// await new A();
Diagnostic(ErrorCode.ERR_ObjectProhibited, "await new A()").WithArguments("Awaiter.GetResult()"));
}
[Fact]
public void GetResultExtensionMethod()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool IsCompleted { get { return false; } }
}
static class MyExtensions
{
public static bool GetResult(this Awaiter a)
{
throw new Exception();
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0117: 'Awaiter' does not contain a definition for 'GetResult'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "GetResult"));
}
[Fact]
public void GetResultWithNonZeroArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult(object o = null) { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void GetResultWithNonZeroTypeParameterArity()
{
var source = @"
using System;
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
public bool GetResult<T>() { throw new Exception(); }
public bool IsCompleted { get { return false; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'Awaiter.GetResult<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// await new A();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "await new A()").WithArguments("Awaiter.GetResult<T>()")
);
}
[Fact]
public void ConditionalGetResult()
{
var source = @"
using System;
using System.Diagnostics;
static class Program
{
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action x) { }
[Conditional(""X"")]
public void GetResult() { Console.WriteLine(""unconditional""); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (15,9): error CS4011: 'await' requires that the return type 'Awaiter' of 'A.GetAwaiter()' have suitable IsCompleted, OnCompleted, and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion
// await new A();
Diagnostic(ErrorCode.ERR_BadAwaiterPattern, "await new A()").WithArguments("Awaiter", "A"));
}
[Fact]
public void Missing_IsCompleted_INotifyCompletion_GetResult()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion
{
//public void OnCompleted(Action x) { }
//public bool GetResult() { throw new Exception(); }
//public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS0117: 'Awaiter' does not contain a definition for 'IsCompleted'
// await new A();
Diagnostic(ErrorCode.ERR_NoSuchMember, "await new A()").WithArguments("Awaiter", "IsCompleted"));
}
[Fact]
public void Missing_INotifyCompletion_GetResult()
{
var source = @"
static class Program
{
static void Main() { }
static async void f()
{
await new A();
}
}
class A
{
public Awaiter GetAwaiter() { return null; }
}
class Awaiter //: System.Runtime.CompilerServices.INotifyCompletion
{
//public void OnCompleted(Action x) { }
//public bool GetResult() { throw new Exception(); }
public bool IsCompleted { get { return true; } }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS4027: 'Awaiter' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'
// await new A();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new A()").WithArguments("Awaiter", "System.Runtime.CompilerServices.INotifyCompletion"));
}
[Fact]
public void BadAwaitArg_NeedSystem()
{
var source = @"
// using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
class App {
static void Main() {
EnumDevices().Wait();
}
private static async Task EnumDevices() {
await DeviceInformation.FindAllAsync();
return;
}
}";
CreateCompilationWithWinRT(source).VerifyDiagnostics(
// (12,9): error CS4035: 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>' could be found (are you missing a using directive for 'System'?)
// await DeviceInformation.FindAllAsync();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, "await DeviceInformation.FindAllAsync()").WithArguments("Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection>", "GetAwaiter", "System")
);
}
[Fact]
public void ErrorInAwaitSubexpression()
{
var source = @"
class C
{
async void M()
{
using (await goo())
{
}
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,22): error CS0103: The name 'goo' does not exist in the current context
// using (await goo())
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
}
[Fact]
public void BadAwaitArgIntrinsic()
{
var source = @"
class Test
{
public void goo() { }
public async void awaitVoid()
{
await goo();
}
public async void awaitNull()
{
await null;
}
public async void awaitMethodGroup()
{
await goo;
}
public async void awaitLambda()
{
await (x => x);
}
public static void Main() { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (8,9): error CS4008: Cannot await 'void'
// await goo();
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"),
// (13,9): error CS4001: Cannot await '<null>;'
// await null;
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await null").WithArguments("<null>"),
// (18,9): error CS4001: Cannot await 'method group'
// await goo;
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await goo").WithArguments("method group"),
// (23,9): error CS4001: Cannot await 'lambda expression'
// await (x => x);
Diagnostic(ErrorCode.ERR_BadAwaitArgIntrinsic, "await (x => x)").WithArguments("lambda expression"));
}
[Fact]
public void BadAwaitArgVoidCall()
{
var source = @"
using System.Threading.Tasks;
class Test
{
public async void goo()
{
await Task.Factory.StartNew(() => { });
}
public async void bar()
{
await goo();
}
public static void Main() { }
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (10,9): error CS4008: Cannot await 'void'
// await goo();
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "await goo()"));
}
[Fact, WorkItem(531356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531356")]
public void Repro_17997()
{
var source = @"
class C
{
public IVsTask ResolveReferenceAsync()
{
return this.VsTasksService.InvokeAsync(async delegate
{
return null;
});
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (4,12): error CS0246: The type or namespace name 'IVsTask' could not be found (are you missing a using directive or an assembly reference?)
// public IVsTask ResolveReferenceAsync()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVsTask").WithArguments("IVsTask").WithLocation(4, 12),
// (6,21): error CS1061: 'C' does not contain a definition for 'VsTasksService' and no extension method 'VsTasksService' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// return this.VsTasksService.InvokeAsync(async delegate
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "VsTasksService").WithArguments("C", "VsTasksService").WithLocation(6, 21),
// (6,54): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// return this.VsTasksService.InvokeAsync(async delegate
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(6, 54));
}
[Fact, WorkItem(627123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627123")]
public void Repro_627123()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
interface IA : INotifyCompletion
{
bool IsCompleted { get; }
void GetResult();
}
interface IB : IA
{
new Action GetResult { get; }
}
interface IC
{
IB GetAwaiter();
}
class D
{
Action<IC> a = async x => await x;
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (23,31): error CS0118: 'GetResult' is a property but is used like a method
// Action<IC> a = async x => await x;
Diagnostic(ErrorCode.ERR_BadSKknown, "await x").WithArguments("GetResult", "property", "method")
);
}
[Fact, WorkItem(1091911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091911")]
public void Repro_1091911()
{
const string source = @"
using System;
using System.Threading.Tasks;
class Repro
{
int Boom { get { return 42; } }
static Task<dynamic> Compute()
{
return Task.FromResult<dynamic>(new Repro());
}
static async Task<int> Bug()
{
dynamic results = await Compute().ConfigureAwait(false);
var x = results.Boom;
return (int)x;
}
static void Main()
{
Console.WriteLine(Bug().Result);
}
}";
var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void DynamicResultTypeCustomAwaiter()
{
const string source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
public struct MyTask
{
public readonly Task task;
private readonly Func<dynamic> getResult;
public MyTask(Task task, Func<dynamic> getResult)
{
this.task = task;
this.getResult = getResult;
}
public dynamic Result { get { return this.getResult(); } }
}
public struct MyAwaiter : INotifyCompletion
{
private readonly MyTask task;
public MyAwaiter(MyTask task)
{
this.task = task;
}
public bool IsCompleted { get { return true; } }
public dynamic GetResult() { Console.Write(""dynamic""); return task.Result; }
public void OnCompleted(System.Action continuation) { task.task.ContinueWith(_ => continuation()); }
}
public static class TaskAwaiter
{
public static MyAwaiter GetAwaiter(this MyTask task)
{
return new MyAwaiter(task);
}
}
class Repro
{
int Boom { get { return 42; } }
static MyTask Compute()
{
var task = Task.FromResult(new Repro());
return new MyTask(task, () => task.Result);
}
static async Task<int> Bug()
{
return (await Compute()).Boom;
}
static void Main()
{
Console.WriteLine(Bug().Result);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, new[] { TestMetadata.Net40.SystemCore, TestMetadata.Net40.MicrosoftCSharp }, TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// warning CS1685: The predefined type 'ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
Diagnostic(ErrorCode.WRN_MultiplePredefTypes).WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(1, 1));
var compiled = CompileAndVerify(comp, expectedOutput: "dynamic42", verify: Verification.Fails);
compiled.VerifyIL("MyAwaiter.OnCompleted(System.Action)", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (MyAwaiter.<>c__DisplayClass5_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""MyAwaiter.<>c__DisplayClass5_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.1
IL_0008: stfld ""System.Action MyAwaiter.<>c__DisplayClass5_0.continuation""
IL_000d: ldarg.0
IL_000e: ldflda ""MyTask MyAwaiter.task""
IL_0013: ldfld ""System.Threading.Tasks.Task MyTask.task""
IL_0018: ldloc.0
IL_0019: ldftn ""void MyAwaiter.<>c__DisplayClass5_0.<OnCompleted>b__0(System.Threading.Tasks.Task)""
IL_001f: newobj ""System.Action<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)""
IL_0024: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.Task.ContinueWith(System.Action<System.Threading.Tasks.Task>)""
IL_0029: pop
IL_002a: ret
}");
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AdditionalText.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a non source code file.
/// </summary>
public abstract class AdditionalText
{
/// <summary>
/// Path to the text.
/// </summary>
public abstract string Path { get; }
/// <summary>
/// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
/// there were errors reading the file.
/// </summary>
public abstract SourceText? GetText(CancellationToken cancellationToken = default);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a non source code file.
/// </summary>
public abstract class AdditionalText
{
/// <summary>
/// Path to the text.
/// </summary>
public abstract string Path { get; }
/// <summary>
/// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
/// there were errors reading the file.
/// </summary>
public abstract SourceText? GetText(CancellationToken cancellationToken = default);
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/CSharp/Portable/Binder/Binder_Invocation.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 System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>.
/// </summary>
internal partial class Binder
{
private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.ParenthesizedExpression:
return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics);
default:
return BindExpression(node, diagnostics, invoked, indexed);
}
}
private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult)
{
// If overload resolution has failed then we want to stash away the original methods that we
// considered so that the IDE can display tooltips or other information about them.
// However, if a method group contained a generic method that was type inferred then
// the IDE wants information about the *inferred* method, not the original unconstructed
// generic method.
if (overloadResolutionResult == null)
{
return ImmutableArray<MethodSymbol>.Empty;
}
var builder = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var result in overloadResolutionResult.Results)
{
builder.Add(result.Member);
}
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Helper method to create a synthesized method invocation expression.
/// </summary>
/// <param name="node">Syntax Node.</param>
/// <param name="receiver">Receiver for the method call.</param>
/// <param name="methodName">Method to be invoked on the receiver.</param>
/// <param name="args">Arguments to the method call.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="typeArgsSyntax">Optional type arguments syntax.</param>
/// <param name="typeArgs">Optional type arguments.</param>
/// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param>
/// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param>
/// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param>
/// <returns>Synthesized method invocation expression.</returns>
internal BoundExpression MakeInvocationExpression(
SyntaxNode node,
BoundExpression receiver,
string methodName,
ImmutableArray<BoundExpression> args,
BindingDiagnosticBag diagnostics,
SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>),
ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>),
ImmutableArray<(string Name, Location Location)?> names = default,
CSharpSyntaxNode? queryClause = null,
bool allowFieldsAndProperties = false,
bool allowUnexpandedForm = true,
bool searchExtensionMethodsIfNecessary = true)
{
Debug.Assert(receiver != null);
Debug.Assert(names.IsDefault || names.Length == args.Length);
receiver = BindToNaturalType(receiver, diagnostics);
var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary);
// The other consumers of this helper (await and collection initializers) require the target member to be a method.
if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess))
{
Symbol symbol;
MessageID msgId;
if (boundExpression.Kind == BoundKind.FieldAccess)
{
msgId = MessageID.IDS_SK_FIELD;
symbol = ((BoundFieldAccess)boundExpression).FieldSymbol;
}
else
{
msgId = MessageID.IDS_SK_PROPERTY;
symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol;
}
diagnostics.Add(
ErrorCode.ERR_BadSKknown,
node.Location,
methodName,
msgId.Localize(),
MessageID.IDS_SK_METHOD.Localize());
return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true);
}
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
boundExpression.WasCompilerGenerated = true;
var analyzedArguments = AnalyzedArguments.GetInstance();
Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference ||
e.Kind == BoundKind.OutDeconstructVarPendingInference ||
e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType()));
analyzedArguments.Arguments.AddRange(args);
if (!names.IsDefault)
{
analyzedArguments.Names.AddRange(names);
}
BoundExpression result = BindInvocationExpression(
node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause,
allowUnexpandedForm: allowUnexpandedForm);
// Query operator can't be called dynamically.
if (queryClause != null && result.Kind == BoundKind.DynamicInvocation)
{
// the error has already been reported by BindInvocationExpression
Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors());
result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result.WasCompilerGenerated = true;
analyzedArguments.Free();
return result;
}
#nullable disable
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
InvocationExpressionSyntax node,
BindingDiagnosticBag diagnostics)
{
BoundExpression result;
if (TryBindNameofOperator(node, diagnostics, out result))
{
return result; // all of the binding is done by BindNameofOperator
}
// M(__arglist()) is legal, but M(__arglist(__arglist()) is not!
bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression;
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
if (isArglist)
{
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false);
result = BindArgListOperator(node, diagnostics, analyzedArguments);
}
else
{
BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics);
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null;
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true);
result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics);
}
analyzedArguments.Free();
return result;
}
private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments)
{
bool hasErrors = analyzedArguments.HasErrors;
// We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them.
TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node);
for (int i = 0; i < analyzedArguments.Arguments.Count; ++i)
{
BoundExpression argument = analyzedArguments.Arguments[i];
if (argument.Kind == BoundKind.OutVariablePendingInference)
{
analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics);
}
else if ((object)argument.Type == null && !argument.HasAnyErrors)
{
// We are going to need every argument in here to have a type. If we don't have one,
// try converting it to object. We'll either succeed (if it is a null literal)
// or fail with a good error message.
//
// Note that the native compiler converts null literals to object, and for everything
// else it either crashes, or produces nonsense code. Roslyn improves upon this considerably.
analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics);
}
else if (argument.Type.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax);
hasErrors = true;
}
else if (analyzedArguments.RefKind(i) == RefKind.None)
{
analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics);
}
switch (analyzedArguments.RefKind(i))
{
case RefKind.None:
case RefKind.Ref:
break;
default:
// Disallow "in" or "out" arguments
Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax);
hasErrors = true;
break;
}
}
ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable();
ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors);
}
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause = null,
bool allowUnexpandedForm = true)
{
BoundExpression result;
NamedTypeSymbol delegateType;
if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic())
{
// Either we have a dynamic method group invocation "dyn.M(...)" or
// a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic
// invocation and let the lowering pass sort it out.
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause);
}
else if (boundExpression.Kind == BoundKind.MethodGroup)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindMethodGroupInvocation(
node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments,
diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _);
}
else if ((object)(delegateType = GetDelegateType(boundExpression)) != null)
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node))
{
return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType);
}
else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics);
}
else
{
if (!boundExpression.HasAnyErrors)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location);
}
result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments);
}
CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics);
return result;
}
private BoundExpression BindDynamicInvocation(
SyntaxNode node,
BoundExpression expression,
AnalyzedArguments arguments,
ImmutableArray<MethodSymbol> applicableMethods,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause)
{
CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics);
bool hasErrors = false;
if (expression.Kind == BoundKind.MethodGroup)
{
BoundMethodGroup methodGroup = (BoundMethodGroup)expression;
BoundExpression receiver = methodGroup.ReceiverOpt;
// receiver is null if we are calling a static method declared on an outer class via its simple name:
if (receiver != null)
{
switch (receiver.Kind)
{
case BoundKind.BaseReference:
Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name);
hasErrors = true;
break;
case BoundKind.ThisReference:
// Can't call the HasThis method due to EE doing odd things with containing member and its containing type.
if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated)
{
// Only a static method can be called in a constructor initializer. If we were not in a ctor initializer
// the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before
// the base constructor is called. We need to handle this as a type qualified static method call.
// Also applicable to things like field initializers, which run before the ctor initializer.
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver,
receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(),
resultKind: methodGroup.ResultKind);
}
break;
case BoundKind.TypeOrValueExpression:
var typeOrValue = (BoundTypeOrValueExpression)receiver;
// Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value".
// Ideally the runtime binder would choose between type and value based on the result of the overload resolution.
// We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed.
bool inStaticContext;
bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext);
BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics);
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags,
finalReceiver,
methodGroup.ResultKind);
break;
}
}
}
else
{
expression = BindToNaturalType(expression, diagnostics);
}
ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics);
var refKindsArray = arguments.RefKinds.ToImmutableOrNull();
hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause);
return new BoundDynamicInvocation(
node,
arguments.GetNames(),
refKindsArray,
applicableMethods,
expression,
argArray,
type: Compilation.DynamicType,
hasErrors: hasErrors);
}
private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
if (arguments.Names.Count == 0)
{
return;
}
if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments())
{
return;
}
bool seenName = false;
for (int i = 0; i < arguments.Names.Count; i++)
{
if (arguments.Names[i] != null)
{
seenName = true;
}
else if (seenName)
{
Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax);
return;
}
}
}
private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count);
builder.AddRange(arguments.Arguments);
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = builder[i] switch
{
OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics),
BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics),
var arg => BindToNaturalType(arg, diagnostics)
};
}
return builder.ToImmutableAndFree();
}
// Returns true if there were errors.
private static bool ReportBadDynamicArguments(
SyntaxNode node,
ImmutableArray<BoundExpression> arguments,
ImmutableArray<RefKind> refKinds,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause)
{
bool hasErrors = false;
bool reportedBadQuery = false;
if (!refKinds.IsDefault)
{
for (int argIndex = 0; argIndex < refKinds.Length; argIndex++)
{
if (refKinds[argIndex] == RefKind.In)
{
Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax);
hasErrors = true;
}
}
}
foreach (var arg in arguments)
{
if (!IsLegalDynamicOperand(arg))
{
if (queryClause != null && !reportedBadQuery)
{
reportedBadQuery = true;
Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node);
hasErrors = true;
continue;
}
if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda)
{
// Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.MethodGroup)
{
// Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.ArgListOperator)
{
// Not a great error message, since __arglist is not a type, but it'll do.
// error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist");
}
else
{
// Lambdas,anonymous methods and method groups are the typeless expressions that
// are not usable as dynamic arguments; if we get here then the expression must have a type.
Debug.Assert((object)arg.Type != null);
// error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type);
hasErrors = true;
}
}
}
return hasErrors;
}
private BoundExpression BindDelegateInvocation(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
NamedTypeSymbol delegateType)
{
BoundExpression result;
var methodGroup = MethodGroup.GetInstance();
methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod);
var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
OverloadResolution.MethodInvocationOverloadResolution(
methods: methodGroup.Methods,
typeArguments: methodGroup.TypeArguments,
receiver: methodGroup.Receiver,
arguments: analyzedArguments,
result: overloadResolutionResult,
useSiteInfo: ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
// If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments
// was dynamic then treat this as a dynamic call.
if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember)
{
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause);
}
else
{
result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause);
}
overloadResolutionResult.Free();
methodGroup.Free();
return result;
}
private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results)
{
var r = results.Results;
for (int i = 0; i < r.Length; ++i)
{
if (r[i].IsApplicable && r[i].Member.IsConditional)
{
return true;
}
}
return false;
}
private BoundExpression BindMethodGroupInvocation(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup methodGroup,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
bool allowUnexpandedForm,
out bool anyApplicableCandidates)
{
BoundExpression result;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(
methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false,
useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm);
diagnostics.Add(expression, useSiteInfo);
anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember;
if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
if (resolution.HasAnyErrors)
{
ImmutableArray<MethodSymbol> originalMethods;
LookupResultKind resultKind;
ImmutableArray<TypeWithAnnotations> typeArguments;
if (resolution.OverloadResolutionResult != null)
{
originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult);
resultKind = resolution.MethodGroup.ResultKind;
typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable();
}
else
{
originalMethods = methodGroup.Methods;
resultKind = methodGroup.ResultKind;
typeArguments = methodGroup.TypeArgumentsOpt;
}
result = CreateBadCall(
syntax,
methodName,
methodGroup.ReceiverOpt,
originalMethods,
resultKind,
typeArguments,
analyzedArguments,
invokedAsExtensionMethod: resolution.IsExtensionMethodGroup,
isDelegate: false);
}
else if (!resolution.IsEmpty)
{
// We're checking resolution.ResultKind, rather than methodGroup.HasErrors
// to better handle the case where there's a problem with the receiver
// (e.g. inaccessible), but the method group resolved correctly (e.g. because
// it's actually an accessible static method on a base type).
// CONSIDER: could check for error types amongst method group type arguments.
if (resolution.ResultKind != LookupResultKind.Viable)
{
if (resolution.MethodGroup != null)
{
// we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448.
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause);
}
// Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting.
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
// If overload resolution found one or more applicable methods and at least one argument
// was dynamic then treat this as a dynamic call.
if (resolution.AnalyzedArguments.HasDynamicArgument &&
resolution.OverloadResolutionResult.HasAnyApplicableMember)
{
if (resolution.IsLocalFunctionInvocation)
{
result = BindLocalFunctionInvocationWithDynamicArgument(
syntax, expression, methodName, methodGroup,
diagnostics, queryClause, resolution);
}
else if (resolution.IsExtensionMethodGroup)
{
// error CS1973: 'T' has no applicable method named 'M' but appears to have an
// extension method by that name. Extension methods cannot be dynamically dispatched. Consider
// casting the dynamic arguments or calling the extension method without the extension method
// syntax.
// We found an extension method, so the instance associated with the method group must have
// existed and had a type.
Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null);
Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name);
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult))
{
// warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime
// because one or more applicable overloads are conditional methods
Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name);
}
// Note that the runtime binder may consider candidates that haven't passed compile-time final validation
// and an ambiguity error may be reported. Also additional checks are performed in runtime final validation
// that are not performed at compile-time.
// Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime.
var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult,
methodGroup.ReceiverOpt,
methodGroup.TypeArgumentsOpt,
diagnostics);
if (finalApplicableCandidates.Length > 0)
{
result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause);
}
else
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
}
}
else
{
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause);
}
}
}
else
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
resolution.Free();
return result;
}
private BoundExpression BindLocalFunctionInvocationWithDynamicArgument(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup boundMethodGroup,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
MethodGroupResolution resolution)
{
// Invocations of local functions with dynamic arguments don't need
// to be dispatched as dynamic invocations since they cannot be
// overloaded. Instead, we'll just emit a standard call with
// dynamic implicit conversions for any dynamic arguments. There
// are two exceptions: "params", and unconstructed generics. While
// implementing those cases with dynamic invocations is possible,
// we have decided the implementation complexity is not worth it.
// Refer to the comments below for the exact semantics.
Debug.Assert(resolution.IsLocalFunctionInvocation);
Debug.Assert(resolution.OverloadResolutionResult.Succeeded);
Debug.Assert(queryClause == null);
var validResult = resolution.OverloadResolutionResult.ValidResult;
var args = resolution.AnalyzedArguments.Arguments.ToImmutable();
var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull();
ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause);
var localFunction = validResult.Member;
var methodResult = validResult.Result;
// We're only in trouble if a dynamic argument is passed to the
// params parameter and is ambiguous at compile time between normal
// and expanded form i.e., there is exactly one dynamic argument to
// a params parameter
// See https://github.com/dotnet/roslyn/issues/10708
if (OverloadResolution.IsValidParams(localFunction) &&
methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm)
{
var parameters = localFunction.Parameters;
Debug.Assert(parameters.Last().IsParams);
var lastParamIndex = parameters.Length - 1;
for (int i = 0; i < args.Length; ++i)
{
var arg = args[i];
if (arg.HasDynamicType() &&
methodResult.ParameterFromArgument(i) == lastParamIndex)
{
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionParamsParameter,
syntax, parameters.Last().Name, localFunction.Name);
return BindDynamicInvocation(
syntax,
boundMethodGroup,
resolution.AnalyzedArguments,
resolution.OverloadResolutionResult.GetAllApplicableMembers(),
diagnostics,
queryClause);
}
}
}
// If we call an unconstructed generic local function with a
// dynamic argument in a place where it influences the type
// parameters, we need to dynamically dispatch the call (as the
// function must be constructed at runtime). We cannot do that, so
// disallow that. However, doing a specific analysis of each
// argument and its corresponding parameter to check if it's
// generic (and allow dynamic in non-generic parameters) may break
// overload resolution in the future, if we ever allow overloaded
// local functions. So, just disallow any mixing of dynamic and
// inferred generics. (Explicit generic arguments are fine)
// See https://github.com/dotnet/roslyn/issues/21317
if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod)
{
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionTypeParameter,
syntax, localFunction.Name);
return BindDynamicInvocation(
syntax,
boundMethodGroup,
resolution.AnalyzedArguments,
resolution.OverloadResolutionResult.GetAllApplicableMembers(),
diagnostics,
queryClause);
}
return BindInvocationExpressionContinued(
node: syntax,
expression: expression,
methodName: methodName,
result: resolution.OverloadResolutionResult,
analyzedArguments: resolution.AnalyzedArguments,
methodGroup: resolution.MethodGroup,
delegateTypeOpt: null,
diagnostics: diagnostics,
queryClause: queryClause);
}
private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>(
SyntaxNode syntax,
OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult,
BoundExpression receiverOpt,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol
{
Debug.Assert(overloadResolutionResult.HasAnyApplicableMember);
var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance();
BindingDiagnosticBag firstFailed = null;
var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++)
{
var result = overloadResolutionResult.ResultsBuilder[i];
if (result.Result.IsApplicable)
{
// For F to pass the check, all of the following must hold:
// ...
// * If the type parameters of F were substituted in the step above, their constraints are satisfied.
// * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
// * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) &&
(typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics))))
{
finalCandidates.Add(result.Member);
continue;
}
if (firstFailed == null)
{
firstFailed = candidateDiagnostics;
candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
}
else
{
candidateDiagnostics.Clear();
}
}
}
if (firstFailed != null)
{
// Report diagnostics of the first candidate that failed the validation
// unless we have at least one candidate that passes.
if (finalCandidates.Count == 0)
{
diagnostics.AddRange(firstFailed);
}
firstFailed.Free();
}
candidateDiagnostics.Free();
return finalCandidates.ToImmutableAndFree();
}
private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
// It is never legal to box a restricted type, even if we are boxing it as the receiver
// of a method call. When must be box? We skip boxing when the method in question is defined
// on the restricted type or overridden by the restricted type.
switch (expression.Kind)
{
case BoundKind.Call:
{
var call = (BoundCall)expression;
if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null)
{
// error CS0029: Cannot implicitly convert type 'A' to 'B'
// Case 1: receiver is a restricted type, and method called is defined on a parent type
if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2))
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType);
Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second);
}
// Case 2: receiver is a base reference, and the child type is restricted
else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType())
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType);
Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second);
}
}
}
break;
case BoundKind.DynamicInvocation:
{
var dynInvoke = (BoundDynamicInvocation)expression;
if (!dynInvoke.HasAnyErrors &&
(object)dynInvoke.Expression.Type != null &&
dynInvoke.Expression.Type.IsRestrictedType())
{
// eg: b = typedReference.Equals(dyn);
// error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type);
}
}
break;
case BoundKind.FunctionPointerInvocation:
break;
default:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
/// <summary>
/// Perform overload resolution on the method group or expression (BoundMethodGroup)
/// and arguments and return a BoundExpression representing the invocation.
/// </summary>
/// <param name="node">Invocation syntax node.</param>
/// <param name="expression">The syntax for the invoked method, including receiver.</param>
/// <param name="methodName">Name of the invoked method.</param>
/// <param name="result">Overload resolution result for method group executed by caller.</param>
/// <param name="analyzedArguments">Arguments bound by the caller.</param>
/// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param>
/// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param>
/// <returns>BoundCall or error expression representing the invocation.</returns>
private BoundCall BindInvocationExpressionContinued(
SyntaxNode node,
SyntaxNode expression,
string methodName,
OverloadResolutionResult<MethodSymbol> result,
AnalyzedArguments analyzedArguments,
MethodGroup methodGroup,
NamedTypeSymbol delegateTypeOpt,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause = null)
{
Debug.Assert(node != null);
Debug.Assert(methodGroup != null);
Debug.Assert(methodGroup.Error == null);
Debug.Assert(methodGroup.Methods.Count > 0);
Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1));
var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup;
// Delegate invocations should never be considered extension method
// invocations (even though the delegate may refer to an extension method).
Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null));
// We have already determined that we are not in a situation where we can successfully do
// a dynamic binding. We might be in one of the following situations:
//
// * There were dynamic arguments but overload resolution still found zero applicable candidates.
// * There were no dynamic arguments and overload resolution found zero applicable candidates.
// * There were no dynamic arguments and overload resolution found multiple applicable candidates
// without being able to find the best one.
//
// In those three situations we might give an additional error.
if (!result.Succeeded)
{
if (analyzedArguments.HasErrors)
{
// Errors for arguments have already been reported, except for unbound lambdas and switch expressions.
// We report those now.
foreach (var argument in analyzedArguments.Arguments)
{
switch (argument)
{
case UnboundLambda unboundLambda:
var boundWithErrors = unboundLambda.BindForErrorRecovery();
diagnostics.AddRange(boundWithErrors.Diagnostics);
break;
case BoundUnconvertedObjectCreationExpression _:
case BoundTupleLiteral _:
// Tuple literals can contain unbound lambdas or switch expressions.
_ = BindToNaturalType(argument, diagnostics);
break;
case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr:
_ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics);
break;
case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr:
_ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics);
break;
}
}
}
else
{
// Since there were no argument errors to report, we report an error on the invocation itself.
string name = (object)delegateTypeOpt == null ? methodName : null;
result.ReportDiagnostics(
binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name,
receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(),
typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause);
}
return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver,
GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null));
}
// Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate.
// We still have to determine if it passes final validation.
var methodResult = result.ValidResult;
var returnType = methodResult.Member.ReturnType;
var method = methodResult.Member;
// It is possible that overload resolution succeeded, but we have chosen an
// instance method and we're in a static method. A careful reading of the
// overload resolution spec shows that the "final validation" stage allows an
// "implicit this" on any method call, not just method calls from inside
// instance methods. Therefore we must detect this scenario here, rather than in
// overload resolution.
var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics);
var receiverRefKind = receiver?.GetRefKind();
uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null
? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth)
: Binder.ExternalScope;
this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope);
var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm;
var argsToParams = methodResult.Result.ArgsToParamsOpt;
BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics);
// Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2),
// so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors.
// Note: final validation wants the receiver that corresponds to the source representation
// (i.e. the first argument, if invokedAsExtensionMethod).
var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod);
CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics);
if (invokedAsExtensionMethod)
{
BoundExpression receiverArgument = analyzedArguments.Argument(0);
ParameterSymbol receiverParameter = method.Parameters.First();
// we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue
if ((object)receiver != receiverArgument)
{
// Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here.
Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0);
receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0),
receiverParameter.Type, diagnostics);
}
if (receiverParameter.RefKind == RefKind.Ref)
{
// If this was a ref extension method, receiverArgument must be checked for L-value constraints.
// This helper method will also replace it with a BoundBadExpression if it was invalid.
receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics);
if (analyzedArguments.RefKinds.Count == 0)
{
analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count;
}
// receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref)
// we need to adjust the argument refkind as if we had a `ref` modifier in a call.
analyzedArguments.RefKinds[0] = RefKind.Ref;
CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics);
}
else if (receiverParameter.RefKind == RefKind.In)
{
// NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case.
Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None);
CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics);
}
analyzedArguments.Arguments[0] = receiverArgument;
}
// This will be the receiver of the BoundCall node that we create.
// For extension methods, there is no receiver because the receiver in source was actually the first argument.
// For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter.
// For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it.
if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated))
{
receiver = null;
}
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var args = analyzedArguments.Arguments.ToImmutable();
if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated)
{
gotError = IsRefOrOutThisParameterCaptured(node, diagnostics);
}
// What if some of the arguments are implicit? Dev10 reports unsafe errors
// if the implied argument would have an unsafe type. We need to check
// the parameters explicitly, since there won't be bound nodes for the implied
// arguments until lowering.
if (method.HasUnsafeParameter())
{
// Don't worry about double reporting (i.e. for both the argument and the parameter)
// because only one unsafe diagnostic is allowed per scope - the others are suppressed.
gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError;
}
bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference;
ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver);
ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false);
// No use site errors, but there could be use site warnings.
// If there are any use site warnings, they have already been reported by overload resolution.
Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors.");
if (method.IsRuntimeFinalizer())
{
ErrorCode code = hasBaseReceiver
? ErrorCode.ERR_CallingBaseFinalizeDeprecated
: ErrorCode.ERR_CallingFinalizeDeprecated;
Error(diagnostics, code, node);
gotError = true;
}
Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]);
if (!gotError)
{
gotError = !CheckInvocationArgMixing(
node,
method,
receiver,
method.Parameters,
args,
argsToParams,
this.LocalScopeDepth,
diagnostics);
}
bool isDelegateCall = (object)delegateTypeOpt != null;
if (!isDelegateCall)
{
if (method.RequiresInstanceReceiver)
{
WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ?
((InvocationExpressionSyntax)node).Expression :
node,
receiver,
diagnostics);
}
}
return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall,
expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod,
argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError);
}
#nullable enable
private static SourceLocation GetCallerLocation(SyntaxNode syntax)
{
var token = syntax switch
{
InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken,
BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword,
ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken,
PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken,
ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken,
_ => syntax.GetFirstToken()
};
return new SourceLocation(token);
}
private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics)
{
var parameterType = parameter.Type;
Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object);
// We have a call to a method M([Optional] object x) which omits the argument. The value we generate
// for the argument depends on the presence or absence of other attributes. The rules are:
//
// * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)]
// then the argument is null.
// * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is
// new UnknownWrapper(null)
// * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is
// new DispatchWrapper(null)
// * Otherwise, the argument is Type.Missing.
BoundExpression? defaultValue = null;
if (parameter.IsMarshalAsObject)
{
// default(object)
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else if (parameter.IsIUnknownConstant)
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol)
{
// new UnknownWrapper(default(object))
var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true };
}
}
else if (parameter.IsIDispatchConstant)
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol)
{
// new DispatchWrapper(default(object))
var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true };
}
}
else
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol)
{
// Type.Missing
defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true };
}
}
return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated();
}
internal static ParameterSymbol? GetCorrespondingParameter(
int argumentOrdinal,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<int> argsToParamsOpt,
bool expanded)
{
int n = parameters.Length;
ParameterSymbol? parameter;
if (argsToParamsOpt.IsDefault)
{
if (argumentOrdinal < n)
{
parameter = parameters[argumentOrdinal];
}
else if (expanded)
{
parameter = parameters[n - 1];
}
else
{
parameter = null;
}
}
else
{
Debug.Assert(argumentOrdinal < argsToParamsOpt.Length);
int parameterOrdinal = argsToParamsOpt[argumentOrdinal];
if (parameterOrdinal < n)
{
parameter = parameters[parameterOrdinal];
}
else
{
parameter = null;
}
}
return parameter;
}
internal void BindDefaultArguments(
SyntaxNode node,
ImmutableArray<ParameterSymbol> parameters,
ArrayBuilder<BoundExpression> argumentsBuilder,
ArrayBuilder<RefKind>? argumentRefKindsBuilder,
ref ImmutableArray<int> argsToParamsOpt,
out BitVector defaultArguments,
bool expanded,
bool enableCallerInfo,
BindingDiagnosticBag diagnostics,
bool assertMissingParametersAreOptional = true)
{
var visitedParameters = BitVector.Create(parameters.Length);
for (var i = 0; i < argumentsBuilder.Count; i++)
{
var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded);
if (parameter is not null)
{
visitedParameters[parameter.Ordinal] = true;
}
}
// only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument
if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters))
{
defaultArguments = default;
return;
}
// In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field.
// We want to use the associated user-declared symbol instead where possible.
var containingMember = ContainingMember() switch
{
FieldSymbol { AssociatedSymbol: { } symbol } => symbol,
var c => c
};
defaultArguments = BitVector.Create(parameters.Length);
ArrayBuilder<int>? argsToParamsBuilder = null;
if (!argsToParamsOpt.IsDefault)
{
argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length);
argsToParamsBuilder.AddRange(argsToParamsOpt);
}
// Params methods can be invoked in normal form, so the strongest assertion we can make is that, if
// we're in an expanded context, the last param must be params. The inverse is not necessarily true.
Debug.Assert(!expanded || parameters[^1].IsParams);
// Params array is filled in the local rewriter
var lastIndex = expanded ? ^1 : ^0;
var argumentsCount = argumentsBuilder.Count;
// Go over missing parameters, inserting default values for optional parameters
foreach (var parameter in parameters.AsSpan()[..lastIndex])
{
if (!visitedParameters[parameter.Ordinal])
{
Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional);
defaultArguments[argumentsBuilder.Count] = true;
argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt));
if (argumentRefKindsBuilder is { Count: > 0 })
{
argumentRefKindsBuilder.Add(RefKind.None);
}
argsToParamsBuilder?.Add(parameter.Ordinal);
}
}
Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count);
Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count);
if (argsToParamsBuilder is object)
{
argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull();
argsToParamsBuilder.Free();
}
BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt)
{
TypeSymbol parameterType = parameter.Type;
if (Flags.Includes(BinderFlags.ParameterDefaultValue))
{
// This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }`
// We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller.
return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch
{
// Bad default values are implicitly replaced with default(T) at call sites.
{ IsBad: true } => ConstantValue.Null,
var constantValue => constantValue
};
Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset);
var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null;
BoundExpression defaultValue;
if (callerSourceLocation is object && parameter.IsCallerLineNumber)
{
int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan);
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && parameter.IsCallerFilePath)
{
string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver);
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && parameter.IsCallerMemberName)
{
var memberName = containingMember.GetMemberCallerName();
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex &&
argumentIndex > -1 && argumentIndex < argumentsCount)
{
var argument = argumentsBuilder[argumentIndex];
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (defaultConstantValue == ConstantValue.NotAvailable)
{
// There is no constant value given for the parameter in source/metadata.
if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object)
{
// We have something like M([Optional] object x). We have special handling for such situations.
defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics);
}
else
{
// The argument to M([Optional] int x) becomes default(int)
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
}
else if (defaultConstantValue.IsNull)
{
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else
{
TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType);
defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true };
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime })
{
// Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site.
// For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type
// then we want to silently replace it with default(ParameterType).
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else
{
if (!conversion.IsValid)
{
GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType);
}
var isCast = conversion.IsExplicit;
defaultValue = CreateConversion(
defaultValue.Syntax,
defaultValue,
conversion,
isCast,
isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null,
parameterType,
diagnostics);
}
return defaultValue;
static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt)
=> argsToParamsOpt.IsDefault
? parameterIndex
: argsToParamsOpt.IndexOf(parameterIndex);
}
}
#nullable disable
/// <summary>
/// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member.
/// </summary>
internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics)
{
// For now we are warning only in implicit copy scenarios that are only possible with readonly members.
// Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968.
if (receiver is BoundThisReference &&
receiver.Type.IsValueType &&
ContainingMemberOrLambda is MethodSymbol containingMethod &&
containingMethod.IsEffectivelyReadOnly &&
// Ignore calls to base members.
TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) &&
!method.IsEffectivelyReadOnly &&
method.RequiresInstanceReceiver)
{
Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName);
return false;
}
return true;
}
/// <param name="node">Invocation syntax node.</param>
/// <param name="expression">The syntax for the invoked method, including receiver.</param>
private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression)
{
if (node != expression)
{
switch (expression.Kind())
{
case SyntaxKind.QualifiedName:
return ((QualifiedNameSyntax)expression).Right.GetLocation();
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return ((MemberAccessExpressionSyntax)expression).Name.GetLocation();
}
}
return expression.GetLocation();
}
/// <summary>
/// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true)
/// or a value (if useType is false). Any other node is bound to its natural type.
/// </summary>
/// <remarks>
/// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression
/// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise.
/// </remarks>
private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics)
{
if ((object)receiver == null)
{
return null;
}
switch (receiver.Kind)
{
case BoundKind.TypeOrValueExpression:
var typeOrValue = (BoundTypeOrValueExpression)receiver;
if (useType)
{
diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics);
return typeOrValue.Data.TypeExpression;
}
else
{
diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics);
return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics);
}
case BoundKind.QueryClause:
// a query clause may wrap a TypeOrValueExpression.
var q = (BoundQueryClause)receiver;
var value = q.Value;
var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics);
return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type);
default:
return BindToNaturalType(receiver, diagnostics);
}
}
/// <summary>
/// Return the delegate type if this expression represents a delegate.
/// </summary>
private static NamedTypeSymbol GetDelegateType(BoundExpression expr)
{
if ((object)expr != null && expr.Kind != BoundKind.TypeExpression)
{
var type = expr.Type as NamedTypeSymbol;
if (((object)type != null) && type.IsDelegateType())
{
return type;
}
}
return null;
}
private BoundCall CreateBadCall(
SyntaxNode node,
string name,
BoundExpression receiver,
ImmutableArray<MethodSymbol> methods,
LookupResultKind resultKind,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
AnalyzedArguments analyzedArguments,
bool invokedAsExtensionMethod,
bool isDelegate)
{
MethodSymbol method;
ImmutableArray<BoundExpression> args;
if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty)
{
var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var m in methods)
{
constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m);
}
methods = constructedMethods.ToImmutableAndFree();
}
if (methods.Length == 1 && !IsUnboundGeneric(methods[0]))
{
method = methods[0];
}
else
{
var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null);
var methodContainer = (object)receiver != null && (object)receiver.Type != null
? receiver.Type
: this.ContainingType;
method = new ErrorMethodSymbol(methodContainer, returnType, name);
}
args = BuildArgumentsForErrorRecovery(analyzedArguments, methods);
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
receiver = BindToTypeForErrorRecovery(receiver);
return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this);
}
private static bool IsUnboundGeneric(MethodSymbol method)
{
return method.IsGenericMethod && method.ConstructedFrom() == method;
}
// Arbitrary limit on the number of parameter lists from overload
// resolution candidates considered when binding argument types.
// Any additional parameter lists are ignored.
internal const int MaxParameterListsForErrorRecovery = 10;
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods)
{
var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance();
foreach (var m in methods)
{
if (!IsUnboundGeneric(m) && m.ParameterCount > 0)
{
parameterListList.Add(m.Parameters);
if (parameterListList.Count == MaxParameterListsForErrorRecovery)
{
break;
}
}
}
var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList);
parameterListList.Free();
return result;
}
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties)
{
var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance();
foreach (var p in properties)
{
if (p.ParameterCount > 0)
{
parameterListList.Add(p.Parameters);
if (parameterListList.Count == MaxParameterListsForErrorRecovery)
{
break;
}
}
}
var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList);
parameterListList.Free();
return result;
}
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList)
{
var discardedDiagnostics = DiagnosticBag.GetInstance();
int argumentCount = analyzedArguments.Arguments.Count;
ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount);
newArguments.AddRange(analyzedArguments.Arguments);
for (int i = 0; i < argumentCount; i++)
{
var argument = newArguments[i];
switch (argument.Kind)
{
case BoundKind.UnboundLambda:
{
// bind the argument against each applicable parameter
var unboundArgument = (UnboundLambda)argument;
foreach (var parameterList in parameterListList)
{
var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList);
if (parameterType?.Kind == SymbolKind.NamedType &&
(object)parameterType.GetDelegateType() != null)
{
// Just assume we're not in an expression tree for the purposes of error recovery.
var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false);
}
}
// replace the unbound lambda with its best inferred bound version
newArguments[i] = unboundArgument.BindForErrorRecovery();
break;
}
case BoundKind.OutVariablePendingInference:
case BoundKind.DiscardExpression:
{
if (argument.HasExpressionType())
{
break;
}
var candidateType = getCorrespondingParameterType(i);
if (argument.Kind == BoundKind.OutVariablePendingInference)
{
if ((object)candidateType == null)
{
newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null);
}
else
{
newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null);
}
}
else if (argument.Kind == BoundKind.DiscardExpression)
{
if ((object)candidateType == null)
{
newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null);
}
else
{
newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType));
}
}
break;
}
case BoundKind.OutDeconstructVarPendingInference:
{
newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this);
break;
}
case BoundKind.Parameter:
case BoundKind.Local:
{
newArguments[i] = BindToTypeForErrorRecovery(argument);
break;
}
default:
{
newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i));
break;
}
}
}
discardedDiagnostics.Free();
return newArguments.ToImmutableAndFree();
TypeSymbol getCorrespondingParameterType(int i)
{
// See if all applicable parameters have the same type
TypeSymbol candidateType = null;
foreach (var parameterList in parameterListList)
{
var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList);
if ((object)parameterType != null)
{
if ((object)candidateType == null)
{
candidateType = parameterType;
}
else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
// type mismatch
candidateType = null;
break;
}
}
}
return candidateType;
}
}
/// <summary>
/// Compute the type of the corresponding parameter, if any. This is used to improve error recovery,
/// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic.
/// If no parameter appears to correspond to the given argument, we return null.
/// </summary>
/// <param name="analyzedArguments">The analyzed argument list</param>
/// <param name="i">The index of the argument</param>
/// <param name="parameterList">The parameter list to match against</param>
/// <returns>The type of the corresponding parameter.</returns>
private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList)
{
string name = analyzedArguments.Name(i);
if (name != null)
{
// look for a parameter by that name
foreach (var parameter in parameterList)
{
if (parameter.Name == name) return parameter.Type;
}
return null;
}
return (i < parameterList.Length) ? parameterList[i].Type : null;
// CONSIDER: should we handle variable argument lists?
}
/// <summary>
/// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery.
/// </summary>
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments)
{
return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>());
}
private BoundCall CreateBadCall(
SyntaxNode node,
BoundExpression expr,
LookupResultKind resultKind,
AnalyzedArguments analyzedArguments)
{
TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null);
var methodContainer = expr.Type ?? this.ContainingType;
MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty);
var args = BuildArgumentsForErrorRecovery(analyzedArguments);
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty;
return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this);
}
private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members)
where TMember : Symbol
{
TypeSymbol type = null;
for (int i = 0, n = members.Length; i < n; i++)
{
TypeSymbol returnType = members[i].GetTypeOrReturnType().Type;
if ((object)type == null)
{
type = returnType;
}
else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2))
{
return null;
}
}
return type;
}
private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result)
{
result = null;
if (node.Expression.Kind() != SyntaxKind.IdentifierName ||
((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword ||
node.ArgumentList.Arguments.Count != 1)
{
return false;
}
ArgumentSyntax argument = node.ArgumentList.Arguments[0];
if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope())
{
return false;
}
result = BindNameofOperatorInternal(node, diagnostics);
return true;
}
private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics);
var argument = node.ArgumentList.Arguments[0].Expression;
// We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder.
var nameofBinder = new NameofBinder(argument, this);
var boundArgument = nameofBinder.BindExpression(argument, diagnostics);
bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics);
if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup)
{
var methodGroup = (BoundMethodGroup)boundArgument;
if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty)
{
// method group with type parameters not allowed
diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location);
}
else
{
nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics);
}
}
if (boundArgument is BoundNamespaceExpression nsExpr)
{
diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol);
}
boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false);
return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String));
}
private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics)
{
// Check that the method group contains something applicable. Otherwise error.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo);
diagnostics.Add(methodGroup.Syntax, useSiteInfo);
diagnostics.AddRange(resolution.Diagnostics);
if (resolution.IsExtensionMethodGroup)
{
diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location);
}
}
/// <summary>
/// Returns true if syntax form is OK (so no errors were reported)
/// </summary>
private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true)
{
switch (argument.Kind())
{
case SyntaxKind.IdentifierName:
{
var syntax = (IdentifierNameSyntax)argument;
name = syntax.Identifier.ValueText;
return true;
}
case SyntaxKind.GenericName:
{
var syntax = (GenericNameSyntax)argument;
name = syntax.Identifier.ValueText;
return true;
}
case SyntaxKind.SimpleMemberAccessExpression:
{
var syntax = (MemberAccessExpressionSyntax)argument;
bool ok = true;
switch (syntax.Expression.Kind())
{
case SyntaxKind.BaseExpression:
case SyntaxKind.ThisExpression:
break;
default:
ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false);
break;
}
name = syntax.Name.Identifier.ValueText;
return ok;
}
case SyntaxKind.AliasQualifiedName:
{
var syntax = (AliasQualifiedNameSyntax)argument;
bool ok = true;
if (top)
{
diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location);
ok = false;
}
name = syntax.Name.Identifier.ValueText;
return ok;
}
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.PredefinedType:
name = "";
if (top) goto default;
return true;
default:
{
var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof;
diagnostics.Add(code, argument.Location);
name = "";
return false;
}
}
}
/// <summary>
/// Helper method that checks whether there is an invocable 'nameof' in scope.
/// </summary>
private bool InvocableNameofInScope()
{
var lookupResult = LookupResult.GetInstance();
const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember;
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options);
var result = lookupResult.IsMultiViable;
lookupResult.Free();
return result;
}
#nullable enable
private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol);
var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type;
var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance();
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1);
methodsBuilder.Add(funcPtr.Signature);
OverloadResolution.FunctionPointerOverloadResolution(
methodsBuilder,
analyzedArguments,
overloadResolutionResult,
ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!overloadResolutionResult.Succeeded)
{
ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree();
overloadResolutionResult.ReportDiagnostics(
binder: this,
node.Location,
nodeOpt: null,
diagnostics,
name: null,
boundExpression,
boundExpression.Syntax,
analyzedArguments,
methods,
typeContainingConstructor: null,
delegateTypeBeingInvoked: null,
returnRefKind: funcPtr.Signature.RefKind);
return new BoundFunctionPointerInvocation(
node,
boundExpression,
BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)),
analyzedArguments.RefKinds.ToImmutableOrNull(),
LookupResultKind.OverloadResolutionFailure,
funcPtr.Signature.ReturnType,
hasErrors: true);
}
methodsBuilder.Free();
MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult;
CoerceArguments(
methodResult,
analyzedArguments.Arguments,
diagnostics,
receiverType: null,
receiverRefKind: null,
receiverEscapeScope: Binder.ExternalScope);
var args = analyzedArguments.Arguments.ToImmutable();
var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics);
if (!hasErrors)
{
hasErrors = !CheckInvocationArgMixing(
node,
funcPtr.Signature,
receiverOpt: null,
funcPtr.Signature.Parameters,
args,
methodResult.Result.ArgsToParamsOpt,
LocalScopeDepth,
diagnostics);
}
return new BoundFunctionPointerInvocation(
node,
boundExpression,
args,
refKinds,
LookupResultKind.Viable,
funcPtr.Signature.ReturnType,
hasErrors);
}
}
}
| // Licensed to the .NET Foundation under one or more 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 System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>.
/// </summary>
internal partial class Binder
{
private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.ParenthesizedExpression:
return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics);
default:
return BindExpression(node, diagnostics, invoked, indexed);
}
}
private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult)
{
// If overload resolution has failed then we want to stash away the original methods that we
// considered so that the IDE can display tooltips or other information about them.
// However, if a method group contained a generic method that was type inferred then
// the IDE wants information about the *inferred* method, not the original unconstructed
// generic method.
if (overloadResolutionResult == null)
{
return ImmutableArray<MethodSymbol>.Empty;
}
var builder = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var result in overloadResolutionResult.Results)
{
builder.Add(result.Member);
}
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Helper method to create a synthesized method invocation expression.
/// </summary>
/// <param name="node">Syntax Node.</param>
/// <param name="receiver">Receiver for the method call.</param>
/// <param name="methodName">Method to be invoked on the receiver.</param>
/// <param name="args">Arguments to the method call.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="typeArgsSyntax">Optional type arguments syntax.</param>
/// <param name="typeArgs">Optional type arguments.</param>
/// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param>
/// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param>
/// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param>
/// <returns>Synthesized method invocation expression.</returns>
internal BoundExpression MakeInvocationExpression(
SyntaxNode node,
BoundExpression receiver,
string methodName,
ImmutableArray<BoundExpression> args,
BindingDiagnosticBag diagnostics,
SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>),
ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>),
ImmutableArray<(string Name, Location Location)?> names = default,
CSharpSyntaxNode? queryClause = null,
bool allowFieldsAndProperties = false,
bool allowUnexpandedForm = true,
bool searchExtensionMethodsIfNecessary = true)
{
Debug.Assert(receiver != null);
Debug.Assert(names.IsDefault || names.Length == args.Length);
receiver = BindToNaturalType(receiver, diagnostics);
var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary);
// The other consumers of this helper (await and collection initializers) require the target member to be a method.
if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess))
{
Symbol symbol;
MessageID msgId;
if (boundExpression.Kind == BoundKind.FieldAccess)
{
msgId = MessageID.IDS_SK_FIELD;
symbol = ((BoundFieldAccess)boundExpression).FieldSymbol;
}
else
{
msgId = MessageID.IDS_SK_PROPERTY;
symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol;
}
diagnostics.Add(
ErrorCode.ERR_BadSKknown,
node.Location,
methodName,
msgId.Localize(),
MessageID.IDS_SK_METHOD.Localize());
return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true);
}
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
boundExpression.WasCompilerGenerated = true;
var analyzedArguments = AnalyzedArguments.GetInstance();
Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference ||
e.Kind == BoundKind.OutDeconstructVarPendingInference ||
e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType()));
analyzedArguments.Arguments.AddRange(args);
if (!names.IsDefault)
{
analyzedArguments.Names.AddRange(names);
}
BoundExpression result = BindInvocationExpression(
node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause,
allowUnexpandedForm: allowUnexpandedForm);
// Query operator can't be called dynamically.
if (queryClause != null && result.Kind == BoundKind.DynamicInvocation)
{
// the error has already been reported by BindInvocationExpression
Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors());
result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result.WasCompilerGenerated = true;
analyzedArguments.Free();
return result;
}
#nullable disable
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
InvocationExpressionSyntax node,
BindingDiagnosticBag diagnostics)
{
BoundExpression result;
if (TryBindNameofOperator(node, diagnostics, out result))
{
return result; // all of the binding is done by BindNameofOperator
}
// M(__arglist()) is legal, but M(__arglist(__arglist()) is not!
bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression;
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
if (isArglist)
{
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false);
result = BindArgListOperator(node, diagnostics, analyzedArguments);
}
else
{
BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics);
boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics);
string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null;
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true);
result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics);
}
analyzedArguments.Free();
return result;
}
private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments)
{
bool hasErrors = analyzedArguments.HasErrors;
// We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them.
TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node);
for (int i = 0; i < analyzedArguments.Arguments.Count; ++i)
{
BoundExpression argument = analyzedArguments.Arguments[i];
if (argument.Kind == BoundKind.OutVariablePendingInference)
{
analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics);
}
else if ((object)argument.Type == null && !argument.HasAnyErrors)
{
// We are going to need every argument in here to have a type. If we don't have one,
// try converting it to object. We'll either succeed (if it is a null literal)
// or fail with a good error message.
//
// Note that the native compiler converts null literals to object, and for everything
// else it either crashes, or produces nonsense code. Roslyn improves upon this considerably.
analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics);
}
else if (argument.Type.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax);
hasErrors = true;
}
else if (analyzedArguments.RefKind(i) == RefKind.None)
{
analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics);
}
switch (analyzedArguments.RefKind(i))
{
case RefKind.None:
case RefKind.Ref:
break;
default:
// Disallow "in" or "out" arguments
Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax);
hasErrors = true;
break;
}
}
ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable();
ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors);
}
/// <summary>
/// Bind an expression as a method invocation.
/// </summary>
private BoundExpression BindInvocationExpression(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause = null,
bool allowUnexpandedForm = true)
{
BoundExpression result;
NamedTypeSymbol delegateType;
if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic())
{
// Either we have a dynamic method group invocation "dyn.M(...)" or
// a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic
// invocation and let the lowering pass sort it out.
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause);
}
else if (boundExpression.Kind == BoundKind.MethodGroup)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindMethodGroupInvocation(
node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments,
diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _);
}
else if ((object)(delegateType = GetDelegateType(boundExpression)) != null)
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node))
{
return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments);
}
result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType);
}
else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType)
{
ReportSuppressionIfNeeded(boundExpression, diagnostics);
result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics);
}
else
{
if (!boundExpression.HasAnyErrors)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location);
}
result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments);
}
CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics);
return result;
}
private BoundExpression BindDynamicInvocation(
SyntaxNode node,
BoundExpression expression,
AnalyzedArguments arguments,
ImmutableArray<MethodSymbol> applicableMethods,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause)
{
CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics);
bool hasErrors = false;
if (expression.Kind == BoundKind.MethodGroup)
{
BoundMethodGroup methodGroup = (BoundMethodGroup)expression;
BoundExpression receiver = methodGroup.ReceiverOpt;
// receiver is null if we are calling a static method declared on an outer class via its simple name:
if (receiver != null)
{
switch (receiver.Kind)
{
case BoundKind.BaseReference:
Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name);
hasErrors = true;
break;
case BoundKind.ThisReference:
// Can't call the HasThis method due to EE doing odd things with containing member and its containing type.
if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated)
{
// Only a static method can be called in a constructor initializer. If we were not in a ctor initializer
// the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before
// the base constructor is called. We need to handle this as a type qualified static method call.
// Also applicable to things like field initializers, which run before the ctor initializer.
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver,
receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(),
resultKind: methodGroup.ResultKind);
}
break;
case BoundKind.TypeOrValueExpression:
var typeOrValue = (BoundTypeOrValueExpression)receiver;
// Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value".
// Ideally the runtime binder would choose between type and value based on the result of the overload resolution.
// We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed.
bool inStaticContext;
bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext);
BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics);
expression = methodGroup.Update(
methodGroup.TypeArgumentsOpt,
methodGroup.Name,
methodGroup.Methods,
methodGroup.LookupSymbolOpt,
methodGroup.LookupError,
methodGroup.Flags,
finalReceiver,
methodGroup.ResultKind);
break;
}
}
}
else
{
expression = BindToNaturalType(expression, diagnostics);
}
ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics);
var refKindsArray = arguments.RefKinds.ToImmutableOrNull();
hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause);
return new BoundDynamicInvocation(
node,
arguments.GetNames(),
refKindsArray,
applicableMethods,
expression,
argArray,
type: Compilation.DynamicType,
hasErrors: hasErrors);
}
private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
if (arguments.Names.Count == 0)
{
return;
}
if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments())
{
return;
}
bool seenName = false;
for (int i = 0; i < arguments.Names.Count; i++)
{
if (arguments.Names[i] != null)
{
seenName = true;
}
else if (seenName)
{
Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax);
return;
}
}
}
private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count);
builder.AddRange(arguments.Arguments);
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = builder[i] switch
{
OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics),
BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics),
var arg => BindToNaturalType(arg, diagnostics)
};
}
return builder.ToImmutableAndFree();
}
// Returns true if there were errors.
private static bool ReportBadDynamicArguments(
SyntaxNode node,
ImmutableArray<BoundExpression> arguments,
ImmutableArray<RefKind> refKinds,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause)
{
bool hasErrors = false;
bool reportedBadQuery = false;
if (!refKinds.IsDefault)
{
for (int argIndex = 0; argIndex < refKinds.Length; argIndex++)
{
if (refKinds[argIndex] == RefKind.In)
{
Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax);
hasErrors = true;
}
}
}
foreach (var arg in arguments)
{
if (!IsLegalDynamicOperand(arg))
{
if (queryClause != null && !reportedBadQuery)
{
reportedBadQuery = true;
Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node);
hasErrors = true;
continue;
}
if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda)
{
// Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.MethodGroup)
{
// Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax);
hasErrors = true;
}
else if (arg.Kind == BoundKind.ArgListOperator)
{
// Not a great error message, since __arglist is not a type, but it'll do.
// error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist");
}
else
{
// Lambdas,anonymous methods and method groups are the typeless expressions that
// are not usable as dynamic arguments; if we get here then the expression must have a type.
Debug.Assert((object)arg.Type != null);
// error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type);
hasErrors = true;
}
}
}
return hasErrors;
}
private BoundExpression BindDelegateInvocation(
SyntaxNode node,
SyntaxNode expression,
string methodName,
BoundExpression boundExpression,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
NamedTypeSymbol delegateType)
{
BoundExpression result;
var methodGroup = MethodGroup.GetInstance();
methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod);
var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
OverloadResolution.MethodInvocationOverloadResolution(
methods: methodGroup.Methods,
typeArguments: methodGroup.TypeArguments,
receiver: methodGroup.Receiver,
arguments: analyzedArguments,
result: overloadResolutionResult,
useSiteInfo: ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
// If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments
// was dynamic then treat this as a dynamic call.
if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember)
{
result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause);
}
else
{
result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause);
}
overloadResolutionResult.Free();
methodGroup.Free();
return result;
}
private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results)
{
var r = results.Results;
for (int i = 0; i < r.Length; ++i)
{
if (r[i].IsApplicable && r[i].Member.IsConditional)
{
return true;
}
}
return false;
}
private BoundExpression BindMethodGroupInvocation(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup methodGroup,
AnalyzedArguments analyzedArguments,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
bool allowUnexpandedForm,
out bool anyApplicableCandidates)
{
BoundExpression result;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(
methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false,
useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm);
diagnostics.Add(expression, useSiteInfo);
anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember;
if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
if (resolution.HasAnyErrors)
{
ImmutableArray<MethodSymbol> originalMethods;
LookupResultKind resultKind;
ImmutableArray<TypeWithAnnotations> typeArguments;
if (resolution.OverloadResolutionResult != null)
{
originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult);
resultKind = resolution.MethodGroup.ResultKind;
typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable();
}
else
{
originalMethods = methodGroup.Methods;
resultKind = methodGroup.ResultKind;
typeArguments = methodGroup.TypeArgumentsOpt;
}
result = CreateBadCall(
syntax,
methodName,
methodGroup.ReceiverOpt,
originalMethods,
resultKind,
typeArguments,
analyzedArguments,
invokedAsExtensionMethod: resolution.IsExtensionMethodGroup,
isDelegate: false);
}
else if (!resolution.IsEmpty)
{
// We're checking resolution.ResultKind, rather than methodGroup.HasErrors
// to better handle the case where there's a problem with the receiver
// (e.g. inaccessible), but the method group resolved correctly (e.g. because
// it's actually an accessible static method on a base type).
// CONSIDER: could check for error types amongst method group type arguments.
if (resolution.ResultKind != LookupResultKind.Viable)
{
if (resolution.MethodGroup != null)
{
// we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448.
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause);
}
// Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting.
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
// If overload resolution found one or more applicable methods and at least one argument
// was dynamic then treat this as a dynamic call.
if (resolution.AnalyzedArguments.HasDynamicArgument &&
resolution.OverloadResolutionResult.HasAnyApplicableMember)
{
if (resolution.IsLocalFunctionInvocation)
{
result = BindLocalFunctionInvocationWithDynamicArgument(
syntax, expression, methodName, methodGroup,
diagnostics, queryClause, resolution);
}
else if (resolution.IsExtensionMethodGroup)
{
// error CS1973: 'T' has no applicable method named 'M' but appears to have an
// extension method by that name. Extension methods cannot be dynamically dispatched. Consider
// casting the dynamic arguments or calling the extension method without the extension method
// syntax.
// We found an extension method, so the instance associated with the method group must have
// existed and had a type.
Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null);
Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name);
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
else
{
if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult))
{
// warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime
// because one or more applicable overloads are conditional methods
Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name);
}
// Note that the runtime binder may consider candidates that haven't passed compile-time final validation
// and an ambiguity error may be reported. Also additional checks are performed in runtime final validation
// that are not performed at compile-time.
// Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime.
var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult,
methodGroup.ReceiverOpt,
methodGroup.TypeArgumentsOpt,
diagnostics);
if (finalApplicableCandidates.Length > 0)
{
result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause);
}
else
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
}
}
else
{
result = BindInvocationExpressionContinued(
syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments,
resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause);
}
}
}
else
{
result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments);
}
resolution.Free();
return result;
}
private BoundExpression BindLocalFunctionInvocationWithDynamicArgument(
SyntaxNode syntax,
SyntaxNode expression,
string methodName,
BoundMethodGroup boundMethodGroup,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause,
MethodGroupResolution resolution)
{
// Invocations of local functions with dynamic arguments don't need
// to be dispatched as dynamic invocations since they cannot be
// overloaded. Instead, we'll just emit a standard call with
// dynamic implicit conversions for any dynamic arguments. There
// are two exceptions: "params", and unconstructed generics. While
// implementing those cases with dynamic invocations is possible,
// we have decided the implementation complexity is not worth it.
// Refer to the comments below for the exact semantics.
Debug.Assert(resolution.IsLocalFunctionInvocation);
Debug.Assert(resolution.OverloadResolutionResult.Succeeded);
Debug.Assert(queryClause == null);
var validResult = resolution.OverloadResolutionResult.ValidResult;
var args = resolution.AnalyzedArguments.Arguments.ToImmutable();
var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull();
ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause);
var localFunction = validResult.Member;
var methodResult = validResult.Result;
// We're only in trouble if a dynamic argument is passed to the
// params parameter and is ambiguous at compile time between normal
// and expanded form i.e., there is exactly one dynamic argument to
// a params parameter
// See https://github.com/dotnet/roslyn/issues/10708
if (OverloadResolution.IsValidParams(localFunction) &&
methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm)
{
var parameters = localFunction.Parameters;
Debug.Assert(parameters.Last().IsParams);
var lastParamIndex = parameters.Length - 1;
for (int i = 0; i < args.Length; ++i)
{
var arg = args[i];
if (arg.HasDynamicType() &&
methodResult.ParameterFromArgument(i) == lastParamIndex)
{
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionParamsParameter,
syntax, parameters.Last().Name, localFunction.Name);
return BindDynamicInvocation(
syntax,
boundMethodGroup,
resolution.AnalyzedArguments,
resolution.OverloadResolutionResult.GetAllApplicableMembers(),
diagnostics,
queryClause);
}
}
}
// If we call an unconstructed generic local function with a
// dynamic argument in a place where it influences the type
// parameters, we need to dynamically dispatch the call (as the
// function must be constructed at runtime). We cannot do that, so
// disallow that. However, doing a specific analysis of each
// argument and its corresponding parameter to check if it's
// generic (and allow dynamic in non-generic parameters) may break
// overload resolution in the future, if we ever allow overloaded
// local functions. So, just disallow any mixing of dynamic and
// inferred generics. (Explicit generic arguments are fine)
// See https://github.com/dotnet/roslyn/issues/21317
if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod)
{
Error(diagnostics,
ErrorCode.ERR_DynamicLocalFunctionTypeParameter,
syntax, localFunction.Name);
return BindDynamicInvocation(
syntax,
boundMethodGroup,
resolution.AnalyzedArguments,
resolution.OverloadResolutionResult.GetAllApplicableMembers(),
diagnostics,
queryClause);
}
return BindInvocationExpressionContinued(
node: syntax,
expression: expression,
methodName: methodName,
result: resolution.OverloadResolutionResult,
analyzedArguments: resolution.AnalyzedArguments,
methodGroup: resolution.MethodGroup,
delegateTypeOpt: null,
diagnostics: diagnostics,
queryClause: queryClause);
}
private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>(
SyntaxNode syntax,
OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult,
BoundExpression receiverOpt,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol
{
Debug.Assert(overloadResolutionResult.HasAnyApplicableMember);
var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance();
BindingDiagnosticBag firstFailed = null;
var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++)
{
var result = overloadResolutionResult.ResultsBuilder[i];
if (result.Result.IsApplicable)
{
// For F to pass the check, all of the following must hold:
// ...
// * If the type parameters of F were substituted in the step above, their constraints are satisfied.
// * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
// * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value,
// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) &&
(typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics))))
{
finalCandidates.Add(result.Member);
continue;
}
if (firstFailed == null)
{
firstFailed = candidateDiagnostics;
candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics);
}
else
{
candidateDiagnostics.Clear();
}
}
}
if (firstFailed != null)
{
// Report diagnostics of the first candidate that failed the validation
// unless we have at least one candidate that passes.
if (finalCandidates.Count == 0)
{
diagnostics.AddRange(firstFailed);
}
firstFailed.Free();
}
candidateDiagnostics.Free();
return finalCandidates.ToImmutableAndFree();
}
private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
// It is never legal to box a restricted type, even if we are boxing it as the receiver
// of a method call. When must be box? We skip boxing when the method in question is defined
// on the restricted type or overridden by the restricted type.
switch (expression.Kind)
{
case BoundKind.Call:
{
var call = (BoundCall)expression;
if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null)
{
// error CS0029: Cannot implicitly convert type 'A' to 'B'
// Case 1: receiver is a restricted type, and method called is defined on a parent type
if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2))
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType);
Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second);
}
// Case 2: receiver is a base reference, and the child type is restricted
else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType())
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType);
Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second);
}
}
}
break;
case BoundKind.DynamicInvocation:
{
var dynInvoke = (BoundDynamicInvocation)expression;
if (!dynInvoke.HasAnyErrors &&
(object)dynInvoke.Expression.Type != null &&
dynInvoke.Expression.Type.IsRestrictedType())
{
// eg: b = typedReference.Equals(dyn);
// error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation
Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type);
}
}
break;
case BoundKind.FunctionPointerInvocation:
break;
default:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
/// <summary>
/// Perform overload resolution on the method group or expression (BoundMethodGroup)
/// and arguments and return a BoundExpression representing the invocation.
/// </summary>
/// <param name="node">Invocation syntax node.</param>
/// <param name="expression">The syntax for the invoked method, including receiver.</param>
/// <param name="methodName">Name of the invoked method.</param>
/// <param name="result">Overload resolution result for method group executed by caller.</param>
/// <param name="analyzedArguments">Arguments bound by the caller.</param>
/// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param>
/// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param>
/// <returns>BoundCall or error expression representing the invocation.</returns>
private BoundCall BindInvocationExpressionContinued(
SyntaxNode node,
SyntaxNode expression,
string methodName,
OverloadResolutionResult<MethodSymbol> result,
AnalyzedArguments analyzedArguments,
MethodGroup methodGroup,
NamedTypeSymbol delegateTypeOpt,
BindingDiagnosticBag diagnostics,
CSharpSyntaxNode queryClause = null)
{
Debug.Assert(node != null);
Debug.Assert(methodGroup != null);
Debug.Assert(methodGroup.Error == null);
Debug.Assert(methodGroup.Methods.Count > 0);
Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1));
var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup;
// Delegate invocations should never be considered extension method
// invocations (even though the delegate may refer to an extension method).
Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null));
// We have already determined that we are not in a situation where we can successfully do
// a dynamic binding. We might be in one of the following situations:
//
// * There were dynamic arguments but overload resolution still found zero applicable candidates.
// * There were no dynamic arguments and overload resolution found zero applicable candidates.
// * There were no dynamic arguments and overload resolution found multiple applicable candidates
// without being able to find the best one.
//
// In those three situations we might give an additional error.
if (!result.Succeeded)
{
if (analyzedArguments.HasErrors)
{
// Errors for arguments have already been reported, except for unbound lambdas and switch expressions.
// We report those now.
foreach (var argument in analyzedArguments.Arguments)
{
switch (argument)
{
case UnboundLambda unboundLambda:
var boundWithErrors = unboundLambda.BindForErrorRecovery();
diagnostics.AddRange(boundWithErrors.Diagnostics);
break;
case BoundUnconvertedObjectCreationExpression _:
case BoundTupleLiteral _:
// Tuple literals can contain unbound lambdas or switch expressions.
_ = BindToNaturalType(argument, diagnostics);
break;
case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr:
_ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics);
break;
case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr:
_ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics);
break;
}
}
}
else
{
// Since there were no argument errors to report, we report an error on the invocation itself.
string name = (object)delegateTypeOpt == null ? methodName : null;
result.ReportDiagnostics(
binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name,
receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(),
typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause);
}
return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver,
GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null));
}
// Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate.
// We still have to determine if it passes final validation.
var methodResult = result.ValidResult;
var returnType = methodResult.Member.ReturnType;
var method = methodResult.Member;
// It is possible that overload resolution succeeded, but we have chosen an
// instance method and we're in a static method. A careful reading of the
// overload resolution spec shows that the "final validation" stage allows an
// "implicit this" on any method call, not just method calls from inside
// instance methods. Therefore we must detect this scenario here, rather than in
// overload resolution.
var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics);
var receiverRefKind = receiver?.GetRefKind();
uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null
? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth)
: Binder.ExternalScope;
this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope);
var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm;
var argsToParams = methodResult.Result.ArgsToParamsOpt;
BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics);
// Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2),
// so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors.
// Note: final validation wants the receiver that corresponds to the source representation
// (i.e. the first argument, if invokedAsExtensionMethod).
var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod);
CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics);
if (invokedAsExtensionMethod)
{
BoundExpression receiverArgument = analyzedArguments.Argument(0);
ParameterSymbol receiverParameter = method.Parameters.First();
// we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue
if ((object)receiver != receiverArgument)
{
// Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here.
Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0);
receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0),
receiverParameter.Type, diagnostics);
}
if (receiverParameter.RefKind == RefKind.Ref)
{
// If this was a ref extension method, receiverArgument must be checked for L-value constraints.
// This helper method will also replace it with a BoundBadExpression if it was invalid.
receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics);
if (analyzedArguments.RefKinds.Count == 0)
{
analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count;
}
// receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref)
// we need to adjust the argument refkind as if we had a `ref` modifier in a call.
analyzedArguments.RefKinds[0] = RefKind.Ref;
CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics);
}
else if (receiverParameter.RefKind == RefKind.In)
{
// NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case.
Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None);
CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics);
}
analyzedArguments.Arguments[0] = receiverArgument;
}
// This will be the receiver of the BoundCall node that we create.
// For extension methods, there is no receiver because the receiver in source was actually the first argument.
// For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter.
// For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it.
if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated))
{
receiver = null;
}
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var args = analyzedArguments.Arguments.ToImmutable();
if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated)
{
gotError = IsRefOrOutThisParameterCaptured(node, diagnostics);
}
// What if some of the arguments are implicit? Dev10 reports unsafe errors
// if the implied argument would have an unsafe type. We need to check
// the parameters explicitly, since there won't be bound nodes for the implied
// arguments until lowering.
if (method.HasUnsafeParameter())
{
// Don't worry about double reporting (i.e. for both the argument and the parameter)
// because only one unsafe diagnostic is allowed per scope - the others are suppressed.
gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError;
}
bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference;
ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver);
ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false);
// No use site errors, but there could be use site warnings.
// If there are any use site warnings, they have already been reported by overload resolution.
Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors.");
if (method.IsRuntimeFinalizer())
{
ErrorCode code = hasBaseReceiver
? ErrorCode.ERR_CallingBaseFinalizeDeprecated
: ErrorCode.ERR_CallingFinalizeDeprecated;
Error(diagnostics, code, node);
gotError = true;
}
Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]);
if (!gotError)
{
gotError = !CheckInvocationArgMixing(
node,
method,
receiver,
method.Parameters,
args,
argsToParams,
this.LocalScopeDepth,
diagnostics);
}
bool isDelegateCall = (object)delegateTypeOpt != null;
if (!isDelegateCall)
{
if (method.RequiresInstanceReceiver)
{
WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ?
((InvocationExpressionSyntax)node).Expression :
node,
receiver,
diagnostics);
}
}
return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall,
expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod,
argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError);
}
#nullable enable
private static SourceLocation GetCallerLocation(SyntaxNode syntax)
{
var token = syntax switch
{
InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken,
BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword,
ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken,
PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken,
ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken,
_ => syntax.GetFirstToken()
};
return new SourceLocation(token);
}
private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics)
{
var parameterType = parameter.Type;
Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object);
// We have a call to a method M([Optional] object x) which omits the argument. The value we generate
// for the argument depends on the presence or absence of other attributes. The rules are:
//
// * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)]
// then the argument is null.
// * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is
// new UnknownWrapper(null)
// * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is
// new DispatchWrapper(null)
// * Otherwise, the argument is Type.Missing.
BoundExpression? defaultValue = null;
if (parameter.IsMarshalAsObject)
{
// default(object)
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else if (parameter.IsIUnknownConstant)
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol)
{
// new UnknownWrapper(default(object))
var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true };
}
}
else if (parameter.IsIDispatchConstant)
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol)
{
// new DispatchWrapper(default(object))
var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true };
}
}
else
{
if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol)
{
// Type.Missing
defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true };
}
}
return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated();
}
internal static ParameterSymbol? GetCorrespondingParameter(
int argumentOrdinal,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<int> argsToParamsOpt,
bool expanded)
{
int n = parameters.Length;
ParameterSymbol? parameter;
if (argsToParamsOpt.IsDefault)
{
if (argumentOrdinal < n)
{
parameter = parameters[argumentOrdinal];
}
else if (expanded)
{
parameter = parameters[n - 1];
}
else
{
parameter = null;
}
}
else
{
Debug.Assert(argumentOrdinal < argsToParamsOpt.Length);
int parameterOrdinal = argsToParamsOpt[argumentOrdinal];
if (parameterOrdinal < n)
{
parameter = parameters[parameterOrdinal];
}
else
{
parameter = null;
}
}
return parameter;
}
internal void BindDefaultArguments(
SyntaxNode node,
ImmutableArray<ParameterSymbol> parameters,
ArrayBuilder<BoundExpression> argumentsBuilder,
ArrayBuilder<RefKind>? argumentRefKindsBuilder,
ref ImmutableArray<int> argsToParamsOpt,
out BitVector defaultArguments,
bool expanded,
bool enableCallerInfo,
BindingDiagnosticBag diagnostics,
bool assertMissingParametersAreOptional = true)
{
var visitedParameters = BitVector.Create(parameters.Length);
for (var i = 0; i < argumentsBuilder.Count; i++)
{
var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded);
if (parameter is not null)
{
visitedParameters[parameter.Ordinal] = true;
}
}
// only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument
if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters))
{
defaultArguments = default;
return;
}
// In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field.
// We want to use the associated user-declared symbol instead where possible.
var containingMember = ContainingMember() switch
{
FieldSymbol { AssociatedSymbol: { } symbol } => symbol,
var c => c
};
defaultArguments = BitVector.Create(parameters.Length);
ArrayBuilder<int>? argsToParamsBuilder = null;
if (!argsToParamsOpt.IsDefault)
{
argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length);
argsToParamsBuilder.AddRange(argsToParamsOpt);
}
// Params methods can be invoked in normal form, so the strongest assertion we can make is that, if
// we're in an expanded context, the last param must be params. The inverse is not necessarily true.
Debug.Assert(!expanded || parameters[^1].IsParams);
// Params array is filled in the local rewriter
var lastIndex = expanded ? ^1 : ^0;
var argumentsCount = argumentsBuilder.Count;
// Go over missing parameters, inserting default values for optional parameters
foreach (var parameter in parameters.AsSpan()[..lastIndex])
{
if (!visitedParameters[parameter.Ordinal])
{
Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional);
defaultArguments[argumentsBuilder.Count] = true;
argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt));
if (argumentRefKindsBuilder is { Count: > 0 })
{
argumentRefKindsBuilder.Add(RefKind.None);
}
argsToParamsBuilder?.Add(parameter.Ordinal);
}
}
Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count);
Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count);
if (argsToParamsBuilder is object)
{
argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull();
argsToParamsBuilder.Free();
}
BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt)
{
TypeSymbol parameterType = parameter.Type;
if (Flags.Includes(BinderFlags.ParameterDefaultValue))
{
// This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }`
// We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller.
return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch
{
// Bad default values are implicitly replaced with default(T) at call sites.
{ IsBad: true } => ConstantValue.Null,
var constantValue => constantValue
};
Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset);
var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null;
BoundExpression defaultValue;
if (callerSourceLocation is object && parameter.IsCallerLineNumber)
{
int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan);
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && parameter.IsCallerFilePath)
{
string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver);
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && parameter.IsCallerMemberName)
{
var memberName = containingMember.GetMemberCallerName();
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex &&
argumentIndex > -1 && argumentIndex < argumentsCount)
{
var argument = argumentsBuilder[argumentIndex];
defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true };
}
else if (defaultConstantValue == ConstantValue.NotAvailable)
{
// There is no constant value given for the parameter in source/metadata.
if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object)
{
// We have something like M([Optional] object x). We have special handling for such situations.
defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics);
}
else
{
// The argument to M([Optional] int x) becomes default(int)
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
}
else if (defaultConstantValue.IsNull)
{
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else
{
TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType);
defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true };
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime })
{
// Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site.
// For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type
// then we want to silently replace it with default(ParameterType).
defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true };
}
else
{
if (!conversion.IsValid)
{
GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType);
}
var isCast = conversion.IsExplicit;
defaultValue = CreateConversion(
defaultValue.Syntax,
defaultValue,
conversion,
isCast,
isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null,
parameterType,
diagnostics);
}
return defaultValue;
static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt)
=> argsToParamsOpt.IsDefault
? parameterIndex
: argsToParamsOpt.IndexOf(parameterIndex);
}
}
#nullable disable
/// <summary>
/// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member.
/// </summary>
internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics)
{
// For now we are warning only in implicit copy scenarios that are only possible with readonly members.
// Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968.
if (receiver is BoundThisReference &&
receiver.Type.IsValueType &&
ContainingMemberOrLambda is MethodSymbol containingMethod &&
containingMethod.IsEffectivelyReadOnly &&
// Ignore calls to base members.
TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) &&
!method.IsEffectivelyReadOnly &&
method.RequiresInstanceReceiver)
{
Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName);
return false;
}
return true;
}
/// <param name="node">Invocation syntax node.</param>
/// <param name="expression">The syntax for the invoked method, including receiver.</param>
private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression)
{
if (node != expression)
{
switch (expression.Kind())
{
case SyntaxKind.QualifiedName:
return ((QualifiedNameSyntax)expression).Right.GetLocation();
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return ((MemberAccessExpressionSyntax)expression).Name.GetLocation();
}
}
return expression.GetLocation();
}
/// <summary>
/// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true)
/// or a value (if useType is false). Any other node is bound to its natural type.
/// </summary>
/// <remarks>
/// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression
/// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise.
/// </remarks>
private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics)
{
if ((object)receiver == null)
{
return null;
}
switch (receiver.Kind)
{
case BoundKind.TypeOrValueExpression:
var typeOrValue = (BoundTypeOrValueExpression)receiver;
if (useType)
{
diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics);
return typeOrValue.Data.TypeExpression;
}
else
{
diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics);
return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics);
}
case BoundKind.QueryClause:
// a query clause may wrap a TypeOrValueExpression.
var q = (BoundQueryClause)receiver;
var value = q.Value;
var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics);
return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type);
default:
return BindToNaturalType(receiver, diagnostics);
}
}
/// <summary>
/// Return the delegate type if this expression represents a delegate.
/// </summary>
private static NamedTypeSymbol GetDelegateType(BoundExpression expr)
{
if ((object)expr != null && expr.Kind != BoundKind.TypeExpression)
{
var type = expr.Type as NamedTypeSymbol;
if (((object)type != null) && type.IsDelegateType())
{
return type;
}
}
return null;
}
private BoundCall CreateBadCall(
SyntaxNode node,
string name,
BoundExpression receiver,
ImmutableArray<MethodSymbol> methods,
LookupResultKind resultKind,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
AnalyzedArguments analyzedArguments,
bool invokedAsExtensionMethod,
bool isDelegate)
{
MethodSymbol method;
ImmutableArray<BoundExpression> args;
if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty)
{
var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var m in methods)
{
constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m);
}
methods = constructedMethods.ToImmutableAndFree();
}
if (methods.Length == 1 && !IsUnboundGeneric(methods[0]))
{
method = methods[0];
}
else
{
var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null);
var methodContainer = (object)receiver != null && (object)receiver.Type != null
? receiver.Type
: this.ContainingType;
method = new ErrorMethodSymbol(methodContainer, returnType, name);
}
args = BuildArgumentsForErrorRecovery(analyzedArguments, methods);
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
receiver = BindToTypeForErrorRecovery(receiver);
return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this);
}
private static bool IsUnboundGeneric(MethodSymbol method)
{
return method.IsGenericMethod && method.ConstructedFrom() == method;
}
// Arbitrary limit on the number of parameter lists from overload
// resolution candidates considered when binding argument types.
// Any additional parameter lists are ignored.
internal const int MaxParameterListsForErrorRecovery = 10;
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods)
{
var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance();
foreach (var m in methods)
{
if (!IsUnboundGeneric(m) && m.ParameterCount > 0)
{
parameterListList.Add(m.Parameters);
if (parameterListList.Count == MaxParameterListsForErrorRecovery)
{
break;
}
}
}
var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList);
parameterListList.Free();
return result;
}
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties)
{
var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance();
foreach (var p in properties)
{
if (p.ParameterCount > 0)
{
parameterListList.Add(p.Parameters);
if (parameterListList.Count == MaxParameterListsForErrorRecovery)
{
break;
}
}
}
var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList);
parameterListList.Free();
return result;
}
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList)
{
var discardedDiagnostics = DiagnosticBag.GetInstance();
int argumentCount = analyzedArguments.Arguments.Count;
ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount);
newArguments.AddRange(analyzedArguments.Arguments);
for (int i = 0; i < argumentCount; i++)
{
var argument = newArguments[i];
switch (argument.Kind)
{
case BoundKind.UnboundLambda:
{
// bind the argument against each applicable parameter
var unboundArgument = (UnboundLambda)argument;
foreach (var parameterList in parameterListList)
{
var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList);
if (parameterType?.Kind == SymbolKind.NamedType &&
(object)parameterType.GetDelegateType() != null)
{
// Just assume we're not in an expression tree for the purposes of error recovery.
var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false);
}
}
// replace the unbound lambda with its best inferred bound version
newArguments[i] = unboundArgument.BindForErrorRecovery();
break;
}
case BoundKind.OutVariablePendingInference:
case BoundKind.DiscardExpression:
{
if (argument.HasExpressionType())
{
break;
}
var candidateType = getCorrespondingParameterType(i);
if (argument.Kind == BoundKind.OutVariablePendingInference)
{
if ((object)candidateType == null)
{
newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null);
}
else
{
newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null);
}
}
else if (argument.Kind == BoundKind.DiscardExpression)
{
if ((object)candidateType == null)
{
newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null);
}
else
{
newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType));
}
}
break;
}
case BoundKind.OutDeconstructVarPendingInference:
{
newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this);
break;
}
case BoundKind.Parameter:
case BoundKind.Local:
{
newArguments[i] = BindToTypeForErrorRecovery(argument);
break;
}
default:
{
newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i));
break;
}
}
}
discardedDiagnostics.Free();
return newArguments.ToImmutableAndFree();
TypeSymbol getCorrespondingParameterType(int i)
{
// See if all applicable parameters have the same type
TypeSymbol candidateType = null;
foreach (var parameterList in parameterListList)
{
var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList);
if ((object)parameterType != null)
{
if ((object)candidateType == null)
{
candidateType = parameterType;
}
else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
// type mismatch
candidateType = null;
break;
}
}
}
return candidateType;
}
}
/// <summary>
/// Compute the type of the corresponding parameter, if any. This is used to improve error recovery,
/// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic.
/// If no parameter appears to correspond to the given argument, we return null.
/// </summary>
/// <param name="analyzedArguments">The analyzed argument list</param>
/// <param name="i">The index of the argument</param>
/// <param name="parameterList">The parameter list to match against</param>
/// <returns>The type of the corresponding parameter.</returns>
private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList)
{
string name = analyzedArguments.Name(i);
if (name != null)
{
// look for a parameter by that name
foreach (var parameter in parameterList)
{
if (parameter.Name == name) return parameter.Type;
}
return null;
}
return (i < parameterList.Length) ? parameterList[i].Type : null;
// CONSIDER: should we handle variable argument lists?
}
/// <summary>
/// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery.
/// </summary>
private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments)
{
return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>());
}
private BoundCall CreateBadCall(
SyntaxNode node,
BoundExpression expr,
LookupResultKind resultKind,
AnalyzedArguments analyzedArguments)
{
TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null);
var methodContainer = expr.Type ?? this.ContainingType;
MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty);
var args = BuildArgumentsForErrorRecovery(analyzedArguments);
var argNames = analyzedArguments.GetNames();
var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty;
return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this);
}
private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members)
where TMember : Symbol
{
TypeSymbol type = null;
for (int i = 0, n = members.Length; i < n; i++)
{
TypeSymbol returnType = members[i].GetTypeOrReturnType().Type;
if ((object)type == null)
{
type = returnType;
}
else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2))
{
return null;
}
}
return type;
}
private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result)
{
result = null;
if (node.Expression.Kind() != SyntaxKind.IdentifierName ||
((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword ||
node.ArgumentList.Arguments.Count != 1)
{
return false;
}
ArgumentSyntax argument = node.ArgumentList.Arguments[0];
if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope())
{
return false;
}
result = BindNameofOperatorInternal(node, diagnostics);
return true;
}
private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics);
var argument = node.ArgumentList.Arguments[0].Expression;
// We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder.
var nameofBinder = new NameofBinder(argument, this);
var boundArgument = nameofBinder.BindExpression(argument, diagnostics);
bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics);
if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup)
{
var methodGroup = (BoundMethodGroup)boundArgument;
if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty)
{
// method group with type parameters not allowed
diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location);
}
else
{
nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics);
}
}
if (boundArgument is BoundNamespaceExpression nsExpr)
{
diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol);
}
boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false);
return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String));
}
private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics)
{
// Check that the method group contains something applicable. Otherwise error.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo);
diagnostics.Add(methodGroup.Syntax, useSiteInfo);
diagnostics.AddRange(resolution.Diagnostics);
if (resolution.IsExtensionMethodGroup)
{
diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location);
}
}
/// <summary>
/// Returns true if syntax form is OK (so no errors were reported)
/// </summary>
private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true)
{
switch (argument.Kind())
{
case SyntaxKind.IdentifierName:
{
var syntax = (IdentifierNameSyntax)argument;
name = syntax.Identifier.ValueText;
return true;
}
case SyntaxKind.GenericName:
{
var syntax = (GenericNameSyntax)argument;
name = syntax.Identifier.ValueText;
return true;
}
case SyntaxKind.SimpleMemberAccessExpression:
{
var syntax = (MemberAccessExpressionSyntax)argument;
bool ok = true;
switch (syntax.Expression.Kind())
{
case SyntaxKind.BaseExpression:
case SyntaxKind.ThisExpression:
break;
default:
ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false);
break;
}
name = syntax.Name.Identifier.ValueText;
return ok;
}
case SyntaxKind.AliasQualifiedName:
{
var syntax = (AliasQualifiedNameSyntax)argument;
bool ok = true;
if (top)
{
diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location);
ok = false;
}
name = syntax.Name.Identifier.ValueText;
return ok;
}
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.PredefinedType:
name = "";
if (top) goto default;
return true;
default:
{
var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof;
diagnostics.Add(code, argument.Location);
name = "";
return false;
}
}
}
/// <summary>
/// Helper method that checks whether there is an invocable 'nameof' in scope.
/// </summary>
private bool InvocableNameofInScope()
{
var lookupResult = LookupResult.GetInstance();
const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember;
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options);
var result = lookupResult.IsMultiViable;
lookupResult.Free();
return result;
}
#nullable enable
private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol);
var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type;
var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance();
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1);
methodsBuilder.Add(funcPtr.Signature);
OverloadResolution.FunctionPointerOverloadResolution(
methodsBuilder,
analyzedArguments,
overloadResolutionResult,
ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!overloadResolutionResult.Succeeded)
{
ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree();
overloadResolutionResult.ReportDiagnostics(
binder: this,
node.Location,
nodeOpt: null,
diagnostics,
name: null,
boundExpression,
boundExpression.Syntax,
analyzedArguments,
methods,
typeContainingConstructor: null,
delegateTypeBeingInvoked: null,
returnRefKind: funcPtr.Signature.RefKind);
return new BoundFunctionPointerInvocation(
node,
boundExpression,
BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)),
analyzedArguments.RefKinds.ToImmutableOrNull(),
LookupResultKind.OverloadResolutionFailure,
funcPtr.Signature.ReturnType,
hasErrors: true);
}
methodsBuilder.Free();
MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult;
CoerceArguments(
methodResult,
analyzedArguments.Arguments,
diagnostics,
receiverType: null,
receiverRefKind: null,
receiverEscapeScope: Binder.ExternalScope);
var args = analyzedArguments.Arguments.ToImmutable();
var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics);
if (!hasErrors)
{
hasErrors = !CheckInvocationArgMixing(
node,
funcPtr.Signature,
receiverOpt: null,
funcPtr.Signature.Parameters,
args,
methodResult.Result.ArgsToParamsOpt,
LocalScopeDepth,
diagnostics);
}
return new BoundFunctionPointerInvocation(
node,
boundExpression,
args,
refKinds,
LookupResultKind.Viable,
funcPtr.Signature.ReturnType,
hasErrors);
}
}
}
| -1 |
dotnet/roslyn | 55,354 | Add IFieldSymbol.FixedSize API | Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| 333fred | 2021-08-02T22:15:12Z | 2021-08-03T21:43:37Z | 76bdda7fe502a74f91aee0feb2fe251039be4e82 | a81b07d0d5a6b5c5430443fc843e4a730399c946 | Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
| ./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/c3.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L +L ! & |