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 &amp;&amp; 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 &amp;&amp; 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. $PEL+L! & @@ @@&K@`  H.text  `.rsrc@ @@.reloc `@Bp&H!@( *0 +*0 +*0 +**0 +*0 +*( *( *( *( *( *( *( *BSJB v4.0.30319l#~0@#Stringsp#USx#GUID#BlobG %3 7OH _ dlz  # ( -2 6; CP V X ol s " + CI O V  V  V  V  V  V  V  V 9V AVIV A..#[foxFX4 \iw  <Module>mscorlibC3C6`1C300I1C301C302C304ns1C303ns1.ns2C305SystemObject.ctorc1C1`1C2`1c4C4FooBarc7C8`1C7Foo1Foo2x1x2x3x4Foo3TFoo3Foo4TSystem.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributec3c3.dll ,xDw{z\V4      0     TWrapNonExceptionThrowsh&~& p&_CorDllMainmscoree.dll% @0HX@444VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfop000004b0,FileDescription 0FileVersion0.0.0.00InternalNamec3.dll(LegalCopyright 8OriginalFilenamec3.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
MZ@ !L!This program cannot be run in DOS mode. $PEL+L! & @@ @@&K@`  H.text  `.rsrc@ @@.reloc `@Bp&H!@( *0 +*0 +*0 +**0 +*0 +*( *( *( *( *( *( *( *BSJB v4.0.30319l#~0@#Stringsp#USx#GUID#BlobG %3 7OH _ dlz  # ( -2 6; CP V X ol s " + CI O V  V  V  V  V  V  V  V 9V AVIV A..#[foxFX4 \iw  <Module>mscorlibC3C6`1C300I1C301C302C304ns1C303ns1.ns2C305SystemObject.ctorc1C1`1C2`1c4C4FooBarc7C8`1C7Foo1Foo2x1x2x3x4Foo3TFoo3Foo4TSystem.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributec3c3.dll ,xDw{z\V4      0     TWrapNonExceptionThrowsh&~& p&_CorDllMainmscoree.dll% @0HX@444VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfop000004b0,FileDescription 0FileVersion0.0.0.00InternalNamec3.dll(LegalCopyright 8OriginalFilenamec3.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
-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/Operations/Loops/ForEachLoopOperationInfo.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; namespace Microsoft.CodeAnalysis.Operations { internal class ForEachLoopOperationInfo { /// <summary> /// Element type of the collection /// </summary> public readonly ITypeSymbol ElementType; public readonly IMethodSymbol GetEnumeratorMethod; public readonly IPropertySymbol CurrentProperty; public readonly IMethodSymbol MoveNextMethod; public readonly bool IsAsynchronous; public readonly bool NeedsDispose; public readonly bool KnownToImplementIDisposable; public readonly IMethodSymbol? PatternDisposeMethod; /// <summary> /// The conversion from the type of the <see cref="CurrentProperty"/> to the <see cref="ElementType"/>. /// </summary> public readonly IConvertibleConversion CurrentConversion; /// <summary> /// The conversion from the <see cref="ElementType"/> to the iteration variable type. /// </summary> public readonly IConvertibleConversion ElementConversion; public readonly ImmutableArray<IArgumentOperation> GetEnumeratorArguments; public readonly ImmutableArray<IArgumentOperation> MoveNextArguments; public readonly ImmutableArray<IArgumentOperation> CurrentArguments; public readonly ImmutableArray<IArgumentOperation> DisposeArguments; public ForEachLoopOperationInfo( ITypeSymbol elementType, IMethodSymbol getEnumeratorMethod, IPropertySymbol currentProperty, IMethodSymbol moveNextMethod, bool isAsynchronous, bool needsDispose, bool knownToImplementIDisposable, IMethodSymbol? patternDisposeMethod, IConvertibleConversion currentConversion, IConvertibleConversion elementConversion, ImmutableArray<IArgumentOperation> getEnumeratorArguments = default, ImmutableArray<IArgumentOperation> moveNextArguments = default, ImmutableArray<IArgumentOperation> currentArguments = default, ImmutableArray<IArgumentOperation> disposeArguments = default) { ElementType = elementType; GetEnumeratorMethod = getEnumeratorMethod; CurrentProperty = currentProperty; MoveNextMethod = moveNextMethod; IsAsynchronous = isAsynchronous; KnownToImplementIDisposable = knownToImplementIDisposable; NeedsDispose = needsDispose; PatternDisposeMethod = patternDisposeMethod; CurrentConversion = currentConversion; ElementConversion = elementConversion; GetEnumeratorArguments = getEnumeratorArguments; MoveNextArguments = moveNextArguments; CurrentArguments = currentArguments; DisposeArguments = disposeArguments; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Operations { internal class ForEachLoopOperationInfo { /// <summary> /// Element type of the collection /// </summary> public readonly ITypeSymbol ElementType; public readonly IMethodSymbol GetEnumeratorMethod; public readonly IPropertySymbol CurrentProperty; public readonly IMethodSymbol MoveNextMethod; public readonly bool IsAsynchronous; public readonly bool NeedsDispose; public readonly bool KnownToImplementIDisposable; public readonly IMethodSymbol? PatternDisposeMethod; /// <summary> /// The conversion from the type of the <see cref="CurrentProperty"/> to the <see cref="ElementType"/>. /// </summary> public readonly IConvertibleConversion CurrentConversion; /// <summary> /// The conversion from the <see cref="ElementType"/> to the iteration variable type. /// </summary> public readonly IConvertibleConversion ElementConversion; public readonly ImmutableArray<IArgumentOperation> GetEnumeratorArguments; public readonly ImmutableArray<IArgumentOperation> MoveNextArguments; public readonly ImmutableArray<IArgumentOperation> CurrentArguments; public readonly ImmutableArray<IArgumentOperation> DisposeArguments; public ForEachLoopOperationInfo( ITypeSymbol elementType, IMethodSymbol getEnumeratorMethod, IPropertySymbol currentProperty, IMethodSymbol moveNextMethod, bool isAsynchronous, bool needsDispose, bool knownToImplementIDisposable, IMethodSymbol? patternDisposeMethod, IConvertibleConversion currentConversion, IConvertibleConversion elementConversion, ImmutableArray<IArgumentOperation> getEnumeratorArguments = default, ImmutableArray<IArgumentOperation> moveNextArguments = default, ImmutableArray<IArgumentOperation> currentArguments = default, ImmutableArray<IArgumentOperation> disposeArguments = default) { ElementType = elementType; GetEnumeratorMethod = getEnumeratorMethod; CurrentProperty = currentProperty; MoveNextMethod = moveNextMethod; IsAsynchronous = isAsynchronous; KnownToImplementIDisposable = knownToImplementIDisposable; NeedsDispose = needsDispose; PatternDisposeMethod = patternDisposeMethod; CurrentConversion = currentConversion; ElementConversion = elementConversion; GetEnumeratorArguments = getEnumeratorArguments; MoveNextArguments = moveNextArguments; CurrentArguments = currentArguments; DisposeArguments = disposeArguments; } } }
-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/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryAttributeSuppressions), Shared] internal sealed class RemoveUnnecessaryAttributeSuppressionsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnnecessaryAttributeSuppressionsCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { // Register code fix with a defensive check if (root.FindNode(diagnostic.Location.SourceSpan) != null) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); } } } protected override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = editor.OriginalRoot.FindNode(diagnostic.Location.SourceSpan); editor.RemoveNode(node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_suppression, createChangedDocument, nameof(RemoveUnnecessaryAttributeSuppressionsCodeFixProvider)) { } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryAttributeSuppressions), Shared] internal sealed class RemoveUnnecessaryAttributeSuppressionsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnnecessaryAttributeSuppressionsCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { // Register code fix with a defensive check if (root.FindNode(diagnostic.Location.SourceSpan) != null) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); } } } protected override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = editor.OriginalRoot.FindNode(diagnostic.Location.SourceSpan); editor.RemoveNode(node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_suppression, createChangedDocument, nameof(RemoveUnnecessaryAttributeSuppressionsCodeFixProvider)) { } } } }
-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/Storage/SQLite/v2/SQLitePersistentStorage_ProjectIds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.SQLite.v2.Interop; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// Mapping from the workspace's ID for a project, to the ID we use in the DB for the project. /// Kept locally so we don't have to hit the DB for the common case of trying to determine the /// DB id for a project. /// </summary> private readonly ConcurrentDictionary<ProjectId, int> _projectIdToIdMap = new(); /// <summary> /// Given a project, and the name of a stream to read/write, gets the integral DB ID to /// use to find the data inside the ProjectData table. /// </summary> private bool TryGetProjectDataId( SqlConnection connection, ProjectKey project, string name, bool allowWrite, out long dataId) { dataId = 0; var projectId = TryGetProjectId(connection, project, allowWrite); var nameId = TryGetStringId(connection, name, allowWrite); if (projectId == null || nameId == null) { return false; } // Our data ID is just a 64bit int combining the two 32bit values of our projectId and nameId. dataId = CombineInt32ValuesToInt64(projectId.Value, nameId.Value); return true; } private int? TryGetProjectId(SqlConnection connection, ProjectKey project, bool allowWrite) { // First see if we've cached the ID for this value locally. If so, just return // what we already have. if (_projectIdToIdMap.TryGetValue(project.Id, out var existingId)) { return existingId; } var id = TryGetProjectIdFromDatabase(connection, project, allowWrite); if (id != null) { // Cache the value locally so we don't need to go back to the DB in the future. _projectIdToIdMap.TryAdd(project.Id, id.Value); } return id; } private int? TryGetProjectIdFromDatabase(SqlConnection connection, ProjectKey project, bool allowWrite) { // Key the project off both its path and name. That way we work properly // in host and test scenarios. var projectPathId = TryGetStringId(connection, project.FilePath, allowWrite); var projectNameId = TryGetStringId(connection, project.Name, allowWrite); if (projectPathId == null || projectNameId == null) return null; return TryGetStringId( connection, GetProjectIdString(projectPathId.Value, projectNameId.Value), allowWrite); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.SQLite.v2.Interop; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// Mapping from the workspace's ID for a project, to the ID we use in the DB for the project. /// Kept locally so we don't have to hit the DB for the common case of trying to determine the /// DB id for a project. /// </summary> private readonly ConcurrentDictionary<ProjectId, int> _projectIdToIdMap = new(); /// <summary> /// Given a project, and the name of a stream to read/write, gets the integral DB ID to /// use to find the data inside the ProjectData table. /// </summary> private bool TryGetProjectDataId( SqlConnection connection, ProjectKey project, string name, bool allowWrite, out long dataId) { dataId = 0; var projectId = TryGetProjectId(connection, project, allowWrite); var nameId = TryGetStringId(connection, name, allowWrite); if (projectId == null || nameId == null) { return false; } // Our data ID is just a 64bit int combining the two 32bit values of our projectId and nameId. dataId = CombineInt32ValuesToInt64(projectId.Value, nameId.Value); return true; } private int? TryGetProjectId(SqlConnection connection, ProjectKey project, bool allowWrite) { // First see if we've cached the ID for this value locally. If so, just return // what we already have. if (_projectIdToIdMap.TryGetValue(project.Id, out var existingId)) { return existingId; } var id = TryGetProjectIdFromDatabase(connection, project, allowWrite); if (id != null) { // Cache the value locally so we don't need to go back to the DB in the future. _projectIdToIdMap.TryAdd(project.Id, id.Value); } return id; } private int? TryGetProjectIdFromDatabase(SqlConnection connection, ProjectKey project, bool allowWrite) { // Key the project off both its path and name. That way we work properly // in host and test scenarios. var projectPathId = TryGetStringId(connection, project.FilePath, allowWrite); var projectNameId = TryGetStringId(connection, project.Name, allowWrite); if (projectPathId == null || projectNameId == null) return null; return TryGetStringId( connection, GetProjectIdString(projectPathId.Value, projectNameId.Value), allowWrite); } } }
-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/Syntax/SyntaxTokenList.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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a read-only list of <see cref="SyntaxToken"/>. /// </summary> [StructLayout(LayoutKind.Auto)] public readonly partial struct SyntaxTokenList : IEquatable<SyntaxTokenList>, IReadOnlyList<SyntaxToken> { private readonly SyntaxNode? _parent; private readonly int _index; internal SyntaxTokenList(SyntaxNode? parent, GreenNode? tokenOrList, int position, int index) { Debug.Assert(tokenOrList != null || (position == 0 && index == 0 && parent == null)); Debug.Assert(position >= 0); Debug.Assert(tokenOrList == null || (tokenOrList.IsToken) || (tokenOrList.IsList)); _parent = parent; Node = tokenOrList; Position = position; _index = index; } public SyntaxTokenList(SyntaxToken token) { _parent = token.Parent; Node = token.Node; Position = token.Position; _index = 0; } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens">An array of tokens.</param> public SyntaxTokenList(params SyntaxToken[] tokens) : this(null, CreateNode(tokens), 0, 0) { } /// <summary> /// Creates a list of tokens. /// </summary> public SyntaxTokenList(IEnumerable<SyntaxToken> tokens) : this(null, CreateNode(tokens), 0, 0) { } private static GreenNode? CreateNode(SyntaxToken[] tokens) { if (tokens == null) { return null; } // TODO: we could remove the unnecessary builder allocations here and go directly // from the array to the List nodes. var builder = new SyntaxTokenListBuilder(tokens.Length); for (int i = 0; i < tokens.Length; i++) { var node = tokens[i].Node; Debug.Assert(node is object); builder.Add(node); } return builder.ToList().Node; } private static GreenNode? CreateNode(IEnumerable<SyntaxToken> tokens) { if (tokens == null) { return null; } var builder = SyntaxTokenListBuilder.Create(); foreach (var token in tokens) { Debug.Assert(token.Node is object); builder.Add(token.Node); } return builder.ToList().Node; } internal GreenNode? Node { get; } internal int Position { get; } /// <summary> /// Returns the number of tokens in the list. /// </summary> public int Count => Node == null ? 0 : (Node.IsList ? Node.SlotCount : 1); /// <summary> /// Gets the token at the specified index. /// </summary> /// <param name="index">The zero-based index of the token to get.</param> /// <returns>The token at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than 0.-or-<paramref name="index" /> is equal to or greater than <see cref="Count" />. </exception> public SyntaxToken this[int index] { get { if (Node != null) { if (Node.IsList) { if (unchecked((uint)index < (uint)Node.SlotCount)) { return new SyntaxToken(_parent, Node.GetSlot(index), Position + Node.GetSlotOffset(index), _index + index); } } else if (index == 0) { return new SyntaxToken(_parent, Node, Position, _index); } } throw new ArgumentOutOfRangeException(nameof(index)); } } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (Node == null) { return default(TextSpan); } return new TextSpan(this.Position, Node.FullWidth); } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (Node == null) { return default(TextSpan); } return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); } } /// <summary> /// Returns the string representation of the tokens in this list, not including /// the first token's leading trivia and the last token's trailing trivia. /// </summary> /// <returns> /// The string representation of the tokens in this list, not including /// the first token's leading trivia and the last token's trailing trivia. /// </returns> public override string ToString() { return Node != null ? Node.ToString() : string.Empty; } /// <summary> /// Returns the full string representation of the tokens in this list including /// the first token's leading trivia and the last token's trailing trivia. /// </summary> /// <returns> /// The full string representation of the tokens in this list including /// the first token's leading trivia and the last token's trailing trivia. /// </returns> public string ToFullString() { return Node != null ? Node.ToFullString() : string.Empty; } /// <summary> /// Returns the first token in the list. /// </summary> /// <returns>The first token in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxToken First() { if (Any()) { return this[0]; } throw new InvalidOperationException(); } /// <summary> /// Returns the last token in the list. /// </summary> /// <returns> The last token in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxToken Last() { if (Any()) { return this[this.Count - 1]; } throw new InvalidOperationException(); } /// <summary> /// Tests whether the list is non-empty. /// </summary> /// <returns>True if the list contains any tokens.</returns> public bool Any() { return Node != null; } /// <summary> /// Returns a list which contains all elements of <see cref="SyntaxTokenList"/> in reversed order. /// </summary> /// <returns><see cref="Reversed"/> which contains all elements of <see cref="SyntaxTokenList"/> in reversed order</returns> public Reversed Reverse() { return new Reversed(this); } internal void CopyTo(int offset, GreenNode?[] array, int arrayOffset, int count) { Debug.Assert(this.Count >= offset + count); for (int i = 0; i < count; i++) { array[arrayOffset + i] = GetGreenNodeAt(offset + i); } } /// <summary> /// get the green node at the given slot /// </summary> private GreenNode? GetGreenNodeAt(int i) { Debug.Assert(Node is object); return GetGreenNodeAt(Node, i); } /// <summary> /// get the green node at the given slot /// </summary> private static GreenNode? GetGreenNodeAt(GreenNode node, int i) { Debug.Assert(node.IsList || (i == 0 && !node.IsList)); return node.IsList ? node.GetSlot(i) : node; } public int IndexOf(SyntaxToken tokenInList) { for (int i = 0, n = this.Count; i < n; i++) { var token = this[i]; if (token == tokenInList) { return i; } } return -1; } internal int IndexOf(int rawKind) { for (int i = 0, n = this.Count; i < n; i++) { if (this[i].RawKind == rawKind) { return i; } } return -1; } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token added to the end. /// </summary> /// <param name="token">The token to add.</param> public SyntaxTokenList Add(SyntaxToken token) { return Insert(this.Count, token); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified tokens added to the end. /// </summary> /// <param name="tokens">The tokens to add.</param> public SyntaxTokenList AddRange(IEnumerable<SyntaxToken> tokens) { return InsertRange(this.Count, tokens); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token insert at the index. /// </summary> /// <param name="index">The index to insert the new token.</param> /// <param name="token">The token to insert.</param> public SyntaxTokenList Insert(int index, SyntaxToken token) { if (token == default(SyntaxToken)) { throw new ArgumentOutOfRangeException(nameof(token)); } return InsertRange(index, new[] { token }); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified tokens insert at the index. /// </summary> /// <param name="index">The index to insert the new tokens.</param> /// <param name="tokens">The tokens to insert.</param> public SyntaxTokenList InsertRange(int index, IEnumerable<SyntaxToken> tokens) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } var items = tokens.ToList(); if (items.Count == 0) { return this; } var list = this.ToList(); list.InsertRange(index, tokens); if (list.Count == 0) { return this; } return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the token at the specified index removed. /// </summary> /// <param name="index">The index of the token to remove.</param> public SyntaxTokenList RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var list = this.ToList(); list.RemoveAt(index); return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token removed. /// </summary> /// <param name="tokenInList">The token to remove.</param> public SyntaxTokenList Remove(SyntaxToken tokenInList) { var index = this.IndexOf(tokenInList); if (index >= 0 && index <= this.Count) { return RemoveAt(index); } return this; } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token replaced with a new token. /// </summary> /// <param name="tokenInList">The token to replace.</param> /// <param name="newToken">The new token.</param> public SyntaxTokenList Replace(SyntaxToken tokenInList, SyntaxToken newToken) { if (newToken == default(SyntaxToken)) { throw new ArgumentOutOfRangeException(nameof(newToken)); } return ReplaceRange(tokenInList, new[] { newToken }); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token replaced with new tokens. /// </summary> /// <param name="tokenInList">The token to replace.</param> /// <param name="newTokens">The new tokens.</param> public SyntaxTokenList ReplaceRange(SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens) { var index = this.IndexOf(tokenInList); if (index >= 0 && index <= this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newTokens); return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } throw new ArgumentOutOfRangeException(nameof(tokenInList)); } // for debugging private SyntaxToken[] Nodes => this.ToArray(); /// <summary> /// Returns an enumerator for the tokens in the <see cref="SyntaxTokenList"/> /// </summary> public Enumerator GetEnumerator() { return new Enumerator(in this); } IEnumerator<SyntaxToken> IEnumerable<SyntaxToken>.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxToken>(); } return new EnumeratorImpl(in this); } IEnumerator IEnumerable.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxToken>(); } return new EnumeratorImpl(in this); } /// <summary> /// Compares <paramref name="left"/> and <paramref name="right"/> for equality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>True if the two <see cref="SyntaxTokenList"/>s are equal.</returns> public static bool operator ==(SyntaxTokenList left, SyntaxTokenList right) { return left.Equals(right); } /// <summary> /// Compares <paramref name="left"/> and <paramref name="right"/> for inequality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>True if the two <see cref="SyntaxTokenList"/>s are not equal.</returns> public static bool operator !=(SyntaxTokenList left, SyntaxTokenList right) { return !left.Equals(right); } public bool Equals(SyntaxTokenList other) { return Node == other.Node && _parent == other._parent && _index == other._index; } /// <summary> /// Compares this <see cref=" SyntaxTokenList"/> with the <paramref name="obj"/> for equality. /// </summary> /// <returns>True if the two objects are equal.</returns> public override bool Equals(object? obj) { return obj is SyntaxTokenList list && Equals(list); } /// <summary> /// Serves as a hash function for the <see cref="SyntaxTokenList"/> /// </summary> public override int GetHashCode() { // Not call GHC on parent as it's expensive return Hash.Combine(Node, _index); } /// <summary> /// Create a new Token List /// </summary> /// <param name="token">Element of the return Token List</param> public static SyntaxTokenList Create(SyntaxToken token) { return new SyntaxTokenList(token); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a read-only list of <see cref="SyntaxToken"/>. /// </summary> [StructLayout(LayoutKind.Auto)] public readonly partial struct SyntaxTokenList : IEquatable<SyntaxTokenList>, IReadOnlyList<SyntaxToken> { private readonly SyntaxNode? _parent; private readonly int _index; internal SyntaxTokenList(SyntaxNode? parent, GreenNode? tokenOrList, int position, int index) { Debug.Assert(tokenOrList != null || (position == 0 && index == 0 && parent == null)); Debug.Assert(position >= 0); Debug.Assert(tokenOrList == null || (tokenOrList.IsToken) || (tokenOrList.IsList)); _parent = parent; Node = tokenOrList; Position = position; _index = index; } public SyntaxTokenList(SyntaxToken token) { _parent = token.Parent; Node = token.Node; Position = token.Position; _index = 0; } /// <summary> /// Creates a list of tokens. /// </summary> /// <param name="tokens">An array of tokens.</param> public SyntaxTokenList(params SyntaxToken[] tokens) : this(null, CreateNode(tokens), 0, 0) { } /// <summary> /// Creates a list of tokens. /// </summary> public SyntaxTokenList(IEnumerable<SyntaxToken> tokens) : this(null, CreateNode(tokens), 0, 0) { } private static GreenNode? CreateNode(SyntaxToken[] tokens) { if (tokens == null) { return null; } // TODO: we could remove the unnecessary builder allocations here and go directly // from the array to the List nodes. var builder = new SyntaxTokenListBuilder(tokens.Length); for (int i = 0; i < tokens.Length; i++) { var node = tokens[i].Node; Debug.Assert(node is object); builder.Add(node); } return builder.ToList().Node; } private static GreenNode? CreateNode(IEnumerable<SyntaxToken> tokens) { if (tokens == null) { return null; } var builder = SyntaxTokenListBuilder.Create(); foreach (var token in tokens) { Debug.Assert(token.Node is object); builder.Add(token.Node); } return builder.ToList().Node; } internal GreenNode? Node { get; } internal int Position { get; } /// <summary> /// Returns the number of tokens in the list. /// </summary> public int Count => Node == null ? 0 : (Node.IsList ? Node.SlotCount : 1); /// <summary> /// Gets the token at the specified index. /// </summary> /// <param name="index">The zero-based index of the token to get.</param> /// <returns>The token at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than 0.-or-<paramref name="index" /> is equal to or greater than <see cref="Count" />. </exception> public SyntaxToken this[int index] { get { if (Node != null) { if (Node.IsList) { if (unchecked((uint)index < (uint)Node.SlotCount)) { return new SyntaxToken(_parent, Node.GetSlot(index), Position + Node.GetSlotOffset(index), _index + index); } } else if (index == 0) { return new SyntaxToken(_parent, Node, Position, _index); } } throw new ArgumentOutOfRangeException(nameof(index)); } } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (Node == null) { return default(TextSpan); } return new TextSpan(this.Position, Node.FullWidth); } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (Node == null) { return default(TextSpan); } return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); } } /// <summary> /// Returns the string representation of the tokens in this list, not including /// the first token's leading trivia and the last token's trailing trivia. /// </summary> /// <returns> /// The string representation of the tokens in this list, not including /// the first token's leading trivia and the last token's trailing trivia. /// </returns> public override string ToString() { return Node != null ? Node.ToString() : string.Empty; } /// <summary> /// Returns the full string representation of the tokens in this list including /// the first token's leading trivia and the last token's trailing trivia. /// </summary> /// <returns> /// The full string representation of the tokens in this list including /// the first token's leading trivia and the last token's trailing trivia. /// </returns> public string ToFullString() { return Node != null ? Node.ToFullString() : string.Empty; } /// <summary> /// Returns the first token in the list. /// </summary> /// <returns>The first token in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxToken First() { if (Any()) { return this[0]; } throw new InvalidOperationException(); } /// <summary> /// Returns the last token in the list. /// </summary> /// <returns> The last token in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxToken Last() { if (Any()) { return this[this.Count - 1]; } throw new InvalidOperationException(); } /// <summary> /// Tests whether the list is non-empty. /// </summary> /// <returns>True if the list contains any tokens.</returns> public bool Any() { return Node != null; } /// <summary> /// Returns a list which contains all elements of <see cref="SyntaxTokenList"/> in reversed order. /// </summary> /// <returns><see cref="Reversed"/> which contains all elements of <see cref="SyntaxTokenList"/> in reversed order</returns> public Reversed Reverse() { return new Reversed(this); } internal void CopyTo(int offset, GreenNode?[] array, int arrayOffset, int count) { Debug.Assert(this.Count >= offset + count); for (int i = 0; i < count; i++) { array[arrayOffset + i] = GetGreenNodeAt(offset + i); } } /// <summary> /// get the green node at the given slot /// </summary> private GreenNode? GetGreenNodeAt(int i) { Debug.Assert(Node is object); return GetGreenNodeAt(Node, i); } /// <summary> /// get the green node at the given slot /// </summary> private static GreenNode? GetGreenNodeAt(GreenNode node, int i) { Debug.Assert(node.IsList || (i == 0 && !node.IsList)); return node.IsList ? node.GetSlot(i) : node; } public int IndexOf(SyntaxToken tokenInList) { for (int i = 0, n = this.Count; i < n; i++) { var token = this[i]; if (token == tokenInList) { return i; } } return -1; } internal int IndexOf(int rawKind) { for (int i = 0, n = this.Count; i < n; i++) { if (this[i].RawKind == rawKind) { return i; } } return -1; } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token added to the end. /// </summary> /// <param name="token">The token to add.</param> public SyntaxTokenList Add(SyntaxToken token) { return Insert(this.Count, token); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified tokens added to the end. /// </summary> /// <param name="tokens">The tokens to add.</param> public SyntaxTokenList AddRange(IEnumerable<SyntaxToken> tokens) { return InsertRange(this.Count, tokens); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token insert at the index. /// </summary> /// <param name="index">The index to insert the new token.</param> /// <param name="token">The token to insert.</param> public SyntaxTokenList Insert(int index, SyntaxToken token) { if (token == default(SyntaxToken)) { throw new ArgumentOutOfRangeException(nameof(token)); } return InsertRange(index, new[] { token }); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified tokens insert at the index. /// </summary> /// <param name="index">The index to insert the new tokens.</param> /// <param name="tokens">The tokens to insert.</param> public SyntaxTokenList InsertRange(int index, IEnumerable<SyntaxToken> tokens) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } var items = tokens.ToList(); if (items.Count == 0) { return this; } var list = this.ToList(); list.InsertRange(index, tokens); if (list.Count == 0) { return this; } return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the token at the specified index removed. /// </summary> /// <param name="index">The index of the token to remove.</param> public SyntaxTokenList RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var list = this.ToList(); list.RemoveAt(index); return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token removed. /// </summary> /// <param name="tokenInList">The token to remove.</param> public SyntaxTokenList Remove(SyntaxToken tokenInList) { var index = this.IndexOf(tokenInList); if (index >= 0 && index <= this.Count) { return RemoveAt(index); } return this; } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token replaced with a new token. /// </summary> /// <param name="tokenInList">The token to replace.</param> /// <param name="newToken">The new token.</param> public SyntaxTokenList Replace(SyntaxToken tokenInList, SyntaxToken newToken) { if (newToken == default(SyntaxToken)) { throw new ArgumentOutOfRangeException(nameof(newToken)); } return ReplaceRange(tokenInList, new[] { newToken }); } /// <summary> /// Creates a new <see cref="SyntaxTokenList"/> with the specified token replaced with new tokens. /// </summary> /// <param name="tokenInList">The token to replace.</param> /// <param name="newTokens">The new tokens.</param> public SyntaxTokenList ReplaceRange(SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens) { var index = this.IndexOf(tokenInList); if (index >= 0 && index <= this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newTokens); return new SyntaxTokenList(null, GreenNode.CreateList(list, static n => n.RequiredNode), 0, 0); } throw new ArgumentOutOfRangeException(nameof(tokenInList)); } // for debugging private SyntaxToken[] Nodes => this.ToArray(); /// <summary> /// Returns an enumerator for the tokens in the <see cref="SyntaxTokenList"/> /// </summary> public Enumerator GetEnumerator() { return new Enumerator(in this); } IEnumerator<SyntaxToken> IEnumerable<SyntaxToken>.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxToken>(); } return new EnumeratorImpl(in this); } IEnumerator IEnumerable.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxToken>(); } return new EnumeratorImpl(in this); } /// <summary> /// Compares <paramref name="left"/> and <paramref name="right"/> for equality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>True if the two <see cref="SyntaxTokenList"/>s are equal.</returns> public static bool operator ==(SyntaxTokenList left, SyntaxTokenList right) { return left.Equals(right); } /// <summary> /// Compares <paramref name="left"/> and <paramref name="right"/> for inequality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>True if the two <see cref="SyntaxTokenList"/>s are not equal.</returns> public static bool operator !=(SyntaxTokenList left, SyntaxTokenList right) { return !left.Equals(right); } public bool Equals(SyntaxTokenList other) { return Node == other.Node && _parent == other._parent && _index == other._index; } /// <summary> /// Compares this <see cref=" SyntaxTokenList"/> with the <paramref name="obj"/> for equality. /// </summary> /// <returns>True if the two objects are equal.</returns> public override bool Equals(object? obj) { return obj is SyntaxTokenList list && Equals(list); } /// <summary> /// Serves as a hash function for the <see cref="SyntaxTokenList"/> /// </summary> public override int GetHashCode() { // Not call GHC on parent as it's expensive return Hash.Combine(Node, _index); } /// <summary> /// Create a new Token List /// </summary> /// <param name="token">Element of the return Token List</param> public static SyntaxTokenList Create(SyntaxToken token) { return new SyntaxTokenList(token); } } }
-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/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.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.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeType.Kind() == SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeType.Kind() == SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
-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/Formatting/Context/SuppressWrappingData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// data that will be used in an interval tree related to suppressing wrapping operations. /// </summary> internal class SuppressWrappingData { public SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) { this.TextSpan = textSpan; this.IgnoreElastic = ignoreElastic; } public TextSpan TextSpan { get; } public bool IgnoreElastic { get; } #if DEBUG public override string ToString() => $"Suppress wrapping on '{TextSpan}' with IgnoreElastic={IgnoreElastic}"; #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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// data that will be used in an interval tree related to suppressing wrapping operations. /// </summary> internal class SuppressWrappingData { public SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) { this.TextSpan = textSpan; this.IgnoreElastic = ignoreElastic; } public TextSpan TextSpan { get; } public bool IgnoreElastic { get; } #if DEBUG public override string ToString() => $"Suppress wrapping on '{TextSpan}' with IgnoreElastic={IgnoreElastic}"; #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/Compilers/Test/Core/PDB/DeterministicBuildCompilationTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Roslyn.Test.Utilities.PDB { internal static partial class DeterministicBuildCompilationTestHelpers { public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null) { bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default); var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString(); pdbOptions.TryGetValue(pdbName, out var actualValueString); Assert.Equal(expectedValueString, actualValueString); } public static IEnumerable<EmitOptions> GetEmitOptions() { var emitOptions = new EmitOptions( debugInformationFormat: DebugInformationFormat.Embedded, pdbChecksumAlgorithm: HashAlgorithmName.SHA256, defaultSourceFileEncoding: Encoding.UTF32); yield return emitOptions; yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII); yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode); yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII); } internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions) { pdbOptions.VerifyPdbOption("version", 2); pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName); pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName); int portabilityPolicy = 0; if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy); var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]); pdbOptions.VerifyPdbOption( "optimization", (compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode), toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode)); Assert.Equal(compilation.Language, pdbOptions["language"]); } public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader) { var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework); var count = 0; while (metadataReferenceReader.RemainingBytes > 0) { var info = ParseMetadataReferenceInfo(ref metadataReferenceReader); if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid)) { count++; continue; } var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid); testReference.MetadataReferenceInfo.AssertEqual(info); count++; } Assert.Equal(references.Length + frameworkReferences.Length, count); } public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader) { return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == infoGuid select pdbReader.GetBlobReader(cdi.Value)).Single(); } public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader) { // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // EmbedInteropTypes/MetadataImageKind (byte) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var name = blobReader.ReadUTF8(terminatorIndex); // Skip the null terminator blobReader.ReadByte(); terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var externAliases = blobReader.ReadUTF8(terminatorIndex); blobReader.ReadByte(); var embedInteropTypesAndKind = blobReader.ReadByte(); var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10; var kind = (embedInteropTypesAndKind & 0b1) == 0b1 ? MetadataImageKind.Assembly : MetadataImageKind.Module; var timestamp = blobReader.ReadInt32(); var imageSize = blobReader.ReadInt32(); var mvid = blobReader.ReadGuid(); return new MetadataReferenceInfo( timestamp, imageSize, name, mvid, string.IsNullOrEmpty(externAliases) ? ImmutableArray<string>.Empty : externAliases.Split(',').ToImmutableArray(), kind, embedInteropTypes); } public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader) { // Compiler flag bytes are UTF-8 null-terminated key-value pairs string key = null; Dictionary<string, string> kvp = new Dictionary<string, string>(); for (; ; ) { var nullIndex = blobReader.IndexOf(0); if (nullIndex == -1) { break; } var value = blobReader.ReadUTF8(nullIndex); // Skip the null terminator blobReader.ReadByte(); if (key is null) { key = value; } else { kvp[key] = value; key = null; } } Assert.Null(key); Assert.Equal(0, blobReader.RemainingBytes); return kvp.ToImmutableDictionary(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Roslyn.Test.Utilities.PDB { internal static partial class DeterministicBuildCompilationTestHelpers { public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null) { bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default); var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString(); pdbOptions.TryGetValue(pdbName, out var actualValueString); Assert.Equal(expectedValueString, actualValueString); } public static IEnumerable<EmitOptions> GetEmitOptions() { var emitOptions = new EmitOptions( debugInformationFormat: DebugInformationFormat.Embedded, pdbChecksumAlgorithm: HashAlgorithmName.SHA256, defaultSourceFileEncoding: Encoding.UTF32); yield return emitOptions; yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII); yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode); yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII); } internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions) { pdbOptions.VerifyPdbOption("version", 2); pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName); pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName); int portabilityPolicy = 0; if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy); var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]); pdbOptions.VerifyPdbOption( "optimization", (compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode), toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode)); Assert.Equal(compilation.Language, pdbOptions["language"]); } public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader) { var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework); var count = 0; while (metadataReferenceReader.RemainingBytes > 0) { var info = ParseMetadataReferenceInfo(ref metadataReferenceReader); if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid)) { count++; continue; } var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid); testReference.MetadataReferenceInfo.AssertEqual(info); count++; } Assert.Equal(references.Length + frameworkReferences.Length, count); } public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader) { return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == infoGuid select pdbReader.GetBlobReader(cdi.Value)).Single(); } public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader) { // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // EmbedInteropTypes/MetadataImageKind (byte) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var name = blobReader.ReadUTF8(terminatorIndex); // Skip the null terminator blobReader.ReadByte(); terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var externAliases = blobReader.ReadUTF8(terminatorIndex); blobReader.ReadByte(); var embedInteropTypesAndKind = blobReader.ReadByte(); var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10; var kind = (embedInteropTypesAndKind & 0b1) == 0b1 ? MetadataImageKind.Assembly : MetadataImageKind.Module; var timestamp = blobReader.ReadInt32(); var imageSize = blobReader.ReadInt32(); var mvid = blobReader.ReadGuid(); return new MetadataReferenceInfo( timestamp, imageSize, name, mvid, string.IsNullOrEmpty(externAliases) ? ImmutableArray<string>.Empty : externAliases.Split(',').ToImmutableArray(), kind, embedInteropTypes); } public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader) { // Compiler flag bytes are UTF-8 null-terminated key-value pairs string key = null; Dictionary<string, string> kvp = new Dictionary<string, string>(); for (; ; ) { var nullIndex = blobReader.IndexOf(0); if (nullIndex == -1) { break; } var value = blobReader.ReadUTF8(nullIndex); // Skip the null terminator blobReader.ReadByte(); if (key is null) { key = value; } else { kvp[key] = value; key = null; } } Assert.Null(key); Assert.Equal(0, blobReader.RemainingBytes); return kvp.ToImmutableDictionary(); } } }
-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/LanguageServer/Protocol/Handler/Completion/CompletionHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
-1
dotnet/roslyn
55,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.
./docs/wiki/images/fig5.png
PNG  IHDR댌sRGBgAMA a pHYsodIDATx^]=H忙;,` Ksp!Yȓ8Zcό'g hc܋xWYꎇ+222| 2ɏ*o oG'q}q|ax]p|9moU2#TEEF5%5sZm,? 4}bꟊ(otGTunZv{QbYuo*"koGM&9VG#Dpͯ?篿W ,M`rK'o)|tο 4`g"ӻ C)7#ĩs^Y{84DW(@,Lh}0tZ˴r]?E^-˫. H,fuK$!i)|c ̎qGw(GpG L-eg|K߀Kܛ!M ƈàC&k(|EeQ@Ʃ} :Af74Ѥh([e6^N@z&{pn -_2+1w\L7(_ãAkpQ]8b0%2K0 z}!\%.SuQڛhZ\.T.ыX`( \,u./ѭa1*^A2`"(KU6v d*W!A~Q,r0J]0P9o{M-n(v(3<CeG7MnqATLCKk(ޗ Vxbd7rZywM8So}zNƟn ߽0d&Z6ww0LMYH+̀a+[Y|cratS'ZCmv7{;d&^Tr @EFZt8ۑ~Ŷ2Ҭ#+VW5ZYF* :qS XB0ڌ 僘M\pƒc$iFQ-q4Pew~䃷2Mܟ⋞ B%m/m+®iۺ;N!R>=:!Ȫ;}2}i GkVWe͉++Y ibQ\U:8+VJjd~mjyHAg.YDKHe]ebL{<O=$ZɃIă)I#Vt5[M0"T/ [uJS3NQ[ ˳љNd=0jeGD+v?58Vߝt+⇪xQ 񗵭59Uh%K/z@9<ŤУgVN +ɌuFp jI26v ټ{G8W!ٌ֢}z+#K^Uȝ?,Rg[-c&lMSlsp6sb|gR^*$Ivct fO]8p oX&#ujE%uJ|t`ٶ6fpʝ(V=YS 6. fN,bJMe`Gb9'dT_L*hW|?kاk]kw+!b"Cr9ޘ~ͅEl>:@ ̆ql^ ͜p6sb9D]\|?K4`_a?ֱo\l* Z/bR6{},J.((<E r<ˤR^pi)𽩔TFF<]Wbzؼ80$-pZK4|,89l"6ѓ0Y>'tIޡ(,`)hڻrl-b e̮j֎X~(&:b1']yjEB`_?uɄ9{Xc֐36QCSxa thapR!,$YVW3;M9&lnKY3XYl1M5:haս!aЃYJ /jit%;(T9M89l26OL+l??eUpG R/3t}Č=U-N ĺX&ec3!^h ) nR =:(.x?N %]uT^lH $[AM2891r ^IY$+xV̙'OG<W9$2[*߼yS<8NeTfK|o-X˩DoU@UJޡ| R4s*c2|+zuT{e5bT"MPKw_92b9G⚞|:N%>*꡾i,8QIXc%l4X8TfS >owƷh׿ѶM<FeĤ2#SҲߢo,2/oCdP5|@Y~@!hr@~Cag(/r@,x ڼ$j>x 8JitcY3:X2$K}|Ԙ%LtG{Y$o|z Sy\F2iø*2"TfS Ne68Tf"*߽pi{5=>8.p ϖs0T<eg;9_ђv,^G3P:P Bs!4.uڽ)5cN"Уq KRP)WC'P,3TZ*F2dMaص6A6+./b<BSILw ,79n-ChKJȚ2a~e */Ne68TfS Ne68pJ\}݆u\q(K9({ c1!iOFjkXӕާYc0/}](Q#:n?"Q(E֫="wˌuP8$J Ms*RDpY7.;˺e>&}2&LʤuK2 1Ņ waŢX 2}R zb cc  ka⾖ĢL|-|fLoɟ [ѰeB#</'{NxDG%0nu*dDԭV8 )fS<HχFBPxQ(p*2lp*0!vJJh|4& -ىF~p2Z(W(*#_cTT:J|Y=EPObOuu:*ㇽhB5r8xfR+85bHƀ%7> 1ūq2W.:\#t25pS͒9 )R).tS"hs[ׁԌ\8ApK n|*p9@"_^۴zZec-RHe7tvf$|r**THc%lE\{쁩-BXQyY"5eOǂS Ne68Tf*^%lXAeUM0<N1%g=j* @u/!TrYS82[q ÑIt^Ҫ߆1{QfsOfr`@%-$eghȍ9 $2MDS,“r[ @I/d<s`0W)w;Ӥ'>, X@clp*2Nr7;1) wѹ0`0&r5 ܩ&oqD<=<SokNB<"<.=1y\zb˻o?1Xǥ'&KO[L2@I4ū$g3Q5h6 Ĵ,.%|$,OƝ~,q3UqY쀨 OR7_l2.&r-$$,Nǥ'D@xi_\0 D\B5Nfp<røǥctlyR"/S7?ukjڬ_սM#/Z~-qI2՛*\̸˰.V/1[YGy`0'6uxSQuS*xF#. *q*bTdYΗuMyoeDu.D{JքN @'EdMRpe2 &VRC3х@z@r'ڐGU'[M#JW*!-F1)EhQ#JwȲ-#O\:t8-ұEx\:Kq"<.[ǥc׺|]_m1,Gzrg `_%UpqK ʉ@^ejVȟうJ4`FojH ũe-H7`ve.]^^gV+6 unaGmgK@ϝQ6( Mjțv!xr=r`F1beQ^!4vb %h'EȲw \@\H$t⠧:RpȥmxZ%dXц?ь2 ťf8Ne'6},x\:Kq"<.[ǥctlym=adA5=:m]y!N[J9ME4{6x\7Uy޴h:q]#c\Z(ضb, ^seb+P xUY5}ߵͮԹTqY^T_iTT@,RnD|Tv(*f8]E)}èؕ)Uf3BȧEAܯ58[\^řLxo̸ӏ&N `pO+ZfLfC%<D/_)r$J6 0i5v!։'B[Z c\?dg, lݖ*Ս4UR[Ηu-~0"X_Q`&-PkaP/~w@] DD6dZ͉vJ?1iꨘskFkdcĥ 3X`qx\:Kq"<.[ǥctl-"g\&ע:̽͐?:⤱Z,̉S~+dٛ/e-z3 wN4%4⺰& VT{Nrc9cvf 4F_fNOgԲx薵 ڪ.ng`,kg6l&׮ }8{\vpў3+B$iNȞ&Eʴ֨*e!XGHHoT=h,iPBI}W3K Ul!:?@qٹPC&k%-GނY8#pWL^Ta&jxUBD=3  C*ڭb,q-rƥL= ʗˍAKq"<.[ǥc~xNtlg8_/Û2UfK%m f`9Mf9e{p x04=׸,<υ#`8{\~|Q|fT('(~h_Sѹ% Nuӑ*S+ 2(\:W"I\E(Ys蒖Doz=.ʴ,^0^'ҖQۯ1Dl4,P⬫VOI)=\1"ֲ Lb궢m ݣD_u J{BJ =4T!+r'+Br'+1V%.ϒ}HhXZiұEdK#+<.[ǥctlKғNڄZ_{zǥX%IENDB`
PNG  IHDR댌sRGBgAMA a pHYsodIDATx^]=H忙;,` Ksp!Yȓ8Zcό'g hc܋xWYꎇ+222| 2ɏ*o oG'q}q|ax]p|9moU2#TEEF5%5sZm,? 4}bꟊ(otGTunZv{QbYuo*"koGM&9VG#Dpͯ?篿W ,M`rK'o)|tο 4`g"ӻ C)7#ĩs^Y{84DW(@,Lh}0tZ˴r]?E^-˫. H,fuK$!i)|c ̎qGw(GpG L-eg|K߀Kܛ!M ƈàC&k(|EeQ@Ʃ} :Af74Ѥh([e6^N@z&{pn -_2+1w\L7(_ãAkpQ]8b0%2K0 z}!\%.SuQڛhZ\.T.ыX`( \,u./ѭa1*^A2`"(KU6v d*W!A~Q,r0J]0P9o{M-n(v(3<CeG7MnqATLCKk(ޗ Vxbd7rZywM8So}zNƟn ߽0d&Z6ww0LMYH+̀a+[Y|cratS'ZCmv7{;d&^Tr @EFZt8ۑ~Ŷ2Ҭ#+VW5ZYF* :qS XB0ڌ 僘M\pƒc$iFQ-q4Pew~䃷2Mܟ⋞ B%m/m+®iۺ;N!R>=:!Ȫ;}2}i GkVWe͉++Y ibQ\U:8+VJjd~mjyHAg.YDKHe]ebL{<O=$ZɃIă)I#Vt5[M0"T/ [uJS3NQ[ ˳љNd=0jeGD+v?58Vߝt+⇪xQ 񗵭59Uh%K/z@9<ŤУgVN +ɌuFp jI26v ټ{G8W!ٌ֢}z+#K^Uȝ?,Rg[-c&lMSlsp6sb|gR^*$Ivct fO]8p oX&#ujE%uJ|t`ٶ6fpʝ(V=YS 6. fN,bJMe`Gb9'dT_L*hW|?kاk]kw+!b"Cr9ޘ~ͅEl>:@ ̆ql^ ͜p6sb9D]\|?K4`_a?ֱo\l* Z/bR6{},J.((<E r<ˤR^pi)𽩔TFF<]Wbzؼ80$-pZK4|,89l"6ѓ0Y>'tIޡ(,`)hڻrl-b e̮j֎X~(&:b1']yjEB`_?uɄ9{Xc֐36QCSxa thapR!,$YVW3;M9&lnKY3XYl1M5:haս!aЃYJ /jit%;(T9M89l26OL+l??eUpG R/3t}Č=U-N ĺX&ec3!^h ) nR =:(.x?N %]uT^lH $[AM2891r ^IY$+xV̙'OG<W9$2[*߼yS<8NeTfK|o-X˩DoU@UJޡ| R4s*c2|+zuT{e5bT"MPKw_92b9G⚞|:N%>*꡾i,8QIXc%l4X8TfS >owƷh׿ѶM<FeĤ2#SҲߢo,2/oCdP5|@Y~@!hr@~Cag(/r@,x ڼ$j>x 8JitcY3:X2$K}|Ԙ%LtG{Y$o|z Sy\F2iø*2"TfS Ne68Tf"*߽pi{5=>8.p ϖs0T<eg;9_ђv,^G3P:P Bs!4.uڽ)5cN"Уq KRP)WC'P,3TZ*F2dMaص6A6+./b<BSILw ,79n-ChKJȚ2a~e */Ne68TfS Ne68pJ\}݆u\q(K9({ c1!iOFjkXӕާYc0/}](Q#:n?"Q(E֫="wˌuP8$J Ms*RDpY7.;˺e>&}2&LʤuK2 1Ņ waŢX 2}R zb cc  ka⾖ĢL|-|fLoɟ [ѰeB#</'{NxDG%0nu*dDԭV8 )fS<HχFBPxQ(p*2lp*0!vJJh|4& -ىF~p2Z(W(*#_cTT:J|Y=EPObOuu:*ㇽhB5r8xfR+85bHƀ%7> 1ūq2W.:\#t25pS͒9 )R).tS"hs[ׁԌ\8ApK n|*p9@"_^۴zZec-RHe7tvf$|r**THc%lE\{쁩-BXQyY"5eOǂS Ne68Tf*^%lXAeUM0<N1%g=j* @u/!TrYS82[q ÑIt^Ҫ߆1{QfsOfr`@%-$eghȍ9 $2MDS,“r[ @I/d<s`0W)w;Ӥ'>, X@clp*2Nr7;1) wѹ0`0&r5 ܩ&oqD<=<SokNB<"<.=1y\zb˻o?1Xǥ'&KO[L2@I4ū$g3Q5h6 Ĵ,.%|$,OƝ~,q3UqY쀨 OR7_l2.&r-$$,Nǥ'D@xi_\0 D\B5Nfp<røǥctlyR"/S7?ukjڬ_սM#/Z~-qI2՛*\̸˰.V/1[YGy`0'6uxSQuS*xF#. *q*bTdYΗuMyoeDu.D{JքN @'EdMRpe2 &VRC3х@z@r'ڐGU'[M#JW*!-F1)EhQ#JwȲ-#O\:t8-ұEx\:Kq"<.[ǥc׺|]_m1,Gzrg `_%UpqK ʉ@^ejVȟうJ4`FojH ũe-H7`ve.]^^gV+6 unaGmgK@ϝQ6( Mjțv!xr=r`F1beQ^!4vb %h'EȲw \@\H$t⠧:RpȥmxZ%dXц?ь2 ťf8Ne'6},x\:Kq"<.[ǥctlym=adA5=:m]y!N[J9ME4{6x\7Uy޴h:q]#c\Z(ضb, ^seb+P xUY5}ߵͮԹTqY^T_iTT@,RnD|Tv(*f8]E)}èؕ)Uf3BȧEAܯ58[\^řLxo̸ӏ&N `pO+ZfLfC%<D/_)r$J6 0i5v!։'B[Z c\?dg, lݖ*Ս4UR[Ηu-~0"X_Q`&-PkaP/~w@] DD6dZ͉vJ?1iꨘskFkdcĥ 3X`qx\:Kq"<.[ǥctl-"g\&ע:̽͐?:⤱Z,̉S~+dٛ/e-z3 wN4%4⺰& VT{Nrc9cvf 4F_fNOgԲx薵 ڪ.ng`,kg6l&׮ }8{\vpў3+B$iNȞ&Eʴ֨*e!XGHHoT=h,iPBI}W3K Ul!:?@qٹPC&k%-GނY8#pWL^Ta&jxUBD=3  C*ڭb,q-rƥL= ʗˍAKq"<.[ǥc~xNtlg8_/Û2UfK%m f`9Mf9e{p x04=׸,<υ#`8{\~|Q|fT('(~h_Sѹ% Nuӑ*S+ 2(\:W"I\E(Ys蒖Doz=.ʴ,^0^'ҖQۯ1Dl4,P⬫VOI)=\1"ֲ Lb궢m ݣD_u J{BJ =4T!+r'+Br'+1V%.ϒ}HhXZiұEdK#+<.[ǥctlKғNڄZ_{zǥX%IENDB`
-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/Implementation/RenameTracking/RenameTrackingTaggerProvider.Tagger.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 Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { private class Tagger : ITagger<RenameTrackingTag>, ITagger<IErrorTag>, IDisposable { private readonly StateMachine _stateMachine; public event EventHandler<SnapshotSpanEventArgs> TagsChanged = delegate { }; public Tagger(StateMachine stateMachine) { _stateMachine = stateMachine; _stateMachine.Connect(); _stateMachine.TrackingSessionUpdated += StateMachine_TrackingSessionUpdated; _stateMachine.TrackingSessionCleared += StateMachine_TrackingSessionCleared; } private void StateMachine_TrackingSessionCleared(ITrackingSpan trackingSpanToClear) => TagsChanged(this, new SnapshotSpanEventArgs(trackingSpanToClear.GetSpan(_stateMachine.Buffer.CurrentSnapshot))); private void StateMachine_TrackingSessionUpdated() { if (_stateMachine.TrackingSession != null) { TagsChanged(this, new SnapshotSpanEventArgs(_stateMachine.TrackingSession.TrackingSpan.GetSpan(_stateMachine.Buffer.CurrentSnapshot))); } } public IEnumerable<ITagSpan<RenameTrackingTag>> GetTags(NormalizedSnapshotSpanCollection spans) => GetTags(spans, RenameTrackingTag.Instance); IEnumerable<ITagSpan<IErrorTag>> ITagger<IErrorTag>.GetTags(NormalizedSnapshotSpanCollection spans) => GetTags(spans, new ErrorTag(PredefinedErrorTypeNames.Suggestion)); private IEnumerable<ITagSpan<T>> GetTags<T>(NormalizedSnapshotSpanCollection spans, T tag) where T : ITag { if (!_stateMachine.Buffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.RenameTracking)) { // Changes aren't being triggered by the buffer, but there may still be taggers // out there which we should prevent from doing work. yield break; } if (_stateMachine.CanInvokeRename(out var trackingSession, isSmartTagCheck: true)) { foreach (var span in spans) { var snapshotSpan = trackingSession.TrackingSpan.GetSpan(span.Snapshot); if (span.IntersectsWith(snapshotSpan)) { yield return new TagSpan<T>(snapshotSpan, tag); } } } } public void Dispose() { _stateMachine.TrackingSessionUpdated -= StateMachine_TrackingSessionUpdated; _stateMachine.TrackingSessionCleared -= StateMachine_TrackingSessionCleared; _stateMachine.Disconnect(); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { private class Tagger : ITagger<RenameTrackingTag>, ITagger<IErrorTag>, IDisposable { private readonly StateMachine _stateMachine; public event EventHandler<SnapshotSpanEventArgs> TagsChanged = delegate { }; public Tagger(StateMachine stateMachine) { _stateMachine = stateMachine; _stateMachine.Connect(); _stateMachine.TrackingSessionUpdated += StateMachine_TrackingSessionUpdated; _stateMachine.TrackingSessionCleared += StateMachine_TrackingSessionCleared; } private void StateMachine_TrackingSessionCleared(ITrackingSpan trackingSpanToClear) => TagsChanged(this, new SnapshotSpanEventArgs(trackingSpanToClear.GetSpan(_stateMachine.Buffer.CurrentSnapshot))); private void StateMachine_TrackingSessionUpdated() { if (_stateMachine.TrackingSession != null) { TagsChanged(this, new SnapshotSpanEventArgs(_stateMachine.TrackingSession.TrackingSpan.GetSpan(_stateMachine.Buffer.CurrentSnapshot))); } } public IEnumerable<ITagSpan<RenameTrackingTag>> GetTags(NormalizedSnapshotSpanCollection spans) => GetTags(spans, RenameTrackingTag.Instance); IEnumerable<ITagSpan<IErrorTag>> ITagger<IErrorTag>.GetTags(NormalizedSnapshotSpanCollection spans) => GetTags(spans, new ErrorTag(PredefinedErrorTypeNames.Suggestion)); private IEnumerable<ITagSpan<T>> GetTags<T>(NormalizedSnapshotSpanCollection spans, T tag) where T : ITag { if (!_stateMachine.Buffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.RenameTracking)) { // Changes aren't being triggered by the buffer, but there may still be taggers // out there which we should prevent from doing work. yield break; } if (_stateMachine.CanInvokeRename(out var trackingSession, isSmartTagCheck: true)) { foreach (var span in spans) { var snapshotSpan = trackingSession.TrackingSpan.GetSpan(span.Snapshot); if (span.IntersectsWith(snapshotSpan)) { yield return new TagSpan<T>(snapshotSpan, tag); } } } } public void Dispose() { _stateMachine.TrackingSessionUpdated -= StateMachine_TrackingSessionUpdated; _stateMachine.TrackingSessionCleared -= StateMachine_TrackingSessionCleared; _stateMachine.Disconnect(); } } } }
-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/VisualBasic/Impl/ProjectSystemShim/Interop/OutputLevel.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Friend Enum OutputLevel OUTPUT_Quiet OUTPUT_Normal OUTPUT_Verbose 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.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Friend Enum OutputLevel OUTPUT_Quiet OUTPUT_Normal OUTPUT_Verbose 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/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/InteractiveWindow_OutOfProc.Verifier.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 Xunit; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { /// <summary> /// Provides a means of interacting with the interactive window in the Visual Studio host. /// </summary> public abstract partial class InteractiveWindow_OutOfProc : TextViewWindow_OutOfProc { public class Verifier : Verifier<InteractiveWindow_OutOfProc> { private static readonly char[] LineSeparators = { '\r', '\n' }; public Verifier(InteractiveWindow_OutOfProc interactiveWindow, VisualStudioInstance instance) : base(interactiveWindow, instance) { } public void LastReplInput(string expectedReplInput) { var lastReplInput = _textViewWindow.GetLastReplInput(); Assert.Equal(expectedReplInput, lastReplInput); } public void ReplPromptConsistency(string prompt, string output) { var replText = _textViewWindow.GetReplText(); var replTextLines = replText.Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (var replTextLine in replTextLines) { if (!replTextLine.Contains(prompt)) { continue; } // The prompt must be at the beginning of the line Assert.StartsWith(prompt, replTextLine); var promptIndex = replTextLine.IndexOf(prompt, prompt.Length); // A 'subsequent' prompt is only allowed on a line containing #prompt if (promptIndex >= 0) { Assert.StartsWith(prompt + "#prompt", replTextLine); Assert.False(replTextLine.IndexOf(prompt, promptIndex + prompt.Length) >= 0); } // There must be no output on a prompt line. Assert.DoesNotContain(output, replTextLine); } } } } }
// Licensed to the .NET Foundation under one or more 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 Xunit; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { /// <summary> /// Provides a means of interacting with the interactive window in the Visual Studio host. /// </summary> public abstract partial class InteractiveWindow_OutOfProc : TextViewWindow_OutOfProc { public class Verifier : Verifier<InteractiveWindow_OutOfProc> { private static readonly char[] LineSeparators = { '\r', '\n' }; public Verifier(InteractiveWindow_OutOfProc interactiveWindow, VisualStudioInstance instance) : base(interactiveWindow, instance) { } public void LastReplInput(string expectedReplInput) { var lastReplInput = _textViewWindow.GetLastReplInput(); Assert.Equal(expectedReplInput, lastReplInput); } public void ReplPromptConsistency(string prompt, string output) { var replText = _textViewWindow.GetReplText(); var replTextLines = replText.Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (var replTextLine in replTextLines) { if (!replTextLine.Contains(prompt)) { continue; } // The prompt must be at the beginning of the line Assert.StartsWith(prompt, replTextLine); var promptIndex = replTextLine.IndexOf(prompt, prompt.Length); // A 'subsequent' prompt is only allowed on a line containing #prompt if (promptIndex >= 0) { Assert.StartsWith(prompt + "#prompt", replTextLine); Assert.False(replTextLine.IndexOf(prompt, promptIndex + prompt.Length) >= 0); } // There must be no output on a prompt line. Assert.DoesNotContain(output, replTextLine); } } } } }
-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/SourceGeneration/Nodes/TransformNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput> { private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func; private readonly IEqualityComparer<TOutput> _comparer; private readonly IIncrementalGeneratorNode<TInput> _sourceNode; public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null) : this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer) { } public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null) { _sourceNode = sourceNode; _func = userFunc; _comparer = comparer ?? EqualityComparer<TOutput>.Default; } public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer); public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); if (sourceTable.IsCached) { return previousTable; } // Semantics of a transform: // Element-wise comparison of upstream table // - Cached or Removed: no transform, just use previous values // - Added: perform transform and add // - Modified: perform transform and do element wise comparison with previous results var newTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { newTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries()) { // generate the new entries var newOutputs = _func(entry.item, cancellationToken); if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer)) { newTable.AddEntries(newOutputs, EntryState.Added); } } } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput> { private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func; private readonly IEqualityComparer<TOutput> _comparer; private readonly IIncrementalGeneratorNode<TInput> _sourceNode; public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null) : this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer) { } public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null) { _sourceNode = sourceNode; _func = userFunc; _comparer = comparer ?? EqualityComparer<TOutput>.Default; } public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer); public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); if (sourceTable.IsCached) { return previousTable; } // Semantics of a transform: // Element-wise comparison of upstream table // - Cached or Removed: no transform, just use previous values // - Added: perform transform and add // - Modified: perform transform and do element wise comparison with previous results var newTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { newTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries()) { // generate the new entries var newOutputs = _func(entry.item, cancellationToken); if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer)) { newTable.AddEntries(newOutputs, EntryState.Added); } } } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(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/ExpressionEvaluator/CSharp/Test/ResultProvider/Microsoft.CodeAnalysis.CSharp.ResultProvider.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests</AssemblyName> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Test\ResultProvider\Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\SymbolDisplay\ObjectDisplay.cs"> <Link>Compiler\SymbolDisplay\ObjectDisplay.cs</Link> </Compile> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="..\..\Source\ResultProvider\CSharpResultProvider.projitems" Label="Shared" /> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests</AssemblyName> <TargetFramework>net472</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Test\ResultProvider\Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj" /> <ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\SymbolDisplay\ObjectDisplay.cs"> <Link>Compiler\SymbolDisplay\ObjectDisplay.cs</Link> </Compile> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="..\..\Source\ResultProvider\CSharpResultProvider.projitems" Label="Shared" /> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.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 System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> : IAddImportFeatureService, IEqualityComparer<PortableExecutableReference> where TSimpleNameSyntax : SyntaxNode { protected abstract bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool CanAddImportForMethod(string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForQuery(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForType(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract ISet<INamespaceSymbol> GetImportNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetDeconstructInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, IReadOnlyList<string> nameSpaceParts, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel); protected abstract string GetDescription(IReadOnlyList<string> nameParts); protected abstract (string description, bool hasExistingImport) GetDescription(Document document, INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken); public async Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, searchReferenceAssemblies, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetFixesInCurrentProcessAsync( document, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start, findInsideTrivia: true) .GetAncestor(n => n.Span.Contains(span) && n != root); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var result); if (node != null) { using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken)) { if (!cancellationToken.IsCancellationRequested) { if (CanAddImport(node, allowInHiddenRegions, cancellationToken)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allSymbolReferences = await FindResultsAsync( document, semanticModel, diagnosticId, node, maxResults, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); // Nothing found at all. No need to proceed. foreach (var reference in allSymbolReferences) { cancellationToken.ThrowIfCancellationRequested(); var fixData = await reference.TryGetFixDataAsync(document, node, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); result.AddIfNotNull(fixData); } } } } } return result.ToImmutable(); } private async Task<ImmutableArray<Reference>> FindResultsAsync( Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, int maxResults, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // Caches so we don't produce the same data multiple times while searching // all over the solution. var project = document.Project; var projectToAssembly = new ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>>(concurrencyLevel: 2, capacity: project.Solution.ProjectIds.Count); var referenceToCompilation = new ConcurrentDictionary<PortableExecutableReference, Compilation>(concurrencyLevel: 2, capacity: project.Solution.Projects.Sum(p => p.MetadataReferences.Count)); var finder = new SymbolReferenceFinder( this, document, semanticModel, diagnosticId, node, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken); // Look for exact matches first: var exactReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: true, cancellationToken: cancellationToken).ConfigureAwait(false); if (exactReferences.Length > 0) { return exactReferences; } // No exact matches found. Fall back to fuzzy searching. // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as this will cause us to // create expensive bk-trees which we won't even be able to save for // future use. if (!IsHostOrRemoteWorkspace(project)) { return ImmutableArray<Reference>.Empty; } var fuzzyReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: false, cancellationToken: cancellationToken).ConfigureAwait(false); return fuzzyReferences; } private static bool IsHostOrRemoteWorkspace(Project project) { return project.Solution.Workspace.Kind is WorkspaceKind.Host or WorkspaceKind.RemoteWorkspace or WorkspaceKind.RemoteTemporaryWorkspace; } private async Task<ImmutableArray<Reference>> FindResultsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Reference>.GetInstance(out var allReferences); // First search the current project to see if any symbols (source or metadata) match the // search string. await FindResultsInAllSymbolsInStartingProjectAsync( allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as we can't even add project // references to the interactive window. We could consider adding metadata // references with #r in the future. if (IsHostOrRemoteWorkspace(project)) { // Now search unreferenced projects, and see if they have any source symbols that match // the search string. await FindResultsInUnreferencedProjectSourceSymbolsAsync(projectToAssembly, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Finally, check and see if we have any metadata symbols that match the search string. await FindResultsInUnreferencedMetadataSymbolsAsync(referenceToCompilation, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // We only support searching NuGet in an exact manner currently. if (exact) { await finder.FindNugetOrReferenceAssemblyReferencesAsync(allReferences, cancellationToken).ConfigureAwait(false); } } return allReferences.ToImmutable(); } private static async Task FindResultsInAllSymbolsInStartingProjectAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { var references = await finder.FindInAllSymbolsInStartingProjectAsync(exact, cancellationToken).ConfigureAwait(false); AddRange(allSymbolReferences, references, maxResults); } private static async Task FindResultsInUnreferencedProjectSourceSymbolsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { // If we didn't find enough hits searching just in the project, then check // in any unreferenced projects. if (allSymbolReferences.Count >= maxResults) { return; } var viableUnreferencedProjects = GetViableUnreferencedProjects(project); // Search all unreferenced projects in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var unreferencedProject in viableUnreferencedProjects) { // Search in this unreferenced project. But don't search in any of its' // direct references. i.e. we don't want to search in its metadata references // or in the projects it references itself. We'll be searching those entities // individually. findTasks.Add(finder.FindInSourceSymbolsInProjectAsync( projectToAssembly, unreferencedProject, exact, linkedTokenSource.Token)); } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } private async Task FindResultsInUnreferencedMetadataSymbolsAsync( ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { if (allSymbolReferences.Count > 0) { // Only do this if none of the project searches produced any results. We may have a // lot of metadata to search through, and it would be good to avoid that if we can. return; } // Keep track of the references we've seen (so that we don't process them multiple times // across many sibling projects). Prepopulate it with our own metadata references since // we know we don't need to search in that. var seenReferences = new HashSet<PortableExecutableReference>(comparer: this); seenReferences.AddAll(project.MetadataReferences.OfType<PortableExecutableReference>()); var newReferences = GetUnreferencedMetadataReferences(project, seenReferences); // Search all metadata references in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var (referenceProjectId, reference) in newReferences) { var compilation = referenceToCompilation.GetOrAdd( reference, r => CreateCompilation(project, r)); // Ignore netmodules. First, they're incredibly esoteric and barely used. // Second, the SymbolFinder API doesn't even support searching them. if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) { findTasks.Add(finder.FindInMetadataSymbolsAsync( assembly, referenceProjectId, reference, exact, linkedTokenSource.Token)); } } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the set of PEReferences in the solution that are not currently being referenced /// by this project. The set returned will be tuples containing the PEReference, and the project-id /// for the project we found the pe-reference in. /// </summary> private static ImmutableArray<(ProjectId, PortableExecutableReference)> GetUnreferencedMetadataReferences( Project project, HashSet<PortableExecutableReference> seenReferences) { var result = ArrayBuilder<(ProjectId, PortableExecutableReference)>.GetInstance(); var solution = project.Solution; foreach (var p in solution.Projects) { if (p == project) { continue; } foreach (var reference in p.MetadataReferences) { if (reference is PortableExecutableReference peReference && !IsInPackagesDirectory(peReference) && seenReferences.Add(peReference)) { result.Add((p.Id, peReference)); } } } return result.ToImmutableAndFree(); } private static async Task WaitForTasksAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, HashSet<Task<ImmutableArray<SymbolReference>>> findTasks, CancellationTokenSource nestedTokenSource, CancellationToken cancellationToken) { try { while (findTasks.Count > 0) { // Keep on looping through the 'find' tasks, processing each when they finish. cancellationToken.ThrowIfCancellationRequested(); var doneTask = await Task.WhenAny(findTasks).ConfigureAwait(false); // One of the tasks finished. Remove it from the list we're waiting on. findTasks.Remove(doneTask); // Add its results to the final result set we're keeping. AddRange(allSymbolReferences, await doneTask.ConfigureAwait(false), maxResults); // Once we get enough, just stop. if (allSymbolReferences.Count >= maxResults) { return; } } } finally { // Cancel any nested work that's still happening. nestedTokenSource.Cancel(); } } /// <summary> /// We ignore references that are in a directory that contains the names /// "Packages", "packs", "NuGetFallbackFolder", or "NuGetPackages" /// These directories are most likely the ones produced by NuGet, and we don't want /// to offer to add .dll reference manually for dlls that are part of NuGet packages. /// /// Note that this is only a heuristic (though a good one), and we should remove this /// when we can get an API from NuGet that tells us if a reference is actually provided /// by a nuget packages. /// Tracking issue: https://github.com/dotnet/project-system/issues/5275 /// /// This heuristic will do the right thing in practically all cases for all. It /// prevents the very unpleasant experience of us offering to add a direct metadata /// reference to something that should only be referenced as a nuget package. /// /// It does mean that if the following is true: /// You have a project that has a non-nuget metadata reference to something in a "packages" /// directory, and you are in another project that uses a type name that would have matched /// an accessible type from that dll. then we will not offer to add that .dll reference to /// that other project. /// /// However, that would be an exceedingly uncommon case that is degraded. Whereas we're /// vastly improved in the common case. This is a totally acceptable and desirable outcome /// for such a heuristic. /// </summary> private static bool IsInPackagesDirectory(PortableExecutableReference reference) { return ContainsPathComponent(reference, "packages") || ContainsPathComponent(reference, "packs") || ContainsPathComponent(reference, "NuGetFallbackFolder") || ContainsPathComponent(reference, "NuGetPackages"); static bool ContainsPathComponent(PortableExecutableReference reference, string pathComponent) { return PathUtilities.ContainsPathComponent(reference.FilePath, pathComponent, ignoreCase: true); } } /// <summary> /// Called when we want to search a metadata reference. We create a dummy compilation /// containing just that reference and we search that. That way we can get actual symbols /// returned. /// /// We don't want to use the project that the reference is actually associated with as /// getting the compilation for that project may be extremely expensive. For example, /// in a large solution it may cause us to build an enormous amount of skeleton assemblies. /// </summary> private static Compilation CreateCompilation(Project project, PortableExecutableReference reference) { var compilationService = project.LanguageServices.GetRequiredService<ICompilationFactoryService>(); var compilation = compilationService.CreateCompilation("TempAssembly", compilationService.GetDefaultCompilationOptions()); return compilation.WithReferences(reference); } bool IEqualityComparer<PortableExecutableReference>.Equals(PortableExecutableReference? x, PortableExecutableReference? y) { if (x == y) return true; var path1 = x?.FilePath ?? x?.Display; var path2 = y?.FilePath ?? y?.Display; if (path1 == null || path2 == null) return false; return StringComparer.OrdinalIgnoreCase.Equals(path1, path2); } int IEqualityComparer<PortableExecutableReference>.GetHashCode(PortableExecutableReference obj) { var path = obj.FilePath ?? obj.Display; return path == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode(path); } private static HashSet<Project> GetViableUnreferencedProjects(Project project) { var solution = project.Solution; var viableProjects = new HashSet<Project>(solution.Projects); // Clearly we can't reference ourselves. viableProjects.Remove(project); // We can't reference any project that transitively depends on us. Doing so would // cause a circular reference between projects. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectsThatTransitivelyDependOnThisProject = dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id); viableProjects.RemoveAll(projectsThatTransitivelyDependOnThisProject.Select(id => solution.GetRequiredProject(id))); // We also aren't interested in any projects we're already directly referencing. viableProjects.RemoveAll(project.ProjectReferences.Select(r => solution.GetRequiredProject(r.ProjectId))); return viableProjects; } private static void AddRange<TReference>(ArrayBuilder<Reference> allSymbolReferences, ImmutableArray<TReference> proposedReferences, int maxResults) where TReference : Reference { allSymbolReferences.AddRange(proposedReferences.Take(maxResults - allSymbolReferences.Count)); } protected static bool IsViableExtensionMethod(IMethodSymbol method, ITypeSymbol receiver) { if (receiver == null || method == null) { return false; } // It's possible that the 'method' we're looking at is from a different language than // the language we're currently in. For example, we might find the extension method // in an unreferenced VB project while we're in C#. However, in order to 'reduce' // the extension method, the compiler requires both the method and receiver to be // from the same language. // // So, if they're not from the same language, we simply can't proceed. Now in this // case we decide that the method is not viable. But we could, in the future, decide // to just always consider such methods viable. if (receiver.Language != method.Language) { return false; } return method.ReduceExtensionMethod(receiver) != null; } private static bool NotGlobalNamespace(SymbolReference reference) { var symbol = reference.SymbolResult.Symbol; return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true; } private static bool NotNull(SymbolReference reference) => reference.SymbolResult.Symbol != null; public async Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // We might have multiple different diagnostics covering the same span. Have to // process them all as we might produce different fixes for each diagnostic. var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); // Normally we don't allow generation into a hidden region in the file. However, if we have a // modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping // our edit to their domain appropriate. var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var fixesForDiagnosticBuilder = ArrayBuilder<(Diagnostic, ImmutableArray<AddImportFixData>)>.GetInstance(); foreach (var diagnostic in diagnostics) { var fixes = await GetFixesAsync( document, span, diagnostic.Id, maxResultsPerDiagnostic, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); fixesForDiagnosticBuilder.Add((diagnostic, fixes)); } return fixesForDiagnosticBuilder.ToImmutableAndFree(); } public ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService? installerService, int maxResults) { var codeActionsBuilder = ArrayBuilder<CodeAction>.GetInstance(); foreach (var fix in fixes) { var codeAction = TryCreateCodeAction(document, fix, installerService); codeActionsBuilder.AddIfNotNull(codeAction); if (codeActionsBuilder.Count >= maxResults) { break; } } return codeActionsBuilder.ToImmutableAndFree(); } private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService? installerService) => fixData.Kind switch { AddImportFixKind.ProjectSymbol => new ProjectSymbolReferenceCodeAction(document, fixData), AddImportFixKind.MetadataSymbol => new MetadataSymbolReferenceCodeAction(document, fixData), AddImportFixKind.ReferenceAssemblySymbol => new AssemblyReferenceCodeAction(document, fixData), AddImportFixKind.PackageSymbol => installerService?.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) == false ? new ParentInstallPackageCodeAction(document, fixData, installerService) : null, _ => throw ExceptionUtilities.Unreachable, }; private static ITypeSymbol? GetAwaitInfo(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var awaitExpression = FirstAwaitExpressionAncestor(syntaxFactsService, node); if (awaitExpression is null) return null; Debug.Assert(syntaxFactsService.IsAwaitExpression(awaitExpression)); var innerExpression = syntaxFactsService.GetExpressionOfAwaitExpression(awaitExpression); return semanticModel.GetTypeInfo(innerExpression).Type; } private static ITypeSymbol? GetCollectionExpressionType(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var collectionExpression = FirstForeachCollectionExpressionAncestor(syntaxFactsService, node); if (collectionExpression is null) { return null; } return semanticModel.GetTypeInfo(collectionExpression).Type; } protected static bool AncestorOrSelfIsAwaitExpression(ISyntaxFacts syntaxFactsService, SyntaxNode node) => FirstAwaitExpressionAncestor(syntaxFactsService, node) != null; private static SyntaxNode? FirstAwaitExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsAwaitExpression(n), syntaxFactsService); private static SyntaxNode? FirstForeachCollectionExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsExpressionOfForeach(n), syntaxFactsService); } }
// Licensed to the .NET Foundation under one or more 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 System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> : IAddImportFeatureService, IEqualityComparer<PortableExecutableReference> where TSimpleNameSyntax : SyntaxNode { protected abstract bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool CanAddImportForMethod(string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForQuery(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForType(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract ISet<INamespaceSymbol> GetImportNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetDeconstructInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, IReadOnlyList<string> nameSpaceParts, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel); protected abstract string GetDescription(IReadOnlyList<string> nameParts); protected abstract (string description, bool hasExistingImport) GetDescription(Document document, INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken); public async Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, searchReferenceAssemblies, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetFixesInCurrentProcessAsync( document, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start, findInsideTrivia: true) .GetAncestor(n => n.Span.Contains(span) && n != root); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var result); if (node != null) { using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken)) { if (!cancellationToken.IsCancellationRequested) { if (CanAddImport(node, allowInHiddenRegions, cancellationToken)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allSymbolReferences = await FindResultsAsync( document, semanticModel, diagnosticId, node, maxResults, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); // Nothing found at all. No need to proceed. foreach (var reference in allSymbolReferences) { cancellationToken.ThrowIfCancellationRequested(); var fixData = await reference.TryGetFixDataAsync(document, node, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); result.AddIfNotNull(fixData); } } } } } return result.ToImmutable(); } private async Task<ImmutableArray<Reference>> FindResultsAsync( Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, int maxResults, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // Caches so we don't produce the same data multiple times while searching // all over the solution. var project = document.Project; var projectToAssembly = new ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>>(concurrencyLevel: 2, capacity: project.Solution.ProjectIds.Count); var referenceToCompilation = new ConcurrentDictionary<PortableExecutableReference, Compilation>(concurrencyLevel: 2, capacity: project.Solution.Projects.Sum(p => p.MetadataReferences.Count)); var finder = new SymbolReferenceFinder( this, document, semanticModel, diagnosticId, node, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken); // Look for exact matches first: var exactReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: true, cancellationToken: cancellationToken).ConfigureAwait(false); if (exactReferences.Length > 0) { return exactReferences; } // No exact matches found. Fall back to fuzzy searching. // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as this will cause us to // create expensive bk-trees which we won't even be able to save for // future use. if (!IsHostOrRemoteWorkspace(project)) { return ImmutableArray<Reference>.Empty; } var fuzzyReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: false, cancellationToken: cancellationToken).ConfigureAwait(false); return fuzzyReferences; } private static bool IsHostOrRemoteWorkspace(Project project) { return project.Solution.Workspace.Kind is WorkspaceKind.Host or WorkspaceKind.RemoteWorkspace or WorkspaceKind.RemoteTemporaryWorkspace; } private async Task<ImmutableArray<Reference>> FindResultsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Reference>.GetInstance(out var allReferences); // First search the current project to see if any symbols (source or metadata) match the // search string. await FindResultsInAllSymbolsInStartingProjectAsync( allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as we can't even add project // references to the interactive window. We could consider adding metadata // references with #r in the future. if (IsHostOrRemoteWorkspace(project)) { // Now search unreferenced projects, and see if they have any source symbols that match // the search string. await FindResultsInUnreferencedProjectSourceSymbolsAsync(projectToAssembly, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Finally, check and see if we have any metadata symbols that match the search string. await FindResultsInUnreferencedMetadataSymbolsAsync(referenceToCompilation, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // We only support searching NuGet in an exact manner currently. if (exact) { await finder.FindNugetOrReferenceAssemblyReferencesAsync(allReferences, cancellationToken).ConfigureAwait(false); } } return allReferences.ToImmutable(); } private static async Task FindResultsInAllSymbolsInStartingProjectAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { var references = await finder.FindInAllSymbolsInStartingProjectAsync(exact, cancellationToken).ConfigureAwait(false); AddRange(allSymbolReferences, references, maxResults); } private static async Task FindResultsInUnreferencedProjectSourceSymbolsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { // If we didn't find enough hits searching just in the project, then check // in any unreferenced projects. if (allSymbolReferences.Count >= maxResults) { return; } var viableUnreferencedProjects = GetViableUnreferencedProjects(project); // Search all unreferenced projects in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var unreferencedProject in viableUnreferencedProjects) { // Search in this unreferenced project. But don't search in any of its' // direct references. i.e. we don't want to search in its metadata references // or in the projects it references itself. We'll be searching those entities // individually. findTasks.Add(finder.FindInSourceSymbolsInProjectAsync( projectToAssembly, unreferencedProject, exact, linkedTokenSource.Token)); } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } private async Task FindResultsInUnreferencedMetadataSymbolsAsync( ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { if (allSymbolReferences.Count > 0) { // Only do this if none of the project searches produced any results. We may have a // lot of metadata to search through, and it would be good to avoid that if we can. return; } // Keep track of the references we've seen (so that we don't process them multiple times // across many sibling projects). Prepopulate it with our own metadata references since // we know we don't need to search in that. var seenReferences = new HashSet<PortableExecutableReference>(comparer: this); seenReferences.AddAll(project.MetadataReferences.OfType<PortableExecutableReference>()); var newReferences = GetUnreferencedMetadataReferences(project, seenReferences); // Search all metadata references in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var (referenceProjectId, reference) in newReferences) { var compilation = referenceToCompilation.GetOrAdd( reference, r => CreateCompilation(project, r)); // Ignore netmodules. First, they're incredibly esoteric and barely used. // Second, the SymbolFinder API doesn't even support searching them. if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) { findTasks.Add(finder.FindInMetadataSymbolsAsync( assembly, referenceProjectId, reference, exact, linkedTokenSource.Token)); } } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the set of PEReferences in the solution that are not currently being referenced /// by this project. The set returned will be tuples containing the PEReference, and the project-id /// for the project we found the pe-reference in. /// </summary> private static ImmutableArray<(ProjectId, PortableExecutableReference)> GetUnreferencedMetadataReferences( Project project, HashSet<PortableExecutableReference> seenReferences) { var result = ArrayBuilder<(ProjectId, PortableExecutableReference)>.GetInstance(); var solution = project.Solution; foreach (var p in solution.Projects) { if (p == project) { continue; } foreach (var reference in p.MetadataReferences) { if (reference is PortableExecutableReference peReference && !IsInPackagesDirectory(peReference) && seenReferences.Add(peReference)) { result.Add((p.Id, peReference)); } } } return result.ToImmutableAndFree(); } private static async Task WaitForTasksAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, HashSet<Task<ImmutableArray<SymbolReference>>> findTasks, CancellationTokenSource nestedTokenSource, CancellationToken cancellationToken) { try { while (findTasks.Count > 0) { // Keep on looping through the 'find' tasks, processing each when they finish. cancellationToken.ThrowIfCancellationRequested(); var doneTask = await Task.WhenAny(findTasks).ConfigureAwait(false); // One of the tasks finished. Remove it from the list we're waiting on. findTasks.Remove(doneTask); // Add its results to the final result set we're keeping. AddRange(allSymbolReferences, await doneTask.ConfigureAwait(false), maxResults); // Once we get enough, just stop. if (allSymbolReferences.Count >= maxResults) { return; } } } finally { // Cancel any nested work that's still happening. nestedTokenSource.Cancel(); } } /// <summary> /// We ignore references that are in a directory that contains the names /// "Packages", "packs", "NuGetFallbackFolder", or "NuGetPackages" /// These directories are most likely the ones produced by NuGet, and we don't want /// to offer to add .dll reference manually for dlls that are part of NuGet packages. /// /// Note that this is only a heuristic (though a good one), and we should remove this /// when we can get an API from NuGet that tells us if a reference is actually provided /// by a nuget packages. /// Tracking issue: https://github.com/dotnet/project-system/issues/5275 /// /// This heuristic will do the right thing in practically all cases for all. It /// prevents the very unpleasant experience of us offering to add a direct metadata /// reference to something that should only be referenced as a nuget package. /// /// It does mean that if the following is true: /// You have a project that has a non-nuget metadata reference to something in a "packages" /// directory, and you are in another project that uses a type name that would have matched /// an accessible type from that dll. then we will not offer to add that .dll reference to /// that other project. /// /// However, that would be an exceedingly uncommon case that is degraded. Whereas we're /// vastly improved in the common case. This is a totally acceptable and desirable outcome /// for such a heuristic. /// </summary> private static bool IsInPackagesDirectory(PortableExecutableReference reference) { return ContainsPathComponent(reference, "packages") || ContainsPathComponent(reference, "packs") || ContainsPathComponent(reference, "NuGetFallbackFolder") || ContainsPathComponent(reference, "NuGetPackages"); static bool ContainsPathComponent(PortableExecutableReference reference, string pathComponent) { return PathUtilities.ContainsPathComponent(reference.FilePath, pathComponent, ignoreCase: true); } } /// <summary> /// Called when we want to search a metadata reference. We create a dummy compilation /// containing just that reference and we search that. That way we can get actual symbols /// returned. /// /// We don't want to use the project that the reference is actually associated with as /// getting the compilation for that project may be extremely expensive. For example, /// in a large solution it may cause us to build an enormous amount of skeleton assemblies. /// </summary> private static Compilation CreateCompilation(Project project, PortableExecutableReference reference) { var compilationService = project.LanguageServices.GetRequiredService<ICompilationFactoryService>(); var compilation = compilationService.CreateCompilation("TempAssembly", compilationService.GetDefaultCompilationOptions()); return compilation.WithReferences(reference); } bool IEqualityComparer<PortableExecutableReference>.Equals(PortableExecutableReference? x, PortableExecutableReference? y) { if (x == y) return true; var path1 = x?.FilePath ?? x?.Display; var path2 = y?.FilePath ?? y?.Display; if (path1 == null || path2 == null) return false; return StringComparer.OrdinalIgnoreCase.Equals(path1, path2); } int IEqualityComparer<PortableExecutableReference>.GetHashCode(PortableExecutableReference obj) { var path = obj.FilePath ?? obj.Display; return path == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode(path); } private static HashSet<Project> GetViableUnreferencedProjects(Project project) { var solution = project.Solution; var viableProjects = new HashSet<Project>(solution.Projects); // Clearly we can't reference ourselves. viableProjects.Remove(project); // We can't reference any project that transitively depends on us. Doing so would // cause a circular reference between projects. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectsThatTransitivelyDependOnThisProject = dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id); viableProjects.RemoveAll(projectsThatTransitivelyDependOnThisProject.Select(id => solution.GetRequiredProject(id))); // We also aren't interested in any projects we're already directly referencing. viableProjects.RemoveAll(project.ProjectReferences.Select(r => solution.GetRequiredProject(r.ProjectId))); return viableProjects; } private static void AddRange<TReference>(ArrayBuilder<Reference> allSymbolReferences, ImmutableArray<TReference> proposedReferences, int maxResults) where TReference : Reference { allSymbolReferences.AddRange(proposedReferences.Take(maxResults - allSymbolReferences.Count)); } protected static bool IsViableExtensionMethod(IMethodSymbol method, ITypeSymbol receiver) { if (receiver == null || method == null) { return false; } // It's possible that the 'method' we're looking at is from a different language than // the language we're currently in. For example, we might find the extension method // in an unreferenced VB project while we're in C#. However, in order to 'reduce' // the extension method, the compiler requires both the method and receiver to be // from the same language. // // So, if they're not from the same language, we simply can't proceed. Now in this // case we decide that the method is not viable. But we could, in the future, decide // to just always consider such methods viable. if (receiver.Language != method.Language) { return false; } return method.ReduceExtensionMethod(receiver) != null; } private static bool NotGlobalNamespace(SymbolReference reference) { var symbol = reference.SymbolResult.Symbol; return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true; } private static bool NotNull(SymbolReference reference) => reference.SymbolResult.Symbol != null; public async Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // We might have multiple different diagnostics covering the same span. Have to // process them all as we might produce different fixes for each diagnostic. var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); // Normally we don't allow generation into a hidden region in the file. However, if we have a // modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping // our edit to their domain appropriate. var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var fixesForDiagnosticBuilder = ArrayBuilder<(Diagnostic, ImmutableArray<AddImportFixData>)>.GetInstance(); foreach (var diagnostic in diagnostics) { var fixes = await GetFixesAsync( document, span, diagnostic.Id, maxResultsPerDiagnostic, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); fixesForDiagnosticBuilder.Add((diagnostic, fixes)); } return fixesForDiagnosticBuilder.ToImmutableAndFree(); } public async Task<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( Document document, TextSpan span, ImmutableArray<string> diagnosticIds, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetUniqueFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticIds, searchReferenceAssemblies, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetUniqueFixesAsyncInCurrentProcessAsync( document, span, diagnosticIds, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetUniqueFixesAsyncInCurrentProcessAsync( Document document, TextSpan span, ImmutableArray<string> diagnosticIds, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Get the diagnostics that indicate a missing import. var diagnostics = semanticModel.GetDiagnostics(span, cancellationToken) .Where(diagnostic => diagnosticIds.Contains(diagnostic.Id)) .ToImmutableArray(); var getFixesForDiagnosticsTasks = diagnostics .GroupBy(diagnostic => diagnostic.Location.SourceSpan) .Select(diagnosticsForSourceSpan => GetFixesForDiagnosticsAsync( document, diagnosticsForSourceSpan.Key, diagnosticsForSourceSpan.AsImmutable(), maxResultsPerDiagnostic: 2, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken)); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var fixes); foreach (var getFixesForDiagnosticsTask in getFixesForDiagnosticsTasks) { var fixesForDiagnostics = await getFixesForDiagnosticsTask.ConfigureAwait(false); foreach (var fixesForDiagnostic in fixesForDiagnostics) { // When there is more than one potential fix for a missing import diagnostic, // which is possible when the same class name is present in multiple namespaces, // we do not want to choose for the user and be wrong. We will not attempt to // fix this diagnostic and instead leave it for the user to resolve since they // will have more context for determining the proper fix. if (fixesForDiagnostic.Fixes.Length == 1) fixes.Add(fixesForDiagnostic.Fixes[0]); } } return fixes.ToImmutable(); } public ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService? installerService, int maxResults) { var codeActionsBuilder = ArrayBuilder<CodeAction>.GetInstance(); foreach (var fix in fixes) { var codeAction = TryCreateCodeAction(document, fix, installerService); codeActionsBuilder.AddIfNotNull(codeAction); if (codeActionsBuilder.Count >= maxResults) { break; } } return codeActionsBuilder.ToImmutableAndFree(); } private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService? installerService) => fixData.Kind switch { AddImportFixKind.ProjectSymbol => new ProjectSymbolReferenceCodeAction(document, fixData), AddImportFixKind.MetadataSymbol => new MetadataSymbolReferenceCodeAction(document, fixData), AddImportFixKind.ReferenceAssemblySymbol => new AssemblyReferenceCodeAction(document, fixData), AddImportFixKind.PackageSymbol => installerService?.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) == false ? new ParentInstallPackageCodeAction(document, fixData, installerService) : null, _ => throw ExceptionUtilities.Unreachable, }; private static ITypeSymbol? GetAwaitInfo(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var awaitExpression = FirstAwaitExpressionAncestor(syntaxFactsService, node); if (awaitExpression is null) return null; Debug.Assert(syntaxFactsService.IsAwaitExpression(awaitExpression)); var innerExpression = syntaxFactsService.GetExpressionOfAwaitExpression(awaitExpression); return semanticModel.GetTypeInfo(innerExpression).Type; } private static ITypeSymbol? GetCollectionExpressionType(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var collectionExpression = FirstForeachCollectionExpressionAncestor(syntaxFactsService, node); if (collectionExpression is null) { return null; } return semanticModel.GetTypeInfo(collectionExpression).Type; } protected static bool AncestorOrSelfIsAwaitExpression(ISyntaxFacts syntaxFactsService, SyntaxNode node) => FirstAwaitExpressionAncestor(syntaxFactsService, node) != null; private static SyntaxNode? FirstAwaitExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsAwaitExpression(n), syntaxFactsService); private static SyntaxNode? FirstForeachCollectionExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsExpressionOfForeach(n), syntaxFactsService); } }
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/AddImport/IAddImportFeatureService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IAddImportFeatureService : ILanguageService { /// <summary> /// Gets data for how to fix a particular <see cref="Diagnostic" /> id within the specified Document. /// Useful when you do not have an instance of the diagnostic, such as when invoked as a remote service. /// </summary> Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); /// <summary> /// Gets data for how to fix a set of <see cref="Diagnostic" />s within the specified Document. /// The fix data can be used to create code actions that apply the fixes. /// </summary> Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); /// <summary> /// Gets code actions that, when applied, will fix the missing imports for the document using /// the information from the provided fixes. /// </summary> ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService? installerService, int maxResults); } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IAddImportFeatureService : ILanguageService { /// <summary> /// Gets data for how to fix a particular <see cref="Diagnostic" /> id within the specified Document. /// Useful when you do not have an instance of the diagnostic, such as when invoked as a remote service. /// </summary> Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); /// <summary> /// Gets data for how to fix a set of <see cref="Diagnostic" />s within the specified Document. /// The fix data can be used to create code actions that apply the fixes. /// </summary> Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); /// <summary> /// Gets code actions that, when applied, will fix the missing imports for the document using /// the information from the provided fixes. /// </summary> ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService? installerService, int maxResults); /// <summary> /// Gets data for how to fix a particular <see cref="Diagnostic" /> id within the specified Document. /// Similar to <see cref="GetFixesAsync(Document, TextSpan, string, int, bool, bool, ISymbolSearchService, bool, ImmutableArray{PackageSource}, CancellationToken)"/> /// except it only returns fix data when there is a single using fix for a given span /// </summary> Task<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( Document document, TextSpan span, ImmutableArray<string> diagnosticIds, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); } }
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/AddImport/Remote/IRemoteMissingImportDiscoveryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IRemoteMissingImportDiscoveryService { internal interface ICallback { ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken); ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken); ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken); } ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IRemoteMissingImportDiscoveryService { internal interface ICallback { ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken); ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken); ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken); } ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId id, TextSpan span, ImmutableArray<string> diagnosticIds, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); } }
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsFeatureService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddMissingImports { internal abstract class AbstractAddMissingImportsFeatureService : IAddMissingImportsFeatureService { protected abstract ImmutableArray<string> FixableDiagnosticIds { get; } /// <inheritdoc/> public async Task<Document> AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { var analysisResult = await AnalyzeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); return await AddMissingImportsAsync(document, analysisResult, cancellationToken).ConfigureAwait(false); } /// <inheritdoc/> public async Task<Document> AddMissingImportsAsync(Document document, AddMissingImportsAnalysisResult analysisResult, CancellationToken cancellationToken) { if (analysisResult.CanAddMissingImports) { // Apply those fixes to the document. var newDocument = await ApplyFixesAsync(document, analysisResult.AddImportFixData, cancellationToken).ConfigureAwait(false); return newDocument; } return document; } /// <inheritdoc/> public async Task<AddMissingImportsAnalysisResult> AnalyzeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { // Get the diagnostics that indicate a missing import. var diagnostics = await GetDiagnosticsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (diagnostics.IsEmpty) { return new AddMissingImportsAnalysisResult( ImmutableArray<AddImportFixData>.Empty); } // Find fixes for the diagnostic where there is only a single fix. var unambiguousFixes = await GetUnambiguousFixesAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); // We do not want to add project or framework references without the user's input, so filter those out. var usableFixes = unambiguousFixes.WhereAsArray(fixData => DoesNotAddReference(fixData, document.Project.Id)); return new AddMissingImportsAnalysisResult(usableFixes); } private static bool DoesNotAddReference(AddImportFixData fixData, ProjectId currentProjectId) { return (fixData.ProjectReferenceToAdd is null || fixData.ProjectReferenceToAdd == currentProjectId) && (fixData.PortableExecutableReferenceProjectId is null || fixData.PortableExecutableReferenceProjectId == currentProjectId) && string.IsNullOrEmpty(fixData.AssemblyReferenceAssemblyName); } private async Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (semanticModel is null) { return ImmutableArray<Diagnostic>.Empty; } return semanticModel.GetDiagnostics(textSpan, cancellationToken) .Where(diagnostic => FixableDiagnosticIds.Contains(diagnostic.Id)) .ToImmutableArray(); } private static async Task<ImmutableArray<AddImportFixData>> GetUnambiguousFixesAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var solution = document.Project.Solution; var symbolSearchService = solution.Workspace.Services.GetRequiredService<ISymbolSearchService>(); // Since we are not currently considering NuGet packages, pass an empty array var packageSources = ImmutableArray<PackageSource>.Empty; var addImportService = document.GetRequiredLanguageService<IAddImportFeatureService>(); // We only need to receive 2 results back per diagnostic to determine that the fix is ambiguous. var getFixesForDiagnosticsTasks = diagnostics .GroupBy(diagnostic => diagnostic.Location.SourceSpan) .Select(diagnosticsForSourceSpan => addImportService .GetFixesForDiagnosticsAsync(document, diagnosticsForSourceSpan.Key, diagnosticsForSourceSpan.AsImmutable(), maxResultsPerDiagnostic: 2, symbolSearchService, searchReferenceAssemblies: true, packageSources, cancellationToken)); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var fixes); foreach (var getFixesForDiagnosticsTask in getFixesForDiagnosticsTasks) { var fixesForDiagnostics = await getFixesForDiagnosticsTask.ConfigureAwait(false); foreach (var fixesForDiagnostic in fixesForDiagnostics) { // When there is more than one potential fix for a missing import diagnostic, // which is possible when the same class name is present in multiple namespaces, // we do not want to choose for the user and be wrong. We will not attempt to // fix this diagnostic and instead leave it for the user to resolve since they // will have more context for determining the proper fix. if (fixesForDiagnostic.Fixes.Length == 1) fixes.Add(fixesForDiagnostic.Fixes[0]); } } return fixes.ToImmutable(); } private static async Task<Document> ApplyFixesAsync(Document document, ImmutableArray<AddImportFixData> fixes, CancellationToken cancellationToken) { if (fixes.IsEmpty) { return document; } var solution = document.Project.Solution; var progressTracker = new ProgressTracker(); var textDiffingService = solution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); var packageInstallerService = solution.Workspace.Services.GetService<IPackageInstallerService>(); var addImportService = document.GetRequiredLanguageService<IAddImportFeatureService>(); // Do not limit the results since we plan to fix all the reported issues. var codeActions = addImportService.GetCodeActionsForFixes(document, fixes, packageInstallerService, maxResults: int.MaxValue); var getChangesTasks = codeActions.Select( action => GetChangesForCodeActionAsync(document, action, progressTracker, textDiffingService, cancellationToken)); // Using Sets allows us to accumulate only the distinct changes. var allTextChanges = new HashSet<TextChange>(); // Some fixes require adding missing references. var allAddedProjectReferences = new HashSet<ProjectReference>(); var allAddedMetaDataReferences = new HashSet<MetadataReference>(); foreach (var getChangesTask in getChangesTasks) { var (projectChanges, textChanges) = await getChangesTask.ConfigureAwait(false); allTextChanges.UnionWith(textChanges); allAddedProjectReferences.UnionWith(projectChanges.GetAddedProjectReferences()); allAddedMetaDataReferences.UnionWith(projectChanges.GetAddedMetadataReferences()); } // Apply changes to both the project and document. var newProject = document.Project; newProject = newProject.AddMetadataReferences(allAddedMetaDataReferences); newProject = newProject.AddProjectReferences(allAddedProjectReferences); // Only consider insertion changes to reduce the chance of producing a // badly merged final document. Alphabetize the new imports, this will not // change the insertion point but will give a more correct result. The user // may still need to use organize imports afterwards. var orderedTextInserts = allTextChanges.Where(change => change.Span.IsEmpty) .OrderBy(change => change.NewText); // Capture each location where we are inserting imports as well as the total // length of the text we are inserting so that we can format the span afterwards. var insertSpans = allTextChanges .GroupBy(change => change.Span) .Select(changes => new TextSpan(changes.Key.Start, changes.Sum(change => change.NewText!.Length))); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(orderedTextInserts); var newDocument = newProject.GetRequiredDocument(document.Id).WithText(newText); // When imports are added to a code file that has no previous imports, extra // newlines are generated between each import because the fix is expecting to // separate the imports from the rest of the code file. We need to format the // imports to remove these extra newlines. return await CleanUpNewLinesAsync(newDocument, insertSpans, cancellationToken).ConfigureAwait(false); } private static async Task<Document> CleanUpNewLinesAsync(Document document, IEnumerable<TextSpan> insertSpans, CancellationToken cancellationToken) { var languageFormatter = document.GetRequiredLanguageService<ISyntaxFormattingService>(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var newDocument = document; // Since imports can be added at both the CompilationUnit and the Namespace level, // format each span individually so that we can retain each newline that was intended // to separate the import section from the other content. foreach (var insertSpan in insertSpans) { newDocument = await CleanUpNewLinesAsync(newDocument, insertSpan, languageFormatter, options, cancellationToken).ConfigureAwait(false); } return newDocument; } private static async Task<Document> CleanUpNewLinesAsync(Document document, TextSpan insertSpan, ISyntaxFormattingService languageFormatter, OptionSet optionSet, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var optionService = document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var shouldUseFormattingSpanCollapse = optionSet.GetOption(FormattingOptions.AllowDisjointSpanMerging); var options = optionSet.AsAnalyzerConfigOptions(optionService, root.Language); var textChanges = languageFormatter.Format(root, new[] { insertSpan }, shouldUseFormattingSpanCollapse, options, new[] { new CleanUpNewLinesFormatter(text) }, cancellationToken).GetTextChanges(cancellationToken); // If there are no changes then, do less work. if (textChanges.Count == 0) { return document; } // The last text change should include where the insert span ends Debug.Assert(textChanges.Last().Span.IntersectsWith(insertSpan.End)); // If there are changes then, this was a case where there were no // previous imports statements. We need to retain the final extra // newline because that separates the imports section from the rest // of the code. textChanges.RemoveAt(textChanges.Count - 1); var newText = text.WithChanges(textChanges); return document.WithText(newText); } private static async Task<(ProjectChanges, IEnumerable<TextChange>)> GetChangesForCodeActionAsync( Document document, CodeAction codeAction, ProgressTracker progressTracker, IDocumentTextDifferencingService textDiffingService, CancellationToken cancellationToken) { // CodeAction.GetChangedSolutionAsync is only implemented for code actions that can fully compute the new // solution without deferred computation or taking a dependency on the main thread. In other cases, the // implementation of GetChangedSolutionAsync will throw an exception and the code action application is // expected to apply the changes by executing the operations in GetOperationsAsync (which may have other // side effects). This code cannot assume the input CodeAction supports GetChangedSolutionAsync, so it first // attempts to apply text changes obtained from GetOperationsAsync. Two forms are supported: // // 1. GetOperationsAsync returns an empty list of operations (i.e. no changes are required) // 2. GetOperationsAsync returns a list of operations, where the first change is an ApplyChangesOperation to // change the text in the solution, and any remaining changes are deferred computation changes. // // If GetOperationsAsync does not adhere to one of these patterns, the code falls back to calling // GetChangedSolutionAsync since there is no clear way to apply the changes otherwise. var operations = await codeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false); Solution newSolution; if (operations.Length == 0) { newSolution = document.Project.Solution; } else if (operations.Length == 1 && operations[0] is ApplyChangesOperation applyChangesOperation) { newSolution = applyChangesOperation.ChangedSolution; } else { newSolution = await codeAction.GetRequiredChangedSolutionAsync( progressTracker, cancellationToken: cancellationToken).ConfigureAwait(false); } var newDocument = newSolution.GetRequiredDocument(document.Id); // Use Line differencing to reduce the possibility of changes that overwrite existing code. var textChanges = await textDiffingService.GetTextChangesAsync( document, newDocument, TextDifferenceTypes.Line, cancellationToken).ConfigureAwait(false); var projectChanges = newDocument.Project.GetChanges(document.Project); return (projectChanges, textChanges); } private sealed class CleanUpNewLinesFormatter : AbstractFormattingRule { private readonly SourceText _text; public CleanUpNewLinesFormatter(SourceText text) => _text = text; public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // Since we know the general shape of these new import statements, we simply look for where // tokens are not on the same line and force them to only be separated by a single newline. _text.GetLineAndOffset(previousToken.Span.Start, out var previousLine, out _); _text.GetLineAndOffset(currentToken.Span.Start, out var currentLine, out _); if (previousLine != currentLine) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddMissingImports { internal abstract class AbstractAddMissingImportsFeatureService : IAddMissingImportsFeatureService { protected abstract ImmutableArray<string> FixableDiagnosticIds { get; } /// <inheritdoc/> public async Task<Document> AddMissingImportsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { var analysisResult = await AnalyzeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); return await AddMissingImportsAsync(document, analysisResult, cancellationToken).ConfigureAwait(false); } /// <inheritdoc/> public async Task<Document> AddMissingImportsAsync(Document document, AddMissingImportsAnalysisResult analysisResult, CancellationToken cancellationToken) { if (analysisResult.CanAddMissingImports) { // Apply those fixes to the document. var newDocument = await ApplyFixesAsync(document, analysisResult.AddImportFixData, cancellationToken).ConfigureAwait(false); return newDocument; } return document; } /// <inheritdoc/> public async Task<AddMissingImportsAnalysisResult> AnalyzeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { // Get the diagnostics that indicate a missing import. var addImportFeatureService = document.GetRequiredLanguageService<IAddImportFeatureService>(); var solution = document.Project.Solution; var symbolSearchService = solution.Workspace.Services.GetRequiredService<ISymbolSearchService>(); // Since we are not currently considering NuGet packages, pass an empty array var packageSources = ImmutableArray<PackageSource>.Empty; var unambiguousFixes = await addImportFeatureService.GetUniqueFixesAsync( document, textSpan, FixableDiagnosticIds, symbolSearchService, searchReferenceAssemblies: true, packageSources, cancellationToken).ConfigureAwait(false); // We do not want to add project or framework references without the user's input, so filter those out. var usableFixes = unambiguousFixes.WhereAsArray(fixData => DoesNotAddReference(fixData, document.Project.Id)); return new AddMissingImportsAnalysisResult(usableFixes); } private static bool DoesNotAddReference(AddImportFixData fixData, ProjectId currentProjectId) { return (fixData.ProjectReferenceToAdd is null || fixData.ProjectReferenceToAdd == currentProjectId) && (fixData.PortableExecutableReferenceProjectId is null || fixData.PortableExecutableReferenceProjectId == currentProjectId) && string.IsNullOrEmpty(fixData.AssemblyReferenceAssemblyName); } private static async Task<Document> ApplyFixesAsync(Document document, ImmutableArray<AddImportFixData> fixes, CancellationToken cancellationToken) { if (fixes.IsEmpty) { return document; } var solution = document.Project.Solution; var progressTracker = new ProgressTracker(); var textDiffingService = solution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); var packageInstallerService = solution.Workspace.Services.GetService<IPackageInstallerService>(); var addImportService = document.GetRequiredLanguageService<IAddImportFeatureService>(); // Do not limit the results since we plan to fix all the reported issues. var codeActions = addImportService.GetCodeActionsForFixes(document, fixes, packageInstallerService, maxResults: int.MaxValue); var getChangesTasks = codeActions.Select( action => GetChangesForCodeActionAsync(document, action, progressTracker, textDiffingService, cancellationToken)); // Using Sets allows us to accumulate only the distinct changes. var allTextChanges = new HashSet<TextChange>(); // Some fixes require adding missing references. var allAddedProjectReferences = new HashSet<ProjectReference>(); var allAddedMetaDataReferences = new HashSet<MetadataReference>(); foreach (var getChangesTask in getChangesTasks) { var (projectChanges, textChanges) = await getChangesTask.ConfigureAwait(false); allTextChanges.UnionWith(textChanges); allAddedProjectReferences.UnionWith(projectChanges.GetAddedProjectReferences()); allAddedMetaDataReferences.UnionWith(projectChanges.GetAddedMetadataReferences()); } // Apply changes to both the project and document. var newProject = document.Project; newProject = newProject.AddMetadataReferences(allAddedMetaDataReferences); newProject = newProject.AddProjectReferences(allAddedProjectReferences); // Only consider insertion changes to reduce the chance of producing a // badly merged final document. Alphabetize the new imports, this will not // change the insertion point but will give a more correct result. The user // may still need to use organize imports afterwards. var orderedTextInserts = allTextChanges.Where(change => change.Span.IsEmpty) .OrderBy(change => change.NewText); // Capture each location where we are inserting imports as well as the total // length of the text we are inserting so that we can format the span afterwards. var insertSpans = allTextChanges .GroupBy(change => change.Span) .Select(changes => new TextSpan(changes.Key.Start, changes.Sum(change => change.NewText!.Length))); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(orderedTextInserts); var newDocument = newProject.GetRequiredDocument(document.Id).WithText(newText); // When imports are added to a code file that has no previous imports, extra // newlines are generated between each import because the fix is expecting to // separate the imports from the rest of the code file. We need to format the // imports to remove these extra newlines. return await CleanUpNewLinesAsync(newDocument, insertSpans, cancellationToken).ConfigureAwait(false); } private static async Task<Document> CleanUpNewLinesAsync(Document document, IEnumerable<TextSpan> insertSpans, CancellationToken cancellationToken) { var languageFormatter = document.GetRequiredLanguageService<ISyntaxFormattingService>(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var newDocument = document; // Since imports can be added at both the CompilationUnit and the Namespace level, // format each span individually so that we can retain each newline that was intended // to separate the import section from the other content. foreach (var insertSpan in insertSpans) { newDocument = await CleanUpNewLinesAsync(newDocument, insertSpan, languageFormatter, options, cancellationToken).ConfigureAwait(false); } return newDocument; } private static async Task<Document> CleanUpNewLinesAsync(Document document, TextSpan insertSpan, ISyntaxFormattingService languageFormatter, OptionSet optionSet, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var optionService = document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var shouldUseFormattingSpanCollapse = optionSet.GetOption(FormattingOptions.AllowDisjointSpanMerging); var options = optionSet.AsAnalyzerConfigOptions(optionService, root.Language); var textChanges = languageFormatter.Format(root, new[] { insertSpan }, shouldUseFormattingSpanCollapse, options, new[] { new CleanUpNewLinesFormatter(text) }, cancellationToken).GetTextChanges(cancellationToken); // If there are no changes then, do less work. if (textChanges.Count == 0) { return document; } // The last text change should include where the insert span ends Debug.Assert(textChanges.Last().Span.IntersectsWith(insertSpan.End)); // If there are changes then, this was a case where there were no // previous imports statements. We need to retain the final extra // newline because that separates the imports section from the rest // of the code. textChanges.RemoveAt(textChanges.Count - 1); var newText = text.WithChanges(textChanges); return document.WithText(newText); } private static async Task<(ProjectChanges, IEnumerable<TextChange>)> GetChangesForCodeActionAsync( Document document, CodeAction codeAction, ProgressTracker progressTracker, IDocumentTextDifferencingService textDiffingService, CancellationToken cancellationToken) { // CodeAction.GetChangedSolutionAsync is only implemented for code actions that can fully compute the new // solution without deferred computation or taking a dependency on the main thread. In other cases, the // implementation of GetChangedSolutionAsync will throw an exception and the code action application is // expected to apply the changes by executing the operations in GetOperationsAsync (which may have other // side effects). This code cannot assume the input CodeAction supports GetChangedSolutionAsync, so it first // attempts to apply text changes obtained from GetOperationsAsync. Two forms are supported: // // 1. GetOperationsAsync returns an empty list of operations (i.e. no changes are required) // 2. GetOperationsAsync returns a list of operations, where the first change is an ApplyChangesOperation to // change the text in the solution, and any remaining changes are deferred computation changes. // // If GetOperationsAsync does not adhere to one of these patterns, the code falls back to calling // GetChangedSolutionAsync since there is no clear way to apply the changes otherwise. var operations = await codeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false); Solution newSolution; if (operations.Length == 0) { newSolution = document.Project.Solution; } else if (operations.Length == 1 && operations[0] is ApplyChangesOperation applyChangesOperation) { newSolution = applyChangesOperation.ChangedSolution; } else { newSolution = await codeAction.GetRequiredChangedSolutionAsync( progressTracker, cancellationToken: cancellationToken).ConfigureAwait(false); } var newDocument = newSolution.GetRequiredDocument(document.Id); // Use Line differencing to reduce the possibility of changes that overwrite existing code. var textChanges = await textDiffingService.GetTextChangesAsync( document, newDocument, TextDifferenceTypes.Line, cancellationToken).ConfigureAwait(false); var projectChanges = newDocument.Project.GetChanges(document.Project); return (projectChanges, textChanges); } private sealed class CleanUpNewLinesFormatter : AbstractFormattingRule { private readonly SourceText _text; public CleanUpNewLinesFormatter(SourceText text) => _text = text; public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // Since we know the general shape of these new import statements, we simply look for where // tokens are not on the same line and force them to only be separated by a single newline. _text.GetLineAndOffset(previousToken.Span.Start, out var previousLine, out _); _text.GetLineAndOffset(currentToken.Span.Start, out var currentLine, out _); if (previousLine != currentLine) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } return null; } } } }
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/Remote/ServiceHub/Services/MissingImportDiscovery/RemoteMissingImportDiscoveryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteMissingImportDiscoveryService : BrokeredServiceBase, IRemoteMissingImportDiscoveryService { internal sealed class Factory : FactoryBase<IRemoteMissingImportDiscoveryService, IRemoteMissingImportDiscoveryService.ICallback> { protected override IRemoteMissingImportDiscoveryService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback) => new RemoteMissingImportDiscoveryService(arguments, callback); } private readonly RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> _callback; public RemoteMissingImportDiscoveryService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback) : base(arguments) { _callback = callback; } public ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId); var service = document.GetLanguageService<IAddImportFeatureService>(); var symbolSearchService = new SymbolSearchService(_callback, callbackId); var result = await service.GetFixesAsync( document, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); return result; }, cancellationToken); } /// <summary> /// Provides an implementation of the <see cref="ISymbolSearchService"/> on the remote side so that /// Add-Import can find results in nuget packages/reference assemblies. This works /// by remoting *from* the OOP server back to the host, which can then forward this /// appropriately to wherever the real <see cref="ISymbolSearchService"/> is running. This is necessary /// because it's not guaranteed that the real <see cref="ISymbolSearchService"/> will be running in /// the same process that is supplying the <see cref="RemoteMissingImportDiscoveryService"/>. /// /// Ideally we would not need to bounce back to the host for this. /// </summary> private sealed class SymbolSearchService : ISymbolSearchService { private readonly RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public SymbolSearchService(RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindPackagesWithTypeAsync(_callbackId, source, name, arity, cancellationToken), cancellationToken); public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindPackagesWithAssemblyAsync(_callbackId, source, assemblyName, cancellationToken), cancellationToken); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindReferenceAssembliesWithTypeAsync(_callbackId, name, arity, cancellationToken), cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteMissingImportDiscoveryService : BrokeredServiceBase, IRemoteMissingImportDiscoveryService { internal sealed class Factory : FactoryBase<IRemoteMissingImportDiscoveryService, IRemoteMissingImportDiscoveryService.ICallback> { protected override IRemoteMissingImportDiscoveryService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback) => new RemoteMissingImportDiscoveryService(arguments, callback); } private readonly RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> _callback; public RemoteMissingImportDiscoveryService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback) : base(arguments) { _callback = callback; } public ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId); var service = document.GetLanguageService<IAddImportFeatureService>(); var symbolSearchService = new SymbolSearchService(_callback, callbackId); var result = await service.GetFixesAsync( document, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); return result; }, cancellationToken); } public ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, ImmutableArray<string> diagnosticIds, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId); var service = document.GetLanguageService<IAddImportFeatureService>(); var symbolSearchService = new SymbolSearchService(_callback, callbackId); var result = await service.GetUniqueFixesAsync( document, span, diagnosticIds, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); return result; }, cancellationToken); } /// <summary> /// Provides an implementation of the <see cref="ISymbolSearchService"/> on the remote side so that /// Add-Import can find results in nuget packages/reference assemblies. This works /// by remoting *from* the OOP server back to the host, which can then forward this /// appropriately to wherever the real <see cref="ISymbolSearchService"/> is running. This is necessary /// because it's not guaranteed that the real <see cref="ISymbolSearchService"/> will be running in /// the same process that is supplying the <see cref="RemoteMissingImportDiscoveryService"/>. /// /// Ideally we would not need to bounce back to the host for this. /// </summary> private sealed class SymbolSearchService : ISymbolSearchService { private readonly RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public SymbolSearchService(RemoteCallback<IRemoteMissingImportDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindPackagesWithTypeAsync(_callbackId, source, name, arity, cancellationToken), cancellationToken); public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindPackagesWithAssemblyAsync(_callbackId, source, assemblyName, cancellationToken), cancellationToken); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.FindReferenceAssembliesWithTypeAsync(_callbackId, name, arity, cancellationToken), cancellationToken); } } }
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_Queries.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.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests { [Fact] public async Task TestSimpleQuery() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var q = [|from x in args select x|]} }", @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q = from x in args select x} }"); } [Fact] public async Task TestSimpleWhere() { await TestInRegularAndScriptAsync( @"class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = [|from n in numbers where n < 5 select n|]; } }", @"using System.Linq; class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = from n in numbers where n < 5 select n; } }"); } } }
// Licensed to the .NET Foundation under one or more 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.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests { [Fact] public async Task TestSimpleQuery() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var q = [|from x in args select x|]} }", @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q = from x in args select x} }"); } [Fact] public async Task TestSimpleWhere() { await TestInRegularAndScriptAsync( @"class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = [|from n in numbers where n < 5 select n|]; } }", @"using System.Linq; class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = from n in numbers where n < 5 select n; } }"); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/CustomDataFlowAnalysis.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal static class CustomDataFlowAnalysis<TBlockAnalysisData> { /// <summary> /// Runs dataflow analysis for the given <paramref name="analyzer"/> on the given <paramref name="controlFlowGraph"/>. /// </summary> /// <param name="controlFlowGraph">Control flow graph on which to execute analysis.</param> /// <param name="analyzer">Dataflow analyzer.</param> /// <returns>Block analysis data at the end of the exit block.</returns> /// <remarks> /// Algorithm for this CFG walker has been forked from <see cref="ControlFlowGraphBuilder"/>'s internal /// implementation for basic block reachability computation: "MarkReachableBlocks", /// we should keep them in sync as much as possible. /// </remarks> public static TBlockAnalysisData Run(ControlFlowGraph controlFlowGraph, DataFlowAnalyzer<TBlockAnalysisData> analyzer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var blocks = controlFlowGraph.Blocks; var continueDispatchAfterFinally = PooledDictionary<ControlFlowRegion, bool>.GetInstance(); var dispatchedExceptionsFromRegions = PooledHashSet<ControlFlowRegion>.GetInstance(); var firstBlockOrdinal = 0; var lastBlockOrdinal = blocks.Length - 1; var unreachableBlocksToVisit = ArrayBuilder<BasicBlock>.GetInstance(); if (analyzer.AnalyzeUnreachableBlocks) { for (var i = firstBlockOrdinal; i <= lastBlockOrdinal; i++) { if (!blocks[i].IsReachable) { unreachableBlocksToVisit.Add(blocks[i]); } } } var initialAnalysisData = analyzer.GetCurrentAnalysisData(blocks[0]); var result = RunCore(blocks, analyzer, firstBlockOrdinal, lastBlockOrdinal, initialAnalysisData, unreachableBlocksToVisit, outOfRangeBlocksToVisit: null, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, cancellationToken); Debug.Assert(unreachableBlocksToVisit.Count == 0); unreachableBlocksToVisit.Free(); continueDispatchAfterFinally.Free(); dispatchedExceptionsFromRegions.Free(); return result; } private static TBlockAnalysisData RunCore( ImmutableArray<BasicBlock> blocks, DataFlowAnalyzer<TBlockAnalysisData> analyzer, int firstBlockOrdinal, int lastBlockOrdinal, TBlockAnalysisData initialAnalysisData, ArrayBuilder<BasicBlock> unreachableBlocksToVisit, SortedSet<int> outOfRangeBlocksToVisit, PooledDictionary<ControlFlowRegion, bool> continueDispatchAfterFinally, PooledHashSet<ControlFlowRegion> dispatchedExceptionsFromRegions, CancellationToken cancellationToken) { var toVisit = new SortedSet<int>(); var firstBlock = blocks[firstBlockOrdinal]; analyzer.SetCurrentAnalysisData(firstBlock, initialAnalysisData, cancellationToken); toVisit.Add(firstBlock.Ordinal); var processedBlocks = PooledHashSet<BasicBlock>.GetInstance(); TBlockAnalysisData resultAnalysisData = default; do { cancellationToken.ThrowIfCancellationRequested(); BasicBlock current; if (toVisit.Count > 0) { var min = toVisit.Min; toVisit.Remove(min); current = blocks[min]; } else { int index; current = null; for (index = 0; index < unreachableBlocksToVisit.Count; index++) { var unreachableBlock = unreachableBlocksToVisit[index]; if (unreachableBlock.Ordinal >= firstBlockOrdinal && unreachableBlock.Ordinal <= lastBlockOrdinal) { current = unreachableBlock; break; } } if (current == null) { continue; } unreachableBlocksToVisit.RemoveAt(index); if (processedBlocks.Contains(current)) { // Already processed from a branch from another unreachable block. continue; } analyzer.SetCurrentAnalysisData(current, analyzer.GetEmptyAnalysisData(), cancellationToken); } if (current.Ordinal < firstBlockOrdinal || current.Ordinal > lastBlockOrdinal) { outOfRangeBlocksToVisit.Add(current.Ordinal); continue; } if (current.Ordinal == current.EnclosingRegion.FirstBlockOrdinal) { // We are revisiting first block of a region, so we need to again dispatch exceptions from region. dispatchedExceptionsFromRegions.Remove(current.EnclosingRegion); } var fallThroughAnalysisData = analyzer.AnalyzeBlock(current, cancellationToken); var fallThroughSuccessorIsReachable = true; if (current.ConditionKind != ControlFlowConditionKind.None) { TBlockAnalysisData conditionalSuccessorAnalysisData; (fallThroughAnalysisData, conditionalSuccessorAnalysisData) = analyzer.AnalyzeConditionalBranch(current, fallThroughAnalysisData, cancellationToken); var conditionalSuccesorIsReachable = true; if (current.BranchValue.ConstantValue.HasValue && current.BranchValue.ConstantValue.Value is bool constant) { if (constant == (current.ConditionKind == ControlFlowConditionKind.WhenTrue)) { fallThroughSuccessorIsReachable = false; } else { conditionalSuccesorIsReachable = false; } } if (conditionalSuccesorIsReachable || analyzer.AnalyzeUnreachableBlocks) { FollowBranch(current, current.ConditionalSuccessor, conditionalSuccessorAnalysisData); } } else { fallThroughAnalysisData = analyzer.AnalyzeNonConditionalBranch(current, fallThroughAnalysisData, cancellationToken); } if (fallThroughSuccessorIsReachable || analyzer.AnalyzeUnreachableBlocks) { var branch = current.FallThroughSuccessor; FollowBranch(current, branch, fallThroughAnalysisData); if (current.EnclosingRegion.Kind == ControlFlowRegionKind.Finally && current.Ordinal == lastBlockOrdinal) { continueDispatchAfterFinally[current.EnclosingRegion] = branch.Semantics != ControlFlowBranchSemantics.Throw && branch.Semantics != ControlFlowBranchSemantics.Rethrow && current.FallThroughSuccessor.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling; } } if (current.Ordinal == lastBlockOrdinal) { resultAnalysisData = fallThroughAnalysisData; } // We are using very simple approach: // If try block is reachable, we should dispatch an exception from it, even if it is empty. // To simplify implementation, we dispatch exception from every reachable basic block and rely // on dispatchedExceptionsFromRegions cache to avoid doing duplicate work. DispatchException(current.EnclosingRegion); processedBlocks.Add(current); } while (toVisit.Count != 0 || unreachableBlocksToVisit.Count != 0); return resultAnalysisData; // Local functions. void FollowBranch(BasicBlock current, ControlFlowBranch branch, TBlockAnalysisData currentAnalsisData) { if (branch == null) { return; } switch (branch.Semantics) { case ControlFlowBranchSemantics.None: case ControlFlowBranchSemantics.ProgramTermination: case ControlFlowBranchSemantics.StructuredExceptionHandling: case ControlFlowBranchSemantics.Error: Debug.Assert(branch.Destination == null); return; case ControlFlowBranchSemantics.Throw: case ControlFlowBranchSemantics.Rethrow: Debug.Assert(branch.Destination == null); StepThroughFinally(current.EnclosingRegion, destinationOrdinal: lastBlockOrdinal, ref currentAnalsisData); return; case ControlFlowBranchSemantics.Regular: case ControlFlowBranchSemantics.Return: Debug.Assert(branch.Destination != null); if (StepThroughFinally(current.EnclosingRegion, branch.Destination.Ordinal, ref currentAnalsisData)) { var destination = branch.Destination; var currentDestinationData = analyzer.GetCurrentAnalysisData(destination); var mergedAnalysisData = analyzer.Merge(currentDestinationData, currentAnalsisData, cancellationToken); // We need to analyze the destination block if both the following conditions are met: // 1. Either the current block is reachable both destination and current are non-reachable // 2. Either the new analysis data for destination has changed or destination block hasn't // been processed. if ((current.IsReachable || !destination.IsReachable) && (!analyzer.IsEqual(currentDestinationData, mergedAnalysisData) || !processedBlocks.Contains(destination))) { analyzer.SetCurrentAnalysisData(destination, mergedAnalysisData, cancellationToken); toVisit.Add(branch.Destination.Ordinal); } } return; default: throw ExceptionUtilities.UnexpectedValue(branch.Semantics); } } // Returns whether we should proceed to the destination after finallies were taken care of. bool StepThroughFinally(ControlFlowRegion region, int destinationOrdinal, ref TBlockAnalysisData currentAnalysisData) { while (!region.ContainsBlock(destinationOrdinal)) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); var enclosing = region.EnclosingRegion; if (region.Kind == ControlFlowRegionKind.Try && enclosing.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(enclosing.NestedRegions[0] == region); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!StepThroughSingleFinally(enclosing.NestedRegions[1], ref currentAnalysisData)) { // The point that continues dispatch is not reachable. Cancel the dispatch. return false; } } region = enclosing; } return true; } // Returns whether we should proceed with dispatch after finally was taken care of. bool StepThroughSingleFinally(ControlFlowRegion @finally, ref TBlockAnalysisData currentAnalysisData) { Debug.Assert(@finally.Kind == ControlFlowRegionKind.Finally); var previousAnalysisData = analyzer.GetCurrentAnalysisData(blocks[@finally.FirstBlockOrdinal]); var mergedAnalysisData = analyzer.Merge(previousAnalysisData, currentAnalysisData, cancellationToken); if (!analyzer.IsEqual(previousAnalysisData, mergedAnalysisData)) { // For simplicity, we do a complete walk of the finally/filter region in isolation // to make sure that the resume dispatch point is reachable from its beginning. // It could also be reachable through invalid branches into the finally and we don't want to consider // these cases for regular finally handling. currentAnalysisData = RunCore(blocks, analyzer, @finally.FirstBlockOrdinal, @finally.LastBlockOrdinal, mergedAnalysisData, unreachableBlocksToVisit, outOfRangeBlocksToVisit: toVisit, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, cancellationToken); } if (!continueDispatchAfterFinally.TryGetValue(@finally, out var dispatch)) { dispatch = false; continueDispatchAfterFinally.Add(@finally, false); } return dispatch; } void DispatchException(ControlFlowRegion fromRegion) { do { if (!dispatchedExceptionsFromRegions.Add(fromRegion)) { return; } var enclosing = fromRegion.Kind == ControlFlowRegionKind.Root ? null : fromRegion.EnclosingRegion; if (fromRegion.Kind == ControlFlowRegionKind.Try) { switch (enclosing.Kind) { case ControlFlowRegionKind.TryAndFinally: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); var currentAnalysisData = analyzer.GetCurrentAnalysisData(blocks[fromRegion.FirstBlockOrdinal]); if (!StepThroughSingleFinally(enclosing.NestedRegions[1], ref currentAnalysisData)) { // The point that continues dispatch is not reachable. Cancel the dispatch. return; } break; case ControlFlowRegionKind.TryAndCatch: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); DispatchExceptionThroughCatches(enclosing, startAt: 1); break; default: throw ExceptionUtilities.UnexpectedValue(enclosing.Kind); } } else if (fromRegion.Kind == ControlFlowRegionKind.Filter) { // If filter throws, dispatch is resumed at the next catch with an original exception Debug.Assert(enclosing.Kind == ControlFlowRegionKind.FilterAndHandler); var tryAndCatch = enclosing.EnclosingRegion; Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); var index = tryAndCatch.NestedRegions.IndexOf(enclosing, startIndex: 1); if (index > 0) { DispatchExceptionThroughCatches(tryAndCatch, startAt: index + 1); fromRegion = tryAndCatch; continue; } throw ExceptionUtilities.Unreachable; } fromRegion = enclosing; } while (fromRegion != null); } void DispatchExceptionThroughCatches(ControlFlowRegion tryAndCatch, int startAt) { // For simplicity, we do not try to figure out whether a catch clause definitely // handles all exceptions. Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); Debug.Assert(startAt > 0); Debug.Assert(startAt <= tryAndCatch.NestedRegions.Length); for (var i = startAt; i < tryAndCatch.NestedRegions.Length; i++) { var @catch = tryAndCatch.NestedRegions[i]; switch (@catch.Kind) { case ControlFlowRegionKind.Catch: toVisit.Add(@catch.FirstBlockOrdinal); break; case ControlFlowRegionKind.FilterAndHandler: var entryBlock = blocks[@catch.FirstBlockOrdinal]; Debug.Assert(@catch.NestedRegions[0].Kind == ControlFlowRegionKind.Filter); Debug.Assert(entryBlock.Ordinal == @catch.NestedRegions[0].FirstBlockOrdinal); toVisit.Add(entryBlock.Ordinal); break; default: throw ExceptionUtilities.UnexpectedValue(@catch.Kind); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal static class CustomDataFlowAnalysis<TBlockAnalysisData> { /// <summary> /// Runs dataflow analysis for the given <paramref name="analyzer"/> on the given <paramref name="controlFlowGraph"/>. /// </summary> /// <param name="controlFlowGraph">Control flow graph on which to execute analysis.</param> /// <param name="analyzer">Dataflow analyzer.</param> /// <returns>Block analysis data at the end of the exit block.</returns> /// <remarks> /// Algorithm for this CFG walker has been forked from <see cref="ControlFlowGraphBuilder"/>'s internal /// implementation for basic block reachability computation: "MarkReachableBlocks", /// we should keep them in sync as much as possible. /// </remarks> public static TBlockAnalysisData Run(ControlFlowGraph controlFlowGraph, DataFlowAnalyzer<TBlockAnalysisData> analyzer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var blocks = controlFlowGraph.Blocks; var continueDispatchAfterFinally = PooledDictionary<ControlFlowRegion, bool>.GetInstance(); var dispatchedExceptionsFromRegions = PooledHashSet<ControlFlowRegion>.GetInstance(); var firstBlockOrdinal = 0; var lastBlockOrdinal = blocks.Length - 1; var unreachableBlocksToVisit = ArrayBuilder<BasicBlock>.GetInstance(); if (analyzer.AnalyzeUnreachableBlocks) { for (var i = firstBlockOrdinal; i <= lastBlockOrdinal; i++) { if (!blocks[i].IsReachable) { unreachableBlocksToVisit.Add(blocks[i]); } } } var initialAnalysisData = analyzer.GetCurrentAnalysisData(blocks[0]); var result = RunCore(blocks, analyzer, firstBlockOrdinal, lastBlockOrdinal, initialAnalysisData, unreachableBlocksToVisit, outOfRangeBlocksToVisit: null, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, cancellationToken); Debug.Assert(unreachableBlocksToVisit.Count == 0); unreachableBlocksToVisit.Free(); continueDispatchAfterFinally.Free(); dispatchedExceptionsFromRegions.Free(); return result; } private static TBlockAnalysisData RunCore( ImmutableArray<BasicBlock> blocks, DataFlowAnalyzer<TBlockAnalysisData> analyzer, int firstBlockOrdinal, int lastBlockOrdinal, TBlockAnalysisData initialAnalysisData, ArrayBuilder<BasicBlock> unreachableBlocksToVisit, SortedSet<int> outOfRangeBlocksToVisit, PooledDictionary<ControlFlowRegion, bool> continueDispatchAfterFinally, PooledHashSet<ControlFlowRegion> dispatchedExceptionsFromRegions, CancellationToken cancellationToken) { var toVisit = new SortedSet<int>(); var firstBlock = blocks[firstBlockOrdinal]; analyzer.SetCurrentAnalysisData(firstBlock, initialAnalysisData, cancellationToken); toVisit.Add(firstBlock.Ordinal); var processedBlocks = PooledHashSet<BasicBlock>.GetInstance(); TBlockAnalysisData resultAnalysisData = default; do { cancellationToken.ThrowIfCancellationRequested(); BasicBlock current; if (toVisit.Count > 0) { var min = toVisit.Min; toVisit.Remove(min); current = blocks[min]; } else { int index; current = null; for (index = 0; index < unreachableBlocksToVisit.Count; index++) { var unreachableBlock = unreachableBlocksToVisit[index]; if (unreachableBlock.Ordinal >= firstBlockOrdinal && unreachableBlock.Ordinal <= lastBlockOrdinal) { current = unreachableBlock; break; } } if (current == null) { continue; } unreachableBlocksToVisit.RemoveAt(index); if (processedBlocks.Contains(current)) { // Already processed from a branch from another unreachable block. continue; } analyzer.SetCurrentAnalysisData(current, analyzer.GetEmptyAnalysisData(), cancellationToken); } if (current.Ordinal < firstBlockOrdinal || current.Ordinal > lastBlockOrdinal) { outOfRangeBlocksToVisit.Add(current.Ordinal); continue; } if (current.Ordinal == current.EnclosingRegion.FirstBlockOrdinal) { // We are revisiting first block of a region, so we need to again dispatch exceptions from region. dispatchedExceptionsFromRegions.Remove(current.EnclosingRegion); } var fallThroughAnalysisData = analyzer.AnalyzeBlock(current, cancellationToken); var fallThroughSuccessorIsReachable = true; if (current.ConditionKind != ControlFlowConditionKind.None) { TBlockAnalysisData conditionalSuccessorAnalysisData; (fallThroughAnalysisData, conditionalSuccessorAnalysisData) = analyzer.AnalyzeConditionalBranch(current, fallThroughAnalysisData, cancellationToken); var conditionalSuccesorIsReachable = true; if (current.BranchValue.ConstantValue.HasValue && current.BranchValue.ConstantValue.Value is bool constant) { if (constant == (current.ConditionKind == ControlFlowConditionKind.WhenTrue)) { fallThroughSuccessorIsReachable = false; } else { conditionalSuccesorIsReachable = false; } } if (conditionalSuccesorIsReachable || analyzer.AnalyzeUnreachableBlocks) { FollowBranch(current, current.ConditionalSuccessor, conditionalSuccessorAnalysisData); } } else { fallThroughAnalysisData = analyzer.AnalyzeNonConditionalBranch(current, fallThroughAnalysisData, cancellationToken); } if (fallThroughSuccessorIsReachable || analyzer.AnalyzeUnreachableBlocks) { var branch = current.FallThroughSuccessor; FollowBranch(current, branch, fallThroughAnalysisData); if (current.EnclosingRegion.Kind == ControlFlowRegionKind.Finally && current.Ordinal == lastBlockOrdinal) { continueDispatchAfterFinally[current.EnclosingRegion] = branch.Semantics != ControlFlowBranchSemantics.Throw && branch.Semantics != ControlFlowBranchSemantics.Rethrow && current.FallThroughSuccessor.Semantics == ControlFlowBranchSemantics.StructuredExceptionHandling; } } if (current.Ordinal == lastBlockOrdinal) { resultAnalysisData = fallThroughAnalysisData; } // We are using very simple approach: // If try block is reachable, we should dispatch an exception from it, even if it is empty. // To simplify implementation, we dispatch exception from every reachable basic block and rely // on dispatchedExceptionsFromRegions cache to avoid doing duplicate work. DispatchException(current.EnclosingRegion); processedBlocks.Add(current); } while (toVisit.Count != 0 || unreachableBlocksToVisit.Count != 0); return resultAnalysisData; // Local functions. void FollowBranch(BasicBlock current, ControlFlowBranch branch, TBlockAnalysisData currentAnalsisData) { if (branch == null) { return; } switch (branch.Semantics) { case ControlFlowBranchSemantics.None: case ControlFlowBranchSemantics.ProgramTermination: case ControlFlowBranchSemantics.StructuredExceptionHandling: case ControlFlowBranchSemantics.Error: Debug.Assert(branch.Destination == null); return; case ControlFlowBranchSemantics.Throw: case ControlFlowBranchSemantics.Rethrow: Debug.Assert(branch.Destination == null); StepThroughFinally(current.EnclosingRegion, destinationOrdinal: lastBlockOrdinal, ref currentAnalsisData); return; case ControlFlowBranchSemantics.Regular: case ControlFlowBranchSemantics.Return: Debug.Assert(branch.Destination != null); if (StepThroughFinally(current.EnclosingRegion, branch.Destination.Ordinal, ref currentAnalsisData)) { var destination = branch.Destination; var currentDestinationData = analyzer.GetCurrentAnalysisData(destination); var mergedAnalysisData = analyzer.Merge(currentDestinationData, currentAnalsisData, cancellationToken); // We need to analyze the destination block if both the following conditions are met: // 1. Either the current block is reachable both destination and current are non-reachable // 2. Either the new analysis data for destination has changed or destination block hasn't // been processed. if ((current.IsReachable || !destination.IsReachable) && (!analyzer.IsEqual(currentDestinationData, mergedAnalysisData) || !processedBlocks.Contains(destination))) { analyzer.SetCurrentAnalysisData(destination, mergedAnalysisData, cancellationToken); toVisit.Add(branch.Destination.Ordinal); } } return; default: throw ExceptionUtilities.UnexpectedValue(branch.Semantics); } } // Returns whether we should proceed to the destination after finallies were taken care of. bool StepThroughFinally(ControlFlowRegion region, int destinationOrdinal, ref TBlockAnalysisData currentAnalysisData) { while (!region.ContainsBlock(destinationOrdinal)) { Debug.Assert(region.Kind != ControlFlowRegionKind.Root); var enclosing = region.EnclosingRegion; if (region.Kind == ControlFlowRegionKind.Try && enclosing.Kind == ControlFlowRegionKind.TryAndFinally) { Debug.Assert(enclosing.NestedRegions[0] == region); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); if (!StepThroughSingleFinally(enclosing.NestedRegions[1], ref currentAnalysisData)) { // The point that continues dispatch is not reachable. Cancel the dispatch. return false; } } region = enclosing; } return true; } // Returns whether we should proceed with dispatch after finally was taken care of. bool StepThroughSingleFinally(ControlFlowRegion @finally, ref TBlockAnalysisData currentAnalysisData) { Debug.Assert(@finally.Kind == ControlFlowRegionKind.Finally); var previousAnalysisData = analyzer.GetCurrentAnalysisData(blocks[@finally.FirstBlockOrdinal]); var mergedAnalysisData = analyzer.Merge(previousAnalysisData, currentAnalysisData, cancellationToken); if (!analyzer.IsEqual(previousAnalysisData, mergedAnalysisData)) { // For simplicity, we do a complete walk of the finally/filter region in isolation // to make sure that the resume dispatch point is reachable from its beginning. // It could also be reachable through invalid branches into the finally and we don't want to consider // these cases for regular finally handling. currentAnalysisData = RunCore(blocks, analyzer, @finally.FirstBlockOrdinal, @finally.LastBlockOrdinal, mergedAnalysisData, unreachableBlocksToVisit, outOfRangeBlocksToVisit: toVisit, continueDispatchAfterFinally, dispatchedExceptionsFromRegions, cancellationToken); } if (!continueDispatchAfterFinally.TryGetValue(@finally, out var dispatch)) { dispatch = false; continueDispatchAfterFinally.Add(@finally, false); } return dispatch; } void DispatchException(ControlFlowRegion fromRegion) { do { if (!dispatchedExceptionsFromRegions.Add(fromRegion)) { return; } var enclosing = fromRegion.Kind == ControlFlowRegionKind.Root ? null : fromRegion.EnclosingRegion; if (fromRegion.Kind == ControlFlowRegionKind.Try) { switch (enclosing.Kind) { case ControlFlowRegionKind.TryAndFinally: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); Debug.Assert(enclosing.NestedRegions[1].Kind == ControlFlowRegionKind.Finally); var currentAnalysisData = analyzer.GetCurrentAnalysisData(blocks[fromRegion.FirstBlockOrdinal]); if (!StepThroughSingleFinally(enclosing.NestedRegions[1], ref currentAnalysisData)) { // The point that continues dispatch is not reachable. Cancel the dispatch. return; } break; case ControlFlowRegionKind.TryAndCatch: Debug.Assert(enclosing.NestedRegions[0] == fromRegion); DispatchExceptionThroughCatches(enclosing, startAt: 1); break; default: throw ExceptionUtilities.UnexpectedValue(enclosing.Kind); } } else if (fromRegion.Kind == ControlFlowRegionKind.Filter) { // If filter throws, dispatch is resumed at the next catch with an original exception Debug.Assert(enclosing.Kind == ControlFlowRegionKind.FilterAndHandler); var tryAndCatch = enclosing.EnclosingRegion; Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); var index = tryAndCatch.NestedRegions.IndexOf(enclosing, startIndex: 1); if (index > 0) { DispatchExceptionThroughCatches(tryAndCatch, startAt: index + 1); fromRegion = tryAndCatch; continue; } throw ExceptionUtilities.Unreachable; } fromRegion = enclosing; } while (fromRegion != null); } void DispatchExceptionThroughCatches(ControlFlowRegion tryAndCatch, int startAt) { // For simplicity, we do not try to figure out whether a catch clause definitely // handles all exceptions. Debug.Assert(tryAndCatch.Kind == ControlFlowRegionKind.TryAndCatch); Debug.Assert(startAt > 0); Debug.Assert(startAt <= tryAndCatch.NestedRegions.Length); for (var i = startAt; i < tryAndCatch.NestedRegions.Length; i++) { var @catch = tryAndCatch.NestedRegions[i]; switch (@catch.Kind) { case ControlFlowRegionKind.Catch: toVisit.Add(@catch.FirstBlockOrdinal); break; case ControlFlowRegionKind.FilterAndHandler: var entryBlock = blocks[@catch.FirstBlockOrdinal]; Debug.Assert(@catch.NestedRegions[0].Kind == ControlFlowRegionKind.Filter); Debug.Assert(entryBlock.Ordinal == @catch.NestedRegions[0].FirstBlockOrdinal); toVisit.Add(entryBlock.Ordinal); break; default: throw ExceptionUtilities.UnexpectedValue(@catch.Kind); } } } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Portable/Syntax/DeclarationStatementSyntax.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.CSharp.Syntax { public partial class LocalDeclarationStatementSyntax : StatementSyntax { public bool IsConst { get { return this.Modifiers.Any(SyntaxKind.ConstKeyword); } } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax { public partial class LocalDeclarationStatementSyntax : StatementSyntax { public bool IsConst { get { return this.Modifiers.Any(SyntaxKind.ConstKeyword); } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Scripting/Core/Hosting/SearchPaths.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class SearchPaths : SynchronizedList<string> { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class SearchPaths : SynchronizedList<string> { } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/VisualStudio/Core/Def/Implementation/ICodeModelNavigationPointService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface ICodeModelNavigationPointService : ILanguageService { /// <summary> /// Retrieves the start point of a given node for the specified EnvDTE.vsCMPart. /// </summary> VirtualTreePoint? GetStartPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part = null); /// <summary> /// Retrieves the end point of a given node for the specified EnvDTE.vsCMPart. /// </summary> VirtualTreePoint? GetEndPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part = null); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface ICodeModelNavigationPointService : ILanguageService { /// <summary> /// Retrieves the start point of a given node for the specified EnvDTE.vsCMPart. /// </summary> VirtualTreePoint? GetStartPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part = null); /// <summary> /// Retrieves the end point of a given node for the specified EnvDTE.vsCMPart. /// </summary> VirtualTreePoint? GetEndPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part = null); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSubmissionConstructor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedSubmissionConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; internal SynthesizedSubmissionConstructor(NamedTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base(containingType) { Debug.Assert(containingType.TypeKind == TypeKind.Submission); Debug.Assert(diagnostics != null); var compilation = containingType.DeclaringCompilation; var submissionArrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object)); var useSiteInfo = submissionArrayType.GetUseSiteInfo(); diagnostics.Add(useSiteInfo, NoLocation.Singleton); _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(submissionArrayType), 0, RefKind.None, "submissionArray")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedSubmissionConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; internal SynthesizedSubmissionConstructor(NamedTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base(containingType) { Debug.Assert(containingType.TypeKind == TypeKind.Submission); Debug.Assert(diagnostics != null); var compilation = containingType.DeclaringCompilation; var submissionArrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object)); var useSiteInfo = submissionArrayType.GetUseSiteInfo(); diagnostics.Add(useSiteInfo, NoLocation.Singleton); _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(submissionArrayType), 0, RefKind.None, "submissionArray")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/Core.Wpf/Preview/PreviewReferenceHighlightingTaggerProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using System; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// Special tagger we use for previews that is told precisely which spans to /// reference highlight. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewWrittenReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewWrittenReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewDefinitionHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewDefinitionHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.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 System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using System; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// Special tagger we use for previews that is told precisely which spans to /// reference highlight. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewWrittenReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewWrittenReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewDefinitionHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewDefinitionHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.Instance) { } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Dependencies/CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.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.Debugging { internal static class PortableCustomDebugInfoKinds { public static readonly Guid AsyncMethodSteppingInformationBlob = new("54FD2AC5-E925-401A-9C2A-F94F171072F8"); public static readonly Guid StateMachineHoistedLocalScopes = new("6DA9A61E-F8C7-4874-BE62-68BC5630DF71"); public static readonly Guid DynamicLocalVariables = new("83C563C4-B4F3-47D5-B824-BA5441477EA8"); public static readonly Guid TupleElementNames = new("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710"); public static readonly Guid DefaultNamespace = new("58b2eab6-209f-4e4e-a22c-b2d0f910c782"); public static readonly Guid EncLocalSlotMap = new("755F52A8-91C5-45BE-B4B8-209571E552BD"); public static readonly Guid EncLambdaAndClosureMap = new("A643004C-0240-496F-A783-30D64F4979DE"); public static readonly Guid SourceLink = new("CC110556-A091-4D38-9FEC-25AB9A351A6A"); public static readonly Guid EmbeddedSource = new("0E8A571B-6926-466E-B4AD-8AB04611F5FE"); public static readonly Guid CompilationMetadataReferences = new("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D"); public static readonly Guid CompilationOptions = new("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8"); } }
// Licensed to the .NET Foundation under one or more 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.Debugging { internal static class PortableCustomDebugInfoKinds { public static readonly Guid AsyncMethodSteppingInformationBlob = new("54FD2AC5-E925-401A-9C2A-F94F171072F8"); public static readonly Guid StateMachineHoistedLocalScopes = new("6DA9A61E-F8C7-4874-BE62-68BC5630DF71"); public static readonly Guid DynamicLocalVariables = new("83C563C4-B4F3-47D5-B824-BA5441477EA8"); public static readonly Guid TupleElementNames = new("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710"); public static readonly Guid DefaultNamespace = new("58b2eab6-209f-4e4e-a22c-b2d0f910c782"); public static readonly Guid EncLocalSlotMap = new("755F52A8-91C5-45BE-B4B8-209571E552BD"); public static readonly Guid EncLambdaAndClosureMap = new("A643004C-0240-496F-A783-30D64F4979DE"); public static readonly Guid SourceLink = new("CC110556-A091-4D38-9FEC-25AB9A351A6A"); public static readonly Guid EmbeddedSource = new("0E8A571B-6926-466E-B4AD-8AB04611F5FE"); public static readonly Guid CompilationMetadataReferences = new("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D"); public static readonly Guid CompilationOptions = new("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8"); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Portable/Syntax/ThrowStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ThrowStatementSyntax { public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, throwKeyword, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ThrowStatementSyntax { public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, throwKeyword, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.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.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodAsynchronous { public partial class MakeMethodAsynchronousTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeMethodAsynchronousTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeMethodAsynchronousCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] public async Task AwaitInTaskMainMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task Main() { await Task.Delay(1); } }"; await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)); // no option offered to keep void await TestActionCountAsync(initial, count: 1, new TestParameters(compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() { var initial = @"using System; using System.Threading.Tasks; class Program { public void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public async void Main() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInVoidMethodWithModifiers2() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodNoModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/Task/*Comment*/Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/async Task/*Comment*/Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaFunction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = () => [|await Task.Run(a);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = async () => await Task.Run(a); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaAction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = async () => await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod() { var initial = @"using System.Threading.Tasks; class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod2() { var initial = @"using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod3() { var initial = @"using System.Threading.Tasks; class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod4() { var initial = @"using System.Threading.Tasks; class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod5() { var initial = @"class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod6() { var initial = @"class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod7() { var initial = @"class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod8() { var initial = @"class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod9() { var initial = @"class Program { Program Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<Program> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod10() { var initial = @"class Program { asdf Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<asdf> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return local(); IEnumerable<int> local() { yield return 1; } } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return local(); IEnumerable<int> local() { yield return 1; } } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerator<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInMember() { var code = @"using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate3() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task NullNodeCrash() { await TestMissingInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { static async void Main() { try { [|await|] await Task.Delay(100); } finally { } } }"); } [WorkItem(17470, "https://github.com/dotnet/roslyn/issues/17470")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInValueTaskMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { ValueTask<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { async ValueTask<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInValueTaskWithoutGenericMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { ValueTask Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { async ValueTask Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task AddAsyncInLocalFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async Task M2Async() { await M3Async(); } } async Task<int> M3Async() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepVoidReturn() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async void M2() { await M3Async(); } } async Task<int> M3Async() { return 1; } }", index: 1); } [Theory] [InlineData(0, "void", "Task", "M2Async")] [InlineData(1, "void", "void", "M2")] [InlineData(0, "int", "Task<int>", "M2Async")] [InlineData(0, "Task", "Task", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {initialReturn} /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Theory] [InlineData("", 0, "Task", "M2Async")] [InlineData("", 1, "void", "M2")] [InlineData("public", 0, "Task", "M2Async")] [InlineData("public", 1, "void", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitUsing() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await using (var x = new object())|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await using (var x = new object()) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularUsing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using (var x = new object())|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEach() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var n in new int[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEach() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var n in new int[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var (a, b) in new(int, int)[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var (a, b) in new(int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEachVariable() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var (a, b) in new(int, int)[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithNullableReturn() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { string? M() { [|await Task.Delay(1);|] return null; } }", @"#nullable enable using System.Threading.Tasks; class C { async Task<string?> MAsync() { await Task.Delay(1); return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumerableMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumeratorMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodAsynchronous { public partial class MakeMethodAsynchronousTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeMethodAsynchronousTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeMethodAsynchronousCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] public async Task AwaitInTaskMainMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task Main() { await Task.Delay(1); } }"; await TestAsync(initial, expected, parseOptions: CSharpParseOptions.Default, compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication)); // no option offered to keep void await TestActionCountAsync(initial, count: 1, new TestParameters(compilationOptions: new CSharpCompilationOptions(OutputKind.ConsoleApplication))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(26312, "https://github.com/dotnet/roslyn/issues/26312")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInVoidMainMethodWithModifiers_NotEntryPoint() { var initial = @"using System; using System.Threading.Tasks; class Program { public void Main() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public async void Main() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInVoidMethodWithModifiers2() { var initial = @"using System; using System.Threading.Tasks; class Program { public static void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public static async Task TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodNoModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInTaskMethodWithModifiers() { var initial = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/Task/*Comment*/Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { public/*Comment*/static/*Comment*/async Task/*Comment*/Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaFunction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = () => [|await Task.Run(a);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => Console.WriteLine(); Func<Task> b = async () => await Task.Run(a); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInLambdaAction() { var initial = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = () => [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Action a = async () => await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod() { var initial = @"using System.Threading.Tasks; class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod2() { var initial = @"using System.Threading.Tasks; class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod3() { var initial = @"using System.Threading.Tasks; class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod4() { var initial = @"using System.Threading.Tasks; class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod5() { var initial = @"class Program { void Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async void Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod6() { var initial = @"class Program { Task Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInNonAsyncMethod7() { var initial = @"class Program { Task<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async Task<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod8() { var initial = @"class Program { int Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<int> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod9() { var initial = @"class Program { Program Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; class Program { async Task<Program> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInNonAsyncMethod10() { var initial = @"class Program { asdf Test() { [|await Task.Delay(1);|] } }"; var expected = @"class Program { async System.Threading.Tasks.Task<asdf> TestAsync() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodMissingIAsyncEnumerableType() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> TestAsync() { yield return 1; await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumerableMethodWithYieldInsideLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<int> Test() { [|await Task.Delay(1);|] return local(); IEnumerable<int> local() { yield return 1; } } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerable<int>> TestAsync() { await Task.Delay(1); return local(); IEnumerable<int> local() { yield return 1; } } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethodWithReturn() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { [|await Task.Delay(1);|] return null; } }"; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async Task<IEnumerator<int>> TestAsync() { await Task.Delay(1); return null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task BadAwaitInEnumeratorLocalFunction() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { IEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { void M() { async IAsyncEnumerator<int> TestAsync() { yield return 1; await Task.Delay(1); } } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumerableMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerable<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task BadAwaitInIAsyncEnumeratorMethod() { var initial = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { IAsyncEnumerator<int> Test() { yield return 1; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<int> Test() { yield return 1; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInMember() { var code = @"using System.Threading.Tasks; class Program { var x = [|await Task.Delay(3)|]; }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private async void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AddAsyncInDelegate3() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(delegate () { [|await Task.Delay(1000)|]; return ""Test""; }); } }", @"using System; using System.Threading.Tasks; class Program { private void method() { string content = await Task<String>.Run(async delegate () { await Task.Delay(1000); return ""Test""; }); } }"); } [WorkItem(6477, @"https://github.com/dotnet/roslyn/issues/6477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task NullNodeCrash() { await TestMissingInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { static async void Main() { try { [|await|] await Task.Delay(100); } finally { } } }"); } [WorkItem(17470, "https://github.com/dotnet/roslyn/issues/17470")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AwaitInValueTaskMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { ValueTask<int> Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask<T> { } } class Program { async ValueTask<int> Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task AwaitInValueTaskWithoutGenericMethod() { var initial = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { ValueTask Test() { [|await Task.Delay(1);|] } }"; var expected = @"using System; using System.Threading.Tasks; namespace System.Threading.Tasks { struct ValueTask { } } class Program { async ValueTask Test() { await Task.Delay(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task AddAsyncInLocalFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async Task M2Async() { await M3Async(); } } async Task<int> M3Async() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepVoidReturn() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { public void M1() { void M2() { [|await M3Async();|] } } async Task<int> M3Async() { return 1; } }", @"using System.Threading.Tasks; class C { public void M1() { async void M2() { await M3Async(); } } async Task<int> M3Async() { return 1; } }", index: 1); } [Theory] [InlineData(0, "void", "Task", "M2Async")] [InlineData(1, "void", "void", "M2")] [InlineData(0, "int", "Task<int>", "M2Async")] [InlineData(0, "Task", "Task", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {initialReturn} /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Theory] [InlineData("", 0, "Task", "M2Async")] [InlineData("", 1, "void", "M2")] [InlineData("public", 0, "Task", "M2Async")] [InlineData("public", 1, "void", "M2")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] [WorkItem(33082, "https://github.com/dotnet/roslyn/issues/33082")] public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName) { await TestInRegularAndScriptAsync( $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/ {{ [|await M3Async();|] }} async Task<int> M3Async() {{ return 1; }} }}", $@"using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/ {{ await M3Async(); }} async Task<int> M3Async() {{ return 1; }} }}", index: codeFixIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitUsing() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await using (var x = new object())|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await using (var x = new object()) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularUsing() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|using (var x = new object())|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEach() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var n in new int[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEach() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var n in new int[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithAwaitForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { [|await foreach (var (a, b) in new(int, int)[] { })|] { } } }", @"using System.Threading.Tasks; class C { async Task MAsync() { await foreach (var (a, b) in new(int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithRegularForEachVariable() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|foreach (var (a, b) in new(int, int)[] { })|] { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task MethodWithNullableReturn() { await TestInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { string? M() { [|await Task.Delay(1);|] return null; } }", @"#nullable enable using System.Threading.Tasks; class C { async Task<string?> MAsync() { await Task.Delay(1); return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumerableMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerable<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerable<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] public async Task EnumeratorMethodWithNullableType() { var initial = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { IEnumerator<string?> Test() { yield return string.Empty; [|await Task.Delay(1);|] } }" + IAsyncEnumerable; var expected = @"#nullable enable using System.Threading.Tasks; using System.Collections.Generic; class Program { async IAsyncEnumerator<string?> TestAsync() { yield return string.Empty; await Task.Delay(1); } }" + IAsyncEnumerable; await TestInRegularAndScriptAsync(initial, expected); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/ExpressionEvaluator/Core/Test/FunctionResolver/ParameterComparer.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; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class ParameterComparer : IEqualityComparer<ParameterSignature> { internal static readonly ParameterComparer Instance = new ParameterComparer(); public bool Equals(ParameterSignature x, ParameterSignature y) { return TypeComparer.Instance.Equals(x.Type, y.Type); } public int GetHashCode(ParameterSignature obj) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class ParameterComparer : IEqualityComparer<ParameterSignature> { internal static readonly ParameterComparer Instance = new ParameterComparer(); public bool Equals(ParameterSignature x, ParameterSignature y) { return TypeComparer.Instance.Equals(x.Type, y.Type); } public int GetHashCode(ParameterSignature obj) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpCommentSelectionTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat1() { var code = @"class A { [| // void Method ( ) // { // // }|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat2() { var code = @"class A { [| /* void Method ( ) { } */|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentSingleLineCommentInPseudoBlockComment() { var code = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { //[|int x = 0;|] } /* Hello world */ }"; var expected = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { int x = 0; } /* Hello world */ }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat3() { var code = @"class A { [| // void Method ( ) |] [| // { |] [| // |] [| // } |] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } private static void UncommentSelection(string markup, string expected) { using var workspace = TestWorkspace.CreateCSharp(markup); var doc = workspace.Documents.First(); SetupSelection(doc.GetTextView(), doc.SelectedSpans.Select(s => Span.FromBounds(s.Start, s.End))); var commandHandler = new CommentUncommentSelectionCommandHandler( workspace.ExportProvider.GetExportedValue<ITextUndoHistoryRegistry>(), workspace.ExportProvider.GetExportedValue<IEditorOperationsFactoryService>()); var textView = doc.GetTextView(); var textBuffer = doc.GetTextBuffer(); commandHandler.ExecuteCommand(textView, textBuffer, Operation.Uncomment, TestCommandExecutionContext.Create()); Assert.Equal(expected, doc.GetTextBuffer().CurrentSnapshot.GetText()); } private static void SetupSelection(IWpfTextView textView, IEnumerable<Span> spans) { var snapshot = textView.TextSnapshot; if (spans.Count() == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpCommentSelectionTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat1() { var code = @"class A { [| // void Method ( ) // { // // }|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat2() { var code = @"class A { [| /* void Method ( ) { } */|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentSingleLineCommentInPseudoBlockComment() { var code = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { //[|int x = 0;|] } /* Hello world */ }"; var expected = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { int x = 0; } /* Hello world */ }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat3() { var code = @"class A { [| // void Method ( ) |] [| // { |] [| // |] [| // } |] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } private static void UncommentSelection(string markup, string expected) { using var workspace = TestWorkspace.CreateCSharp(markup); var doc = workspace.Documents.First(); SetupSelection(doc.GetTextView(), doc.SelectedSpans.Select(s => Span.FromBounds(s.Start, s.End))); var commandHandler = new CommentUncommentSelectionCommandHandler( workspace.ExportProvider.GetExportedValue<ITextUndoHistoryRegistry>(), workspace.ExportProvider.GetExportedValue<IEditorOperationsFactoryService>()); var textView = doc.GetTextView(); var textBuffer = doc.GetTextBuffer(); commandHandler.ExecuteCommand(textView, textBuffer, Operation.Uncomment, TestCommandExecutionContext.Create()); Assert.Equal(expected, doc.GetTextBuffer().CurrentSnapshot.GetText()); } private static void SetupSelection(IWpfTextView textView, IEnumerable<Span> spans) { var snapshot = textView.TextSnapshot; if (spans.Count() == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/TestWriter.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.IO; using System.Linq; using System.Threading; namespace CSharpSyntaxGenerator { internal class TestWriter : AbstractFileWriter { private TestWriter(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) : base(writer, tree, cancellationToken) { } public static void Write(TextWriter writer, Tree tree) { new TestWriter(writer, tree).WriteFile(); } private void WriteFile() { WriteLine("// <auto-generated />"); WriteLine(); WriteLine("using Microsoft.CodeAnalysis.CSharp.Syntax;"); WriteLine("using Roslyn.Utilities;"); WriteLine("using Xunit;"); WriteLine("using InternalSyntaxFactory = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory;"); WriteLine(); WriteLine("namespace Microsoft.CodeAnalysis.CSharp.UnitTests"); OpenBlock(); WriteLine(); WriteLine("public partial class GreenNodeTests"); OpenBlock(); WriteLine("#region Green Generators"); WriteNodeGenerators(isGreen: true); WriteLine("#endregion Green Generators"); WriteLine(); WriteLine("#region Green Factory and Property Tests"); WriteFactoryPropertyTests(isGreen: true); WriteLine("#endregion Green Factory and Property Tests"); WriteLine(); WriteLine("#region Green Rewriters"); WriteRewriterTests(); WriteLine("#endregion Green Rewriters"); CloseBlock(); WriteLine(); WriteLine("public partial class RedNodeTests"); OpenBlock(); WriteLine("#region Red Generators"); WriteNodeGenerators(isGreen: false); WriteLine("#endregion Red Generators"); WriteLine(); WriteLine("#region Red Factory and Property Tests"); WriteFactoryPropertyTests(isGreen: false); WriteLine("#endregion Red Factory and Property Tests"); WriteLine(); WriteLine("#region Red Rewriters"); WriteRewriterTests(); WriteLine("#endregion Red Rewriters"); CloseBlock(); CloseBlock(); } private void WriteNodeGenerators(bool isGreen) { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteNodeGenerator((Node)node, isGreen); } } private void WriteNodeGenerator(Node node, bool isGreen) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var internalNamespace = isGreen ? "Microsoft.CodeAnalysis.Syntax.InternalSyntax." : ""; var csharpNamespace = isGreen ? "Syntax.InternalSyntax." : ""; var syntaxFactory = isGreen ? "InternalSyntaxFactory" : "SyntaxFactory"; var strippedName = StripPost(node.Name, "Syntax"); WriteLine($"private static {csharpNamespace}{node.Name} Generate{strippedName}()"); Write($" => {syntaxFactory}.{strippedName}("); //instantiate node bool first = true; if (node.Kinds.Count > 1) { Write($"SyntaxKind.{node.Kinds[0].Name}"); //TODO: other kinds? first = false; } foreach (var field in nodeFields) { if (!first) { Write(", "); } first = false; if (IsOptional(field)) { if (isGreen) { Write("null"); } else { Write($"default({field.Type})"); } } else if (IsAnyList(field.Type)) { string typeName; if (isGreen) { typeName = internalNamespace + field.Type.Replace("<", "<" + csharpNamespace); } else { typeName = (field.Type == "SyntaxList<SyntaxToken>") ? "SyntaxTokenList" : field.Type; } Write($"new {typeName}()"); } else if (field.Type == "SyntaxToken") { var kind = ChooseValidKind(field, node); var leadingTrivia = isGreen ? "null, " : string.Empty; var trailingTrivia = isGreen ? ", null" : string.Empty; if (kind == "IdentifierToken") { Write($"{syntaxFactory}.Identifier(\"{field.Name}\")"); } else if (kind == "StringLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"string\", \"string\"{trailingTrivia})"); } else if (kind == "CharacterLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"a\", 'a'{trailingTrivia})"); } else if (kind == "NumericLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"1\", 1{trailingTrivia})"); } else { Write($"{syntaxFactory}.Token(SyntaxKind.{kind})"); } } else if (field.Type == "CSharpSyntaxNode") { Write($"{syntaxFactory}.IdentifierName({syntaxFactory}.Identifier(\"{field.Name}\"))"); } else { //drill down to a concrete type var type = field.Type; while (true) { var subTypes = ChildMap[type]; if (!subTypes.Any()) { break; } type = subTypes.First(); } Write($"Generate{StripPost(type, "Syntax")}()"); } } foreach (var field in valueFields) { if (!first) { Write(", "); } first = false; Write($"new {field.Type}()"); } WriteLine(");"); } private void WriteFactoryPropertyTests(bool isGreen) { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteFactoryPropertyTest((Node)node, isGreen); } } private void WriteFactoryPropertyTest(Node node, bool isGreen) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}FactoryAndProperties()"); OpenBlock(); WriteLine($"var node = Generate{strippedName}();"); WriteLine(); //check properties { string withStat = null; foreach (var field in nodeFields) { if (IsOptional(field)) { if (!isGreen && field.Type == "SyntaxToken") { WriteLine($"Assert.Equal(SyntaxKind.None, node.{field.Name}.Kind());"); } else { WriteLine($"Assert.Null(node.{field.Name});"); } } else if (field.Type == "SyntaxToken") { var kind = ChooseValidKind(field, node); if (!isGreen) { WriteLine($"Assert.Equal(SyntaxKind.{kind}, node.{field.Name}.Kind());"); } else { WriteLine($"Assert.Equal(SyntaxKind.{kind}, node.{field.Name}.Kind);"); } } else { if (field.Type == "SyntaxToken") { WriteLine($"Assert.NotEqual(default, node.{field.Name});"); } else if ( field.Type == "SyntaxTokenList" || field.Type.StartsWith("SyntaxList<") || field.Type.StartsWith("SeparatedSyntaxList<")) { WriteLine($"Assert.Equal(default, node.{field.Name});"); } else { WriteLine($"Assert.NotNull(node.{field.Name});"); } } if (!isGreen) { withStat += $".With{field.Name}(node.{field.Name})"; } } foreach (var field in valueFields) { WriteLine($"Assert.Equal(new {field.Type}(), node.{field.Name});"); if (!isGreen) { withStat += $".With{field.Name}(node.{field.Name})"; } } if (!isGreen && withStat != null) { WriteLine($"var newNode = node{withStat};"); WriteLine("Assert.Equal(node, newNode);"); } } if (isGreen) { WriteLine(); WriteLine("AttachAndCheckDiagnostics(node);"); } CloseBlock(); } private void WriteRewriterTests() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteTokenDeleteRewriterTest((Node)node); WriteLine(); WriteIdentityRewriterTest((Node)node); } } private void WriteTokenDeleteRewriterTest(Node node) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}TokenDeleteRewriter()"); OpenBlock(); WriteLine($"var oldNode = Generate{strippedName}();"); WriteLine("var rewriter = new TokenDeleteRewriter();"); WriteLine("var newNode = rewriter.Visit(oldNode);"); WriteLine(); WriteLine("if(!oldNode.IsMissing)"); OpenBlock(); WriteLine("Assert.NotEqual(oldNode, newNode);"); CloseBlock(); WriteLine(); WriteLine("Assert.NotNull(newNode);"); WriteLine("Assert.True(newNode.IsMissing, \"No tokens => missing\");"); CloseBlock(); } private void WriteIdentityRewriterTest(Node node) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}IdentityRewriter()"); OpenBlock(); WriteLine($"var oldNode = Generate{strippedName}();"); WriteLine("var rewriter = new IdentityRewriter();"); WriteLine("var newNode = rewriter.Visit(oldNode);"); WriteLine(); WriteLine("Assert.Same(oldNode, newNode);"); CloseBlock(); } //guess a reasonable kind if there are no constraints private string ChooseValidKind(Field field, Node nd) { var fieldKinds = GetKindsOfFieldOrNearestParent(nd, field); return fieldKinds?.Any() == true ? fieldKinds[0].Name : "IdentifierToken"; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; namespace CSharpSyntaxGenerator { internal class TestWriter : AbstractFileWriter { private TestWriter(TextWriter writer, Tree tree, CancellationToken cancellationToken = default) : base(writer, tree, cancellationToken) { } public static void Write(TextWriter writer, Tree tree) { new TestWriter(writer, tree).WriteFile(); } private void WriteFile() { WriteLine("// <auto-generated />"); WriteLine(); WriteLine("using Microsoft.CodeAnalysis.CSharp.Syntax;"); WriteLine("using Roslyn.Utilities;"); WriteLine("using Xunit;"); WriteLine("using InternalSyntaxFactory = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.SyntaxFactory;"); WriteLine(); WriteLine("namespace Microsoft.CodeAnalysis.CSharp.UnitTests"); OpenBlock(); WriteLine(); WriteLine("public partial class GreenNodeTests"); OpenBlock(); WriteLine("#region Green Generators"); WriteNodeGenerators(isGreen: true); WriteLine("#endregion Green Generators"); WriteLine(); WriteLine("#region Green Factory and Property Tests"); WriteFactoryPropertyTests(isGreen: true); WriteLine("#endregion Green Factory and Property Tests"); WriteLine(); WriteLine("#region Green Rewriters"); WriteRewriterTests(); WriteLine("#endregion Green Rewriters"); CloseBlock(); WriteLine(); WriteLine("public partial class RedNodeTests"); OpenBlock(); WriteLine("#region Red Generators"); WriteNodeGenerators(isGreen: false); WriteLine("#endregion Red Generators"); WriteLine(); WriteLine("#region Red Factory and Property Tests"); WriteFactoryPropertyTests(isGreen: false); WriteLine("#endregion Red Factory and Property Tests"); WriteLine(); WriteLine("#region Red Rewriters"); WriteRewriterTests(); WriteLine("#endregion Red Rewriters"); CloseBlock(); CloseBlock(); } private void WriteNodeGenerators(bool isGreen) { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteNodeGenerator((Node)node, isGreen); } } private void WriteNodeGenerator(Node node, bool isGreen) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var internalNamespace = isGreen ? "Microsoft.CodeAnalysis.Syntax.InternalSyntax." : ""; var csharpNamespace = isGreen ? "Syntax.InternalSyntax." : ""; var syntaxFactory = isGreen ? "InternalSyntaxFactory" : "SyntaxFactory"; var strippedName = StripPost(node.Name, "Syntax"); WriteLine($"private static {csharpNamespace}{node.Name} Generate{strippedName}()"); Write($" => {syntaxFactory}.{strippedName}("); //instantiate node bool first = true; if (node.Kinds.Count > 1) { Write($"SyntaxKind.{node.Kinds[0].Name}"); //TODO: other kinds? first = false; } foreach (var field in nodeFields) { if (!first) { Write(", "); } first = false; if (IsOptional(field)) { if (isGreen) { Write("null"); } else { Write($"default({field.Type})"); } } else if (IsAnyList(field.Type)) { string typeName; if (isGreen) { typeName = internalNamespace + field.Type.Replace("<", "<" + csharpNamespace); } else { typeName = (field.Type == "SyntaxList<SyntaxToken>") ? "SyntaxTokenList" : field.Type; } Write($"new {typeName}()"); } else if (field.Type == "SyntaxToken") { var kind = ChooseValidKind(field, node); var leadingTrivia = isGreen ? "null, " : string.Empty; var trailingTrivia = isGreen ? ", null" : string.Empty; if (kind == "IdentifierToken") { Write($"{syntaxFactory}.Identifier(\"{field.Name}\")"); } else if (kind == "StringLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"string\", \"string\"{trailingTrivia})"); } else if (kind == "CharacterLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"a\", 'a'{trailingTrivia})"); } else if (kind == "NumericLiteralToken") { Write($"{syntaxFactory}.Literal({leadingTrivia}\"1\", 1{trailingTrivia})"); } else { Write($"{syntaxFactory}.Token(SyntaxKind.{kind})"); } } else if (field.Type == "CSharpSyntaxNode") { Write($"{syntaxFactory}.IdentifierName({syntaxFactory}.Identifier(\"{field.Name}\"))"); } else { //drill down to a concrete type var type = field.Type; while (true) { var subTypes = ChildMap[type]; if (!subTypes.Any()) { break; } type = subTypes.First(); } Write($"Generate{StripPost(type, "Syntax")}()"); } } foreach (var field in valueFields) { if (!first) { Write(", "); } first = false; Write($"new {field.Type}()"); } WriteLine(");"); } private void WriteFactoryPropertyTests(bool isGreen) { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteFactoryPropertyTest((Node)node, isGreen); } } private void WriteFactoryPropertyTest(Node node, bool isGreen) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}FactoryAndProperties()"); OpenBlock(); WriteLine($"var node = Generate{strippedName}();"); WriteLine(); //check properties { string withStat = null; foreach (var field in nodeFields) { if (IsOptional(field)) { if (!isGreen && field.Type == "SyntaxToken") { WriteLine($"Assert.Equal(SyntaxKind.None, node.{field.Name}.Kind());"); } else { WriteLine($"Assert.Null(node.{field.Name});"); } } else if (field.Type == "SyntaxToken") { var kind = ChooseValidKind(field, node); if (!isGreen) { WriteLine($"Assert.Equal(SyntaxKind.{kind}, node.{field.Name}.Kind());"); } else { WriteLine($"Assert.Equal(SyntaxKind.{kind}, node.{field.Name}.Kind);"); } } else { if (field.Type == "SyntaxToken") { WriteLine($"Assert.NotEqual(default, node.{field.Name});"); } else if ( field.Type == "SyntaxTokenList" || field.Type.StartsWith("SyntaxList<") || field.Type.StartsWith("SeparatedSyntaxList<")) { WriteLine($"Assert.Equal(default, node.{field.Name});"); } else { WriteLine($"Assert.NotNull(node.{field.Name});"); } } if (!isGreen) { withStat += $".With{field.Name}(node.{field.Name})"; } } foreach (var field in valueFields) { WriteLine($"Assert.Equal(new {field.Type}(), node.{field.Name});"); if (!isGreen) { withStat += $".With{field.Name}(node.{field.Name})"; } } if (!isGreen && withStat != null) { WriteLine($"var newNode = node{withStat};"); WriteLine("Assert.Equal(node, newNode);"); } } if (isGreen) { WriteLine(); WriteLine("AttachAndCheckDiagnostics(node);"); } CloseBlock(); } private void WriteRewriterTests() { var nodes = Tree.Types.Where(n => !(n is PredefinedNode) && !(n is AbstractNode)); bool first = true; foreach (var node in nodes) { if (!first) { WriteLine(); } first = false; WriteTokenDeleteRewriterTest((Node)node); WriteLine(); WriteIdentityRewriterTest((Node)node); } } private void WriteTokenDeleteRewriterTest(Node node) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}TokenDeleteRewriter()"); OpenBlock(); WriteLine($"var oldNode = Generate{strippedName}();"); WriteLine("var rewriter = new TokenDeleteRewriter();"); WriteLine("var newNode = rewriter.Visit(oldNode);"); WriteLine(); WriteLine("if(!oldNode.IsMissing)"); OpenBlock(); WriteLine("Assert.NotEqual(oldNode, newNode);"); CloseBlock(); WriteLine(); WriteLine("Assert.NotNull(newNode);"); WriteLine("Assert.True(newNode.IsMissing, \"No tokens => missing\");"); CloseBlock(); } private void WriteIdentityRewriterTest(Node node) { var valueFields = node.Fields.Where(n => !IsNodeOrNodeList(n.Type)); var nodeFields = node.Fields.Where(n => IsNodeOrNodeList(n.Type)); var strippedName = StripPost(node.Name, "Syntax"); WriteLine("[Fact]"); WriteLine($"public void Test{strippedName}IdentityRewriter()"); OpenBlock(); WriteLine($"var oldNode = Generate{strippedName}();"); WriteLine("var rewriter = new IdentityRewriter();"); WriteLine("var newNode = rewriter.Visit(oldNode);"); WriteLine(); WriteLine("Assert.Same(oldNode, newNode);"); CloseBlock(); } //guess a reasonable kind if there are no constraints private string ChooseValidKind(Field field, Node nd) { var fieldKinds = GetKindsOfFieldOrNearestParent(nd, field); return fieldKinds?.Any() == true ? fieldKinds[0].Name : "IdentifierToken"; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrModuleInstance.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 using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Symbols; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; namespace Microsoft.VisualStudio.Debugger.Clr { public class DkmClrModuleInstance : DkmModuleInstance { internal readonly Assembly Assembly; private readonly DkmClrRuntimeInstance _runtimeInstance; private int _resolveTypeNameFailures; public DkmClrModuleInstance(DkmClrRuntimeInstance runtimeInstance, Assembly assembly, DkmModule module) : base(module) { _runtimeInstance = runtimeInstance; this.Assembly = assembly; } public Guid Mvid { get { return this.Assembly.Modules.First().ModuleVersionId; } } public DkmClrRuntimeInstance RuntimeInstance { get { return _runtimeInstance; } } public DkmProcess Process => _runtimeInstance.Process; public DkmClrType ResolveTypeName(string typeName, ReadOnlyCollection<DkmClrType> typeArguments) { var type = this.Assembly.GetType(typeName); if (type == null) { Interlocked.Increment(ref _resolveTypeNameFailures); throw new ArgumentException(); } Debug.Assert(typeArguments.Count == type.GetGenericArguments().Length); if (typeArguments.Count > 0) { var typeArgs = typeArguments.Select(t => ((TypeImpl)t.GetLmrType()).Type).ToArray(); type = type.MakeGenericType(typeArgs); } return _runtimeInstance.GetType((TypeImpl)type); } internal int ResolveTypeNameFailures { get { return _resolveTypeNameFailures; } } } }
// Licensed to the .NET Foundation under one or more 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 using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Symbols; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; namespace Microsoft.VisualStudio.Debugger.Clr { public class DkmClrModuleInstance : DkmModuleInstance { internal readonly Assembly Assembly; private readonly DkmClrRuntimeInstance _runtimeInstance; private int _resolveTypeNameFailures; public DkmClrModuleInstance(DkmClrRuntimeInstance runtimeInstance, Assembly assembly, DkmModule module) : base(module) { _runtimeInstance = runtimeInstance; this.Assembly = assembly; } public Guid Mvid { get { return this.Assembly.Modules.First().ModuleVersionId; } } public DkmClrRuntimeInstance RuntimeInstance { get { return _runtimeInstance; } } public DkmProcess Process => _runtimeInstance.Process; public DkmClrType ResolveTypeName(string typeName, ReadOnlyCollection<DkmClrType> typeArguments) { var type = this.Assembly.GetType(typeName); if (type == null) { Interlocked.Increment(ref _resolveTypeNameFailures); throw new ArgumentException(); } Debug.Assert(typeArguments.Count == type.GetGenericArguments().Length); if (typeArguments.Count > 0) { var typeArgs = typeArguments.Select(t => ((TypeImpl)t.GetLmrType()).Type).ToArray(); type = type.MakeGenericType(typeArgs); } return _runtimeInstance.GetType((TypeImpl)type); } internal int ResolveTypeNameFailures { get { return _resolveTypeNameFailures; } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/CSharp/Portable/CodeFixes/FixReturnType/CSharpFixReturnTypeCodeFixProvider.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.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.FixReturnType { /// <summary> /// Helps fix void-returning methods or local functions to return a correct type. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.FixReturnType), Shared] internal class CSharpFixReturnTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { // error CS0127: Since 'M()' returns void, a return keyword must not be followed by an object expression // error CS1997: Since 'M()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS0127", "CS1997", "CS0201"); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpFixReturnTypeCodeFixProvider() : base(supportsFixAll: false) { } internal override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; var analyzedTypes = await TryGetOldAndNewReturnTypeAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); if (analyzedTypes == default) { return; } if (IsVoid(analyzedTypes.declarationToFix) && IsVoid(analyzedTypes.fixedDeclaration)) { // Don't offer a code fix if the return type is void and return is followed by a void expression. // See https://github.com/dotnet/roslyn/issues/47089 return; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(document, diagnostics.First(), c)), diagnostics); return; static bool IsVoid(TypeSyntax typeSyntax) => typeSyntax is PredefinedTypeSyntax predefined && predefined.Keyword.IsKind(SyntaxKind.VoidKeyword); } private static async Task<(TypeSyntax declarationToFix, TypeSyntax fixedDeclaration)> TryGetOldAndNewReturnTypeAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Debug.Assert(diagnostics.Length == 1); var location = diagnostics[0].Location; var node = location.FindNode(getInnermostNodeForTie: true, cancellationToken); var returnedValue = node is ReturnStatementSyntax returnStatement ? returnStatement.Expression : node; if (returnedValue == null) { return default; } var (declarationTypeToFix, useTask) = TryGetDeclarationTypeToFix(node); if (declarationTypeToFix == null) { return default; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var returnedType = semanticModel.GetTypeInfo(returnedValue, cancellationToken).Type; if (returnedType == null) { returnedType = semanticModel.Compilation.ObjectType; } TypeSyntax fixedDeclaration; if (useTask) { var taskOfTType = semanticModel.Compilation.TaskOfTType(); if (taskOfTType is null) { return default; } fixedDeclaration = taskOfTType.Construct(returnedType).GenerateTypeSyntax(); } else { fixedDeclaration = returnedType.GenerateTypeSyntax(); } fixedDeclaration = fixedDeclaration.WithAdditionalAnnotations(Simplifier.Annotation).WithTriviaFrom(declarationTypeToFix); return (declarationTypeToFix, fixedDeclaration); } protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var (declarationTypeToFix, fixedDeclaration) = await TryGetOldAndNewReturnTypeAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); editor.ReplaceNode(declarationTypeToFix, fixedDeclaration); } private static (TypeSyntax type, bool useTask) TryGetDeclarationTypeToFix(SyntaxNode node) { return node.GetAncestors().Select(a => TryGetReturnTypeToFix(a)).FirstOrDefault(p => p != default); // Local functions static (TypeSyntax type, bool useTask) TryGetReturnTypeToFix(SyntaxNode containingMember) { switch (containingMember) { case MethodDeclarationSyntax method: // void M() { return 1; } // async Task M() { return 1; } return (method.ReturnType, IsAsync(method.Modifiers)); case LocalFunctionStatementSyntax localFunction: // void local() { return 1; } // async Task local() { return 1; } return (localFunction.ReturnType, IsAsync(localFunction.Modifiers)); default: return default; } } static bool IsAsync(SyntaxTokenList modifiers) { return modifiers.Any(SyntaxKind.AsyncKeyword); } } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Fix_return_type, createChangedDocument, CSharpFeaturesResources.Fix_return_type) { } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.FixReturnType { /// <summary> /// Helps fix void-returning methods or local functions to return a correct type. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.FixReturnType), Shared] internal class CSharpFixReturnTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { // error CS0127: Since 'M()' returns void, a return keyword must not be followed by an object expression // error CS1997: Since 'M()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS0127", "CS1997", "CS0201"); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpFixReturnTypeCodeFixProvider() : base(supportsFixAll: false) { } internal override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; var analyzedTypes = await TryGetOldAndNewReturnTypeAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); if (analyzedTypes == default) { return; } if (IsVoid(analyzedTypes.declarationToFix) && IsVoid(analyzedTypes.fixedDeclaration)) { // Don't offer a code fix if the return type is void and return is followed by a void expression. // See https://github.com/dotnet/roslyn/issues/47089 return; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(document, diagnostics.First(), c)), diagnostics); return; static bool IsVoid(TypeSyntax typeSyntax) => typeSyntax is PredefinedTypeSyntax predefined && predefined.Keyword.IsKind(SyntaxKind.VoidKeyword); } private static async Task<(TypeSyntax declarationToFix, TypeSyntax fixedDeclaration)> TryGetOldAndNewReturnTypeAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Debug.Assert(diagnostics.Length == 1); var location = diagnostics[0].Location; var node = location.FindNode(getInnermostNodeForTie: true, cancellationToken); var returnedValue = node is ReturnStatementSyntax returnStatement ? returnStatement.Expression : node; if (returnedValue == null) { return default; } var (declarationTypeToFix, useTask) = TryGetDeclarationTypeToFix(node); if (declarationTypeToFix == null) { return default; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var returnedType = semanticModel.GetTypeInfo(returnedValue, cancellationToken).Type; if (returnedType == null) { returnedType = semanticModel.Compilation.ObjectType; } TypeSyntax fixedDeclaration; if (useTask) { var taskOfTType = semanticModel.Compilation.TaskOfTType(); if (taskOfTType is null) { return default; } fixedDeclaration = taskOfTType.Construct(returnedType).GenerateTypeSyntax(); } else { fixedDeclaration = returnedType.GenerateTypeSyntax(); } fixedDeclaration = fixedDeclaration.WithAdditionalAnnotations(Simplifier.Annotation).WithTriviaFrom(declarationTypeToFix); return (declarationTypeToFix, fixedDeclaration); } protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var (declarationTypeToFix, fixedDeclaration) = await TryGetOldAndNewReturnTypeAsync(document, diagnostics, cancellationToken).ConfigureAwait(false); editor.ReplaceNode(declarationTypeToFix, fixedDeclaration); } private static (TypeSyntax type, bool useTask) TryGetDeclarationTypeToFix(SyntaxNode node) { return node.GetAncestors().Select(a => TryGetReturnTypeToFix(a)).FirstOrDefault(p => p != default); // Local functions static (TypeSyntax type, bool useTask) TryGetReturnTypeToFix(SyntaxNode containingMember) { switch (containingMember) { case MethodDeclarationSyntax method: // void M() { return 1; } // async Task M() { return 1; } return (method.ReturnType, IsAsync(method.Modifiers)); case LocalFunctionStatementSyntax localFunction: // void local() { return 1; } // async Task local() { return 1; } return (localFunction.ReturnType, IsAsync(localFunction.Modifiers)); default: return default; } } static bool IsAsync(SyntaxTokenList modifiers) { return modifiers.Any(SyntaxKind.AsyncKeyword); } } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Fix_return_type, createChangedDocument, CSharpFeaturesResources.Fix_return_type) { } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIfStatementCodeRefactoringProvider { // Converts: // if (a || b) // Console.WriteLine(); // // To: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // Converts: // if (a || b) // return; // // To: // if (a) // return; // if (b) // return; // The second case is applied if control flow quits from inside the body. protected sealed override int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds) => syntaxKinds.LogicalOrExpression; protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText) => new MyCodeAction(string.Format(FeaturesResources.Split_into_consecutive_0_statements, ifKeywordText), createChangedDocument); protected sealed override async Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var generator = document.GetLanguageService<SyntaxGenerator>(); leftCondition = leftCondition.WithAdditionalAnnotations(Formatter.Annotation); rightCondition = rightCondition.WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(root, generator); editor.ReplaceNode(ifOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, leftCondition)); if (await CanBeSeparateStatementsAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken).ConfigureAwait(false)) { // Generate: // if (a) // return; // if (b) // return; // At this point, ifLikeStatement must be a standalone if statement with no else clause. Debug.Assert(syntaxFacts.IsExecutableStatement(ifOrElseIf)); Debug.Assert(ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length == 0); var secondIfStatement = ifGenerator.WithCondition(ifOrElseIf, rightCondition) .WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed); if (!syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent)) { // In order to insert a new statement, we have to be inside a block. editor.ReplaceNode(ifOrElseIf, (currentNode, _) => generator.ScopeBlock(ImmutableArray.Create(currentNode))); } editor.InsertAfter(ifOrElseIf, secondIfStatement); } else { // Generate: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // If the if statement is not an else-if clause, we convert it to an else-if clause first (for VB). // Then we insert it right after our current if statement or else-if clause. var elseIfClause = ifGenerator.WithCondition(ifGenerator.ToElseIfClause(ifOrElseIf), rightCondition); ifGenerator.InsertElseIfClause(editor, ifOrElseIf, elseIfClause); } return editor.GetChangedRoot(); } private static async Task<bool> CanBeSeparateStatementsAsync( Document document, ISyntaxFactsService syntaxFacts, IIfLikeStatementGenerator ifGenerator, SyntaxNode ifOrElseIf, CancellationToken cancellationToken) { // In order to make separate statements, ifOrElseIf must be an if statement, not an else-if clause. if (ifGenerator.IsElseIfClause(ifOrElseIf, out _)) { return false; } // If there is an else clause, we *could* in theory separate these and move the current else clause to the second // statement, but we won't. It would break the else-if chain in an odd way. We'll insert an else-if instead. if (ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length > 0) { return false; } var insideStatements = syntaxFacts.GetStatementContainerStatements(ifOrElseIf); if (insideStatements.Count == 0) { // Even though there are no statements inside, we still can't split this into separate statements // because it would change the semantics from short-circuiting to always evaluating the second condition, // breaking code like 'if (a == null || a.InstanceMethod())'. return false; } else { // There are statements inside. We can split this into separate statements and leave out the 'else' if // control flow can't reach the end of these statements (otherwise, it would continue to the second 'if' // and in the case that both conditions are true, run the same statements twice). // This will typically look like a single return, break, continue or a throw statement. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]); return !controlFlow.EndPointIsReachable; } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIfStatementCodeRefactoringProvider { // Converts: // if (a || b) // Console.WriteLine(); // // To: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // Converts: // if (a || b) // return; // // To: // if (a) // return; // if (b) // return; // The second case is applied if control flow quits from inside the body. protected sealed override int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds) => syntaxKinds.LogicalOrExpression; protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText) => new MyCodeAction(string.Format(FeaturesResources.Split_into_consecutive_0_statements, ifKeywordText), createChangedDocument); protected sealed override async Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var generator = document.GetLanguageService<SyntaxGenerator>(); leftCondition = leftCondition.WithAdditionalAnnotations(Formatter.Annotation); rightCondition = rightCondition.WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(root, generator); editor.ReplaceNode(ifOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, leftCondition)); if (await CanBeSeparateStatementsAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken).ConfigureAwait(false)) { // Generate: // if (a) // return; // if (b) // return; // At this point, ifLikeStatement must be a standalone if statement with no else clause. Debug.Assert(syntaxFacts.IsExecutableStatement(ifOrElseIf)); Debug.Assert(ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length == 0); var secondIfStatement = ifGenerator.WithCondition(ifOrElseIf, rightCondition) .WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed); if (!syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent)) { // In order to insert a new statement, we have to be inside a block. editor.ReplaceNode(ifOrElseIf, (currentNode, _) => generator.ScopeBlock(ImmutableArray.Create(currentNode))); } editor.InsertAfter(ifOrElseIf, secondIfStatement); } else { // Generate: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // If the if statement is not an else-if clause, we convert it to an else-if clause first (for VB). // Then we insert it right after our current if statement or else-if clause. var elseIfClause = ifGenerator.WithCondition(ifGenerator.ToElseIfClause(ifOrElseIf), rightCondition); ifGenerator.InsertElseIfClause(editor, ifOrElseIf, elseIfClause); } return editor.GetChangedRoot(); } private static async Task<bool> CanBeSeparateStatementsAsync( Document document, ISyntaxFactsService syntaxFacts, IIfLikeStatementGenerator ifGenerator, SyntaxNode ifOrElseIf, CancellationToken cancellationToken) { // In order to make separate statements, ifOrElseIf must be an if statement, not an else-if clause. if (ifGenerator.IsElseIfClause(ifOrElseIf, out _)) { return false; } // If there is an else clause, we *could* in theory separate these and move the current else clause to the second // statement, but we won't. It would break the else-if chain in an odd way. We'll insert an else-if instead. if (ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length > 0) { return false; } var insideStatements = syntaxFacts.GetStatementContainerStatements(ifOrElseIf); if (insideStatements.Count == 0) { // Even though there are no statements inside, we still can't split this into separate statements // because it would change the semantics from short-circuiting to always evaluating the second condition, // breaking code like 'if (a == null || a.InstanceMethod())'. return false; } else { // There are statements inside. We can split this into separate statements and leave out the 'else' if // control flow can't reach the end of these statements (otherwise, it would continue to the second 'if' // and in the case that both conditions are true, run the same statements twice). // This will typically look like a single return, break, continue or a throw statement. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]); return !controlFlow.EndPointIsReachable; } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/Core/Portable/Syntax/SyntaxList`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A list of <see cref="SyntaxNode"/>. /// </summary> public readonly partial struct SyntaxList<TNode> : IReadOnlyList<TNode>, IEquatable<SyntaxList<TNode>> where TNode : SyntaxNode { private readonly SyntaxNode? _node; internal SyntaxList(SyntaxNode? node) { _node = node; } /// <summary> /// Creates a singleton list of syntax nodes. /// </summary> /// <param name="node">The single element node.</param> public SyntaxList(TNode? node) : this((SyntaxNode?)node) { } /// <summary> /// Creates a list of syntax nodes. /// </summary> /// <param name="nodes">A sequence of element nodes.</param> public SyntaxList(IEnumerable<TNode>? nodes) : this(CreateNode(nodes)) { } private static SyntaxNode? CreateNode(IEnumerable<TNode>? nodes) { if (nodes == null) { return null; } var collection = nodes as ICollection<TNode>; var builder = (collection != null) ? new SyntaxListBuilder<TNode>(collection.Count) : SyntaxListBuilder<TNode>.Create(); foreach (TNode node in nodes) { builder.Add(node); } return builder.ToList().Node; } internal SyntaxNode? Node { get { return _node; } } /// <summary> /// The number of nodes in the list. /// </summary> public int Count { get { return _node == null ? 0 : (_node.IsList ? _node.SlotCount : 1); } } /// <summary> /// Gets the node at the specified index. /// </summary> /// <param name="index">The zero-based index of the node to get or set.</param> /// <returns>The node at the specified index.</returns> public TNode this[int index] { get { if (_node != null) { if (_node.IsList) { if (unchecked((uint)index < (uint)_node.SlotCount)) { return (TNode)_node.GetNodeSlot(index)!; } } else if (index == 0) { return (TNode)_node; } } throw new ArgumentOutOfRangeException(nameof(index)); } } internal SyntaxNode? ItemInternal(int index) { if (_node?.IsList == true) { return _node.GetNodeSlot(index); } Debug.Assert(index == 0); return _node; } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (this.Count == 0) { return default(TextSpan); } else { return TextSpan.FromBounds(this[0].FullSpan.Start, this[this.Count - 1].FullSpan.End); } } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (this.Count == 0) { return default(TextSpan); } else { return TextSpan.FromBounds(this[0].Span.Start, this[this.Count - 1].Span.End); } } } /// <summary> /// Returns the string representation of the nodes in this list, not including /// the first node's leading trivia and the last node's trailing trivia. /// </summary> /// <returns> /// The string representation of the nodes in this list, not including /// the first node's leading trivia and the last node's trailing trivia. /// </returns> public override string ToString() { return _node != null ? _node.ToString() : string.Empty; } /// <summary> /// Returns the full string representation of the nodes in this list including /// the first node's leading trivia and the last node's trailing trivia. /// </summary> /// <returns> /// The full string representation of the nodes in this list including /// the first node's leading trivia and the last node's trailing trivia. /// </returns> public string ToFullString() { return _node != null ? _node.ToFullString() : string.Empty; } /// <summary> /// Creates a new list with the specified node added at the end. /// </summary> /// <param name="node">The node to add.</param> public SyntaxList<TNode> Add(TNode node) { return this.Insert(this.Count, node); } /// <summary> /// Creates a new list with the specified nodes added at the end. /// </summary> /// <param name="nodes">The nodes to add.</param> public SyntaxList<TNode> AddRange(IEnumerable<TNode> nodes) { return this.InsertRange(this.Count, nodes); } /// <summary> /// Creates a new list with the specified node inserted at the index. /// </summary> /// <param name="index">The index to insert at.</param> /// <param name="node">The node to insert.</param> public SyntaxList<TNode> Insert(int index, TNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return InsertRange(index, new[] { node }); } /// <summary> /// Creates a new list with the specified nodes inserted at the index. /// </summary> /// <param name="index">The index to insert at.</param> /// <param name="nodes">The nodes to insert.</param> public SyntaxList<TNode> InsertRange(int index, IEnumerable<TNode> nodes) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } if (nodes == null) { throw new ArgumentNullException(nameof(nodes)); } var list = this.ToList(); list.InsertRange(index, nodes); if (list.Count == 0) { return this; } else { return CreateList(list); } } /// <summary> /// Creates a new list with the element at specified index removed. /// </summary> /// <param name="index">The index of the element to remove.</param> public SyntaxList<TNode> RemoveAt(int index) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } return this.Remove(this[index]); } /// <summary> /// Creates a new list with the element removed. /// </summary> /// <param name="node">The element to remove.</param> public SyntaxList<TNode> Remove(TNode node) { return CreateList(this.Where(x => x != node).ToList()); } /// <summary> /// Creates a new list with the specified element replaced with the new node. /// </summary> /// <param name="nodeInList">The element to replace.</param> /// <param name="newNode">The new node.</param> public SyntaxList<TNode> Replace(TNode nodeInList, TNode newNode) { return ReplaceRange(nodeInList, new[] { newNode }); } /// <summary> /// Creates a new list with the specified element replaced with new nodes. /// </summary> /// <param name="nodeInList">The element to replace.</param> /// <param name="newNodes">The new nodes.</param> public SyntaxList<TNode> ReplaceRange(TNode nodeInList, IEnumerable<TNode> newNodes) { if (nodeInList == null) { throw new ArgumentNullException(nameof(nodeInList)); } if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } var index = this.IndexOf(nodeInList); if (index >= 0 && index < this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newNodes); return CreateList(list); } else { throw new ArgumentException(nameof(nodeInList)); } } private static SyntaxList<TNode> CreateList(List<TNode> items) { if (items.Count == 0) { return default(SyntaxList<TNode>); } var newGreen = GreenNode.CreateList(items, static n => n.Green); return new SyntaxList<TNode>(newGreen!.CreateRed()); } /// <summary> /// The first node in the list. /// </summary> public TNode First() { return this[0]; } /// <summary> /// The first node in the list or default if the list is empty. /// </summary> public TNode? FirstOrDefault() { if (this.Any()) { return this[0]; } else { return null; } } /// <summary> /// The last node in the list. /// </summary> public TNode Last() { return this[this.Count - 1]; } /// <summary> /// The last node in the list or default if the list is empty. /// </summary> public TNode? LastOrDefault() { if (this.Any()) { return this[this.Count - 1]; } else { return null; } } /// <summary> /// True if the list has at least one node. /// </summary> public bool Any() { Debug.Assert(_node == null || Count != 0); return _node != null; } internal bool All(Func<TNode, bool> predicate) { foreach (var item in this) { if (!predicate(item)) { return false; } } return true; } // for debugging private TNode[] Nodes { get { return this.ToArray(); } } /// <summary> /// Get's the enumerator for this list. /// </summary> #pragma warning disable RS0041 // uses oblivious reference types public Enumerator GetEnumerator() #pragma warning restore RS0041 // uses oblivious reference types { return new Enumerator(this); } IEnumerator<TNode> IEnumerable<TNode>.GetEnumerator() { if (this.Any()) { return new EnumeratorImpl(this); } return SpecializedCollections.EmptyEnumerator<TNode>(); } IEnumerator IEnumerable.GetEnumerator() { if (this.Any()) { return new EnumeratorImpl(this); } return SpecializedCollections.EmptyEnumerator<TNode>(); } public static bool operator ==(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node == right._node; } public static bool operator !=(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node != right._node; } public bool Equals(SyntaxList<TNode> other) { return _node == other._node; } public override bool Equals(object? obj) { return obj is SyntaxList<TNode> && Equals((SyntaxList<TNode>)obj); } public override int GetHashCode() { return _node?.GetHashCode() ?? 0; } public static implicit operator SyntaxList<TNode>(SyntaxList<SyntaxNode> nodes) { return new SyntaxList<TNode>(nodes._node); } public static implicit operator SyntaxList<SyntaxNode>(SyntaxList<TNode> nodes) { return new SyntaxList<SyntaxNode>(nodes.Node); } /// <summary> /// The index of the node in this list, or -1 if the node is not in the list. /// </summary> public int IndexOf(TNode node) { var index = 0; foreach (var child in this) { if (object.Equals(child, node)) { return index; } index++; } return -1; } public int IndexOf(Func<TNode, bool> predicate) { var index = 0; foreach (var child in this) { if (predicate(child)) { return index; } index++; } return -1; } internal int IndexOf(int rawKind) { var index = 0; foreach (var child in this) { if (child.RawKind == rawKind) { return index; } index++; } return -1; } public int LastIndexOf(TNode node) { for (int i = this.Count - 1; i >= 0; i--) { if (object.Equals(this[i], node)) { return i; } } return -1; } public int LastIndexOf(Func<TNode, bool> predicate) { for (int i = this.Count - 1; i >= 0; i--) { if (predicate(this[i])) { return i; } } return -1; } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A list of <see cref="SyntaxNode"/>. /// </summary> public readonly partial struct SyntaxList<TNode> : IReadOnlyList<TNode>, IEquatable<SyntaxList<TNode>> where TNode : SyntaxNode { private readonly SyntaxNode? _node; internal SyntaxList(SyntaxNode? node) { _node = node; } /// <summary> /// Creates a singleton list of syntax nodes. /// </summary> /// <param name="node">The single element node.</param> public SyntaxList(TNode? node) : this((SyntaxNode?)node) { } /// <summary> /// Creates a list of syntax nodes. /// </summary> /// <param name="nodes">A sequence of element nodes.</param> public SyntaxList(IEnumerable<TNode>? nodes) : this(CreateNode(nodes)) { } private static SyntaxNode? CreateNode(IEnumerable<TNode>? nodes) { if (nodes == null) { return null; } var collection = nodes as ICollection<TNode>; var builder = (collection != null) ? new SyntaxListBuilder<TNode>(collection.Count) : SyntaxListBuilder<TNode>.Create(); foreach (TNode node in nodes) { builder.Add(node); } return builder.ToList().Node; } internal SyntaxNode? Node { get { return _node; } } /// <summary> /// The number of nodes in the list. /// </summary> public int Count { get { return _node == null ? 0 : (_node.IsList ? _node.SlotCount : 1); } } /// <summary> /// Gets the node at the specified index. /// </summary> /// <param name="index">The zero-based index of the node to get or set.</param> /// <returns>The node at the specified index.</returns> public TNode this[int index] { get { if (_node != null) { if (_node.IsList) { if (unchecked((uint)index < (uint)_node.SlotCount)) { return (TNode)_node.GetNodeSlot(index)!; } } else if (index == 0) { return (TNode)_node; } } throw new ArgumentOutOfRangeException(nameof(index)); } } internal SyntaxNode? ItemInternal(int index) { if (_node?.IsList == true) { return _node.GetNodeSlot(index); } Debug.Assert(index == 0); return _node; } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (this.Count == 0) { return default(TextSpan); } else { return TextSpan.FromBounds(this[0].FullSpan.Start, this[this.Count - 1].FullSpan.End); } } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (this.Count == 0) { return default(TextSpan); } else { return TextSpan.FromBounds(this[0].Span.Start, this[this.Count - 1].Span.End); } } } /// <summary> /// Returns the string representation of the nodes in this list, not including /// the first node's leading trivia and the last node's trailing trivia. /// </summary> /// <returns> /// The string representation of the nodes in this list, not including /// the first node's leading trivia and the last node's trailing trivia. /// </returns> public override string ToString() { return _node != null ? _node.ToString() : string.Empty; } /// <summary> /// Returns the full string representation of the nodes in this list including /// the first node's leading trivia and the last node's trailing trivia. /// </summary> /// <returns> /// The full string representation of the nodes in this list including /// the first node's leading trivia and the last node's trailing trivia. /// </returns> public string ToFullString() { return _node != null ? _node.ToFullString() : string.Empty; } /// <summary> /// Creates a new list with the specified node added at the end. /// </summary> /// <param name="node">The node to add.</param> public SyntaxList<TNode> Add(TNode node) { return this.Insert(this.Count, node); } /// <summary> /// Creates a new list with the specified nodes added at the end. /// </summary> /// <param name="nodes">The nodes to add.</param> public SyntaxList<TNode> AddRange(IEnumerable<TNode> nodes) { return this.InsertRange(this.Count, nodes); } /// <summary> /// Creates a new list with the specified node inserted at the index. /// </summary> /// <param name="index">The index to insert at.</param> /// <param name="node">The node to insert.</param> public SyntaxList<TNode> Insert(int index, TNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return InsertRange(index, new[] { node }); } /// <summary> /// Creates a new list with the specified nodes inserted at the index. /// </summary> /// <param name="index">The index to insert at.</param> /// <param name="nodes">The nodes to insert.</param> public SyntaxList<TNode> InsertRange(int index, IEnumerable<TNode> nodes) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } if (nodes == null) { throw new ArgumentNullException(nameof(nodes)); } var list = this.ToList(); list.InsertRange(index, nodes); if (list.Count == 0) { return this; } else { return CreateList(list); } } /// <summary> /// Creates a new list with the element at specified index removed. /// </summary> /// <param name="index">The index of the element to remove.</param> public SyntaxList<TNode> RemoveAt(int index) { if (index < 0 || index > this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } return this.Remove(this[index]); } /// <summary> /// Creates a new list with the element removed. /// </summary> /// <param name="node">The element to remove.</param> public SyntaxList<TNode> Remove(TNode node) { return CreateList(this.Where(x => x != node).ToList()); } /// <summary> /// Creates a new list with the specified element replaced with the new node. /// </summary> /// <param name="nodeInList">The element to replace.</param> /// <param name="newNode">The new node.</param> public SyntaxList<TNode> Replace(TNode nodeInList, TNode newNode) { return ReplaceRange(nodeInList, new[] { newNode }); } /// <summary> /// Creates a new list with the specified element replaced with new nodes. /// </summary> /// <param name="nodeInList">The element to replace.</param> /// <param name="newNodes">The new nodes.</param> public SyntaxList<TNode> ReplaceRange(TNode nodeInList, IEnumerable<TNode> newNodes) { if (nodeInList == null) { throw new ArgumentNullException(nameof(nodeInList)); } if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } var index = this.IndexOf(nodeInList); if (index >= 0 && index < this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newNodes); return CreateList(list); } else { throw new ArgumentException(nameof(nodeInList)); } } private static SyntaxList<TNode> CreateList(List<TNode> items) { if (items.Count == 0) { return default(SyntaxList<TNode>); } var newGreen = GreenNode.CreateList(items, static n => n.Green); return new SyntaxList<TNode>(newGreen!.CreateRed()); } /// <summary> /// The first node in the list. /// </summary> public TNode First() { return this[0]; } /// <summary> /// The first node in the list or default if the list is empty. /// </summary> public TNode? FirstOrDefault() { if (this.Any()) { return this[0]; } else { return null; } } /// <summary> /// The last node in the list. /// </summary> public TNode Last() { return this[this.Count - 1]; } /// <summary> /// The last node in the list or default if the list is empty. /// </summary> public TNode? LastOrDefault() { if (this.Any()) { return this[this.Count - 1]; } else { return null; } } /// <summary> /// True if the list has at least one node. /// </summary> public bool Any() { Debug.Assert(_node == null || Count != 0); return _node != null; } internal bool All(Func<TNode, bool> predicate) { foreach (var item in this) { if (!predicate(item)) { return false; } } return true; } // for debugging private TNode[] Nodes { get { return this.ToArray(); } } /// <summary> /// Get's the enumerator for this list. /// </summary> #pragma warning disable RS0041 // uses oblivious reference types public Enumerator GetEnumerator() #pragma warning restore RS0041 // uses oblivious reference types { return new Enumerator(this); } IEnumerator<TNode> IEnumerable<TNode>.GetEnumerator() { if (this.Any()) { return new EnumeratorImpl(this); } return SpecializedCollections.EmptyEnumerator<TNode>(); } IEnumerator IEnumerable.GetEnumerator() { if (this.Any()) { return new EnumeratorImpl(this); } return SpecializedCollections.EmptyEnumerator<TNode>(); } public static bool operator ==(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node == right._node; } public static bool operator !=(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node != right._node; } public bool Equals(SyntaxList<TNode> other) { return _node == other._node; } public override bool Equals(object? obj) { return obj is SyntaxList<TNode> && Equals((SyntaxList<TNode>)obj); } public override int GetHashCode() { return _node?.GetHashCode() ?? 0; } public static implicit operator SyntaxList<TNode>(SyntaxList<SyntaxNode> nodes) { return new SyntaxList<TNode>(nodes._node); } public static implicit operator SyntaxList<SyntaxNode>(SyntaxList<TNode> nodes) { return new SyntaxList<SyntaxNode>(nodes.Node); } /// <summary> /// The index of the node in this list, or -1 if the node is not in the list. /// </summary> public int IndexOf(TNode node) { var index = 0; foreach (var child in this) { if (object.Equals(child, node)) { return index; } index++; } return -1; } public int IndexOf(Func<TNode, bool> predicate) { var index = 0; foreach (var child in this) { if (predicate(child)) { return index; } index++; } return -1; } internal int IndexOf(int rawKind) { var index = 0; foreach (var child in this) { if (child.RawKind == rawKind) { return index; } index++; } return -1; } public int LastIndexOf(TNode node) { for (int i = this.Count - 1; i >= 0; i--) { if (object.Equals(this[i], node)) { return i; } } return -1; } public int LastIndexOf(Func<TNode, bool> predicate) { for (int i = this.Count - 1; i >= 0; i--) { if (predicate(this[i])) { return i; } } return -1; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/Test/EditAndContinue/Helpers/MockDiagnosticAnalyzerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockDiagnosticAnalyzerService : IDiagnosticAnalyzerService { public readonly List<DocumentId> DocumentsToReanalyze = new(); public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false) => DocumentsToReanalyze.AddRange(documentIds); public DiagnosticAnalyzerInfoCache AnalyzerInfoCache => throw new NotImplementedException(); public bool ContainsDiagnostics(Workspace workspace, ProjectId projectId) => throw new NotImplementedException(); public Task ForceAnalyzeAsync(Solution solution, Action<Project> onProjectAnalyzed, ProjectId? projectId = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan? range, string? diagnosticId = null, bool includeSuppressedDiagnostics = false, Func<string, IDisposable?>? addOperationScope = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Workspace workspace, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, ArrayBuilder<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockDiagnosticAnalyzerService : IDiagnosticAnalyzerService { public readonly List<DocumentId> DocumentsToReanalyze = new(); public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false) => DocumentsToReanalyze.AddRange(documentIds); public DiagnosticAnalyzerInfoCache AnalyzerInfoCache => throw new NotImplementedException(); public bool ContainsDiagnostics(Workspace workspace, ProjectId projectId) => throw new NotImplementedException(); public Task ForceAnalyzeAsync(Solution solution, Action<Project> onProjectAnalyzed, ProjectId? projectId = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan? range, string? diagnosticId = null, bool includeSuppressedDiagnostics = false, Func<string, IDisposable?>? addOperationScope = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Workspace workspace, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); public Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, ArrayBuilder<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => throw new NotImplementedException(); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/NavigateTo/INavigateToSearchCallback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchCallback { void Done(bool isFullyLoaded); Task AddItemAsync(Project project, INavigateToSearchResult result, CancellationToken cancellationToken); void ReportProgress(int current, int maximum); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchCallback { void Done(bool isFullyLoaded); Task AddItemAsync(Project project, INavigateToSearchResult result, CancellationToken cancellationToken); void ReportProgress(int current, int maximum); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/Core/Portable/InternalUtilities/FatalError.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; using System.Threading; #if NET20 // Some APIs referenced by documentation comments are not available on .NET Framework 2.0. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved #endif #if COMPILERCORE namespace Microsoft.CodeAnalysis #else namespace Microsoft.CodeAnalysis.ErrorReporting #endif { internal static class FatalError { private static Action<Exception>? s_fatalHandler; private static Action<Exception>? s_nonFatalHandler; #pragma warning disable IDE0052 // Remove unread private members - We want to hold onto last exception to make investigation easier private static Exception? s_reportedException; private static string? s_reportedExceptionMessage; #pragma warning restore IDE0052 /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to crash the process on a fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? Handler { get { return s_fatalHandler; } set { if (s_fatalHandler != value) { Debug.Assert(s_fatalHandler == null, "Handler already set"); s_fatalHandler = value; } } } /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to NOT crash the process on a non fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? NonFatalHandler { get { return s_nonFatalHandler; } set { if (s_nonFatalHandler != value) { Debug.Assert(s_nonFatalHandler == null, "Handler already set"); s_nonFatalHandler = value; } } } // Same as setting the Handler property except that it avoids the assert. This is useful in // test code which needs to verify the handler is called in specific cases and will continually // overwrite this value. public static void OverwriteHandler(Action<Exception>? value) { s_fatalHandler = value; } private static bool IsCurrentOperationBeingCancelled(Exception exception, CancellationToken cancellationToken) => exception is OperationCanceledException && cancellationToken.IsCancellationRequested; /// <summary> /// Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled. The exception is never caught. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndPropagate(exception); } /// <summary> /// <para>Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled at the request of <paramref name="contextCancellationToken"/>. The exception is /// never caught.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndPropagate(exception); } /// <summary> /// Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and catch /// the exception, unless the operation was cancelled. /// </summary> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndCatch(exception); } /// <summary> /// <para>Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and /// catch the exception, unless the operation was cancelled at the request of /// <paramref name="contextCancellationToken"/>.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndCatch(exception); } /// <summary> /// Use in an exception filter to report a fatal error without catching the exception. /// The error is reported by calling <see cref="Handler"/>. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagate(Exception exception) { Report(exception, s_fatalHandler); return false; } /// <summary> /// Report a non-fatal error. /// Calls <see cref="NonFatalHandler"/> and doesn't pass the exception through (the method returns true). /// This is generally expected to be used within an exception filter as that allows us to /// capture data at the point the exception is thrown rather than when it is handled. /// However, it can also be used outside of an exception filter. If the exception has not /// already been thrown the method will throw and catch it itself to ensure we get a useful /// stack trace. /// </summary> /// <returns>True to catch the exception.</returns> [DebuggerHidden] public static bool ReportAndCatch(Exception exception) { Report(exception, s_nonFatalHandler); return true; } private static readonly object s_reportedMarker = new(); private static void Report(Exception exception, Action<Exception>? handler) { // hold onto last exception to make investigation easier s_reportedException = exception; s_reportedExceptionMessage = exception.ToString(); if (handler == null) { return; } // only report exception once if (exception.Data[s_reportedMarker] != null) { return; } #if !NET20 if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1 && aggregate.InnerExceptions[0].Data[s_reportedMarker] != null) { return; } #endif if (!exception.Data.IsReadOnly) { exception.Data[s_reportedMarker] = s_reportedMarker; } handler.Invoke(exception); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading; #if NET20 // Some APIs referenced by documentation comments are not available on .NET Framework 2.0. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved #endif #if COMPILERCORE namespace Microsoft.CodeAnalysis #else namespace Microsoft.CodeAnalysis.ErrorReporting #endif { internal static class FatalError { private static Action<Exception>? s_fatalHandler; private static Action<Exception>? s_nonFatalHandler; #pragma warning disable IDE0052 // Remove unread private members - We want to hold onto last exception to make investigation easier private static Exception? s_reportedException; private static string? s_reportedExceptionMessage; #pragma warning restore IDE0052 /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to crash the process on a fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? Handler { get { return s_fatalHandler; } set { if (s_fatalHandler != value) { Debug.Assert(s_fatalHandler == null, "Handler already set"); s_fatalHandler = value; } } } /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to NOT crash the process on a non fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? NonFatalHandler { get { return s_nonFatalHandler; } set { if (s_nonFatalHandler != value) { Debug.Assert(s_nonFatalHandler == null, "Handler already set"); s_nonFatalHandler = value; } } } // Same as setting the Handler property except that it avoids the assert. This is useful in // test code which needs to verify the handler is called in specific cases and will continually // overwrite this value. public static void OverwriteHandler(Action<Exception>? value) { s_fatalHandler = value; } private static bool IsCurrentOperationBeingCancelled(Exception exception, CancellationToken cancellationToken) => exception is OperationCanceledException && cancellationToken.IsCancellationRequested; /// <summary> /// Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled. The exception is never caught. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndPropagate(exception); } /// <summary> /// <para>Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled at the request of <paramref name="contextCancellationToken"/>. The exception is /// never caught.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndPropagate(exception); } /// <summary> /// Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and catch /// the exception, unless the operation was cancelled. /// </summary> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndCatch(exception); } /// <summary> /// <para>Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and /// catch the exception, unless the operation was cancelled at the request of /// <paramref name="contextCancellationToken"/>.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndCatch(exception); } /// <summary> /// Use in an exception filter to report a fatal error without catching the exception. /// The error is reported by calling <see cref="Handler"/>. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagate(Exception exception) { Report(exception, s_fatalHandler); return false; } /// <summary> /// Report a non-fatal error. /// Calls <see cref="NonFatalHandler"/> and doesn't pass the exception through (the method returns true). /// This is generally expected to be used within an exception filter as that allows us to /// capture data at the point the exception is thrown rather than when it is handled. /// However, it can also be used outside of an exception filter. If the exception has not /// already been thrown the method will throw and catch it itself to ensure we get a useful /// stack trace. /// </summary> /// <returns>True to catch the exception.</returns> [DebuggerHidden] public static bool ReportAndCatch(Exception exception) { Report(exception, s_nonFatalHandler); return true; } private static readonly object s_reportedMarker = new(); private static void Report(Exception exception, Action<Exception>? handler) { // hold onto last exception to make investigation easier s_reportedException = exception; s_reportedExceptionMessage = exception.ToString(); if (handler == null) { return; } // only report exception once if (exception.Data[s_reportedMarker] != null) { return; } #if !NET20 if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1 && aggregate.InnerExceptions[0].Data[s_reportedMarker] != null) { return; } #endif if (!exception.Data.IsReadOnly) { exception.Data[s_reportedMarker] = s_reportedMarker; } handler.Invoke(exception); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/Core/EditorConfigSettings/Data/CodeStyle/CodeStyleSetting.BooleanCodeStyleSettingBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private abstract class BooleanCodeStyleSettingBase : CodeStyleSetting { private readonly string _trueValueDescription; private readonly string _falseValueDescription; public BooleanCodeStyleSettingBase(string description, string category, string? trueValueDescription, string? falseValueDescription, OptionUpdater updater) : base(description, updater) { Category = category; _trueValueDescription = trueValueDescription ?? EditorFeaturesResources.Yes; _falseValueDescription = falseValueDescription ?? EditorFeaturesResources.No; } public override string Category { get; } public override Type Type => typeof(bool); public override DiagnosticSeverity Severity => GetOption().Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden; public override string GetCurrentValue() => GetOption().Value ? _trueValueDescription : _falseValueDescription; public override object? Value => GetOption().Value; public override string[] GetValues() => new[] { _trueValueDescription, _falseValueDescription }; protected abstract CodeStyleOption2<bool> GetOption(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private abstract class BooleanCodeStyleSettingBase : CodeStyleSetting { private readonly string _trueValueDescription; private readonly string _falseValueDescription; public BooleanCodeStyleSettingBase(string description, string category, string? trueValueDescription, string? falseValueDescription, OptionUpdater updater) : base(description, updater) { Category = category; _trueValueDescription = trueValueDescription ?? EditorFeaturesResources.Yes; _falseValueDescription = falseValueDescription ?? EditorFeaturesResources.No; } public override string Category { get; } public override Type Type => typeof(bool); public override DiagnosticSeverity Severity => GetOption().Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden; public override string GetCurrentValue() => GetOption().Value ? _trueValueDescription : _falseValueDescription; public override object? Value => GetOption().Value; public override string[] GetValues() => new[] { _trueValueDescription, _falseValueDescription }; protected abstract CodeStyleOption2<bool> GetOption(); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/IndexedTypeParameterTests.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 Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IndexedTypeParameterTests { [Fact] public void TestTake() { var zero = IndexedTypeParameterSymbol.TakeSymbols(0); Assert.Equal(0, zero.Length); var five = IndexedTypeParameterSymbol.TakeSymbols(5); Assert.Equal(5, five.Length); Assert.Equal(five[0], IndexedTypeParameterSymbol.GetTypeParameter(0)); Assert.Equal(five[1], IndexedTypeParameterSymbol.GetTypeParameter(1)); Assert.Equal(five[2], IndexedTypeParameterSymbol.GetTypeParameter(2)); Assert.Equal(five[3], IndexedTypeParameterSymbol.GetTypeParameter(3)); Assert.Equal(five[4], IndexedTypeParameterSymbol.GetTypeParameter(4)); var fifty = IndexedTypeParameterSymbol.TakeSymbols(50); Assert.Equal(50, fifty.Length); // prove they are all unique var set = new HashSet<TypeParameterSymbol>(fifty); Assert.Equal(50, set.Count); var fiveHundred = IndexedTypeParameterSymbol.TakeSymbols(500); Assert.Equal(500, fiveHundred.Length); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IndexedTypeParameterTests { [Fact] public void TestTake() { var zero = IndexedTypeParameterSymbol.TakeSymbols(0); Assert.Equal(0, zero.Length); var five = IndexedTypeParameterSymbol.TakeSymbols(5); Assert.Equal(5, five.Length); Assert.Equal(five[0], IndexedTypeParameterSymbol.GetTypeParameter(0)); Assert.Equal(five[1], IndexedTypeParameterSymbol.GetTypeParameter(1)); Assert.Equal(five[2], IndexedTypeParameterSymbol.GetTypeParameter(2)); Assert.Equal(five[3], IndexedTypeParameterSymbol.GetTypeParameter(3)); Assert.Equal(five[4], IndexedTypeParameterSymbol.GetTypeParameter(4)); var fifty = IndexedTypeParameterSymbol.TakeSymbols(50); Assert.Equal(50, fifty.Length); // prove they are all unique var set = new HashSet<TypeParameterSymbol>(fifty); Assert.Equal(50, set.Count); var fiveHundred = IndexedTypeParameterSymbol.TakeSymbols(500); Assert.Equal(500, fiveHundred.Length); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/VisualStudio/CSharp/Test/PersistentStorage/Mocks/SolutionServiceMock.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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.VisualStudio.RpcContracts.Solution; using Microsoft.VisualStudio.Threading; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class SolutionServiceMock : ISolutionService { private readonly BroadcastObservable<OpenCodeContainersState> openContainerObservable = new BroadcastObservable<OpenCodeContainersState>(new OpenCodeContainersState()); public event EventHandler<ProjectsLoadedEventArgs>? ProjectsLoaded; public event EventHandler<ProjectsUnloadedEventArgs>? ProjectsUnloaded; public event EventHandler<ProjectsLoadProgressEventArgs>? ProjectLoadProgressChanged; internal Uri? SolutionFilePath { get => this.openContainerObservable.Value.SolutionFilePath; set => this.openContainerObservable.Value = this.openContainerObservable.Value with { SolutionFilePath = value }; } public ValueTask<bool[]> AreProjectsLoadedAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public Task<IDisposable> SubscribeToOpenCodeContainersStateAsync(IObserver<OpenCodeContainersState> observer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(this.openContainerObservable.Subscribe(observer)); } public Task<OpenCodeContainersState> GetOpenCodeContainersStateAsync(CancellationToken cancellationToken) => Task.FromResult(this.openContainerObservable.Value); public Task CloseSolutionAndFolderAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<IReadOnlyList<string?>> GetPropertyValuesAsync(IReadOnlyList<int> propertyIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<IReadOnlyList<string?>> GetSolutionTelemetryContextPropertyValuesAsync(IReadOnlyList<string> propertyNames, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> LoadProjectsAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<ProjectLoadResult> LoadProjectsWithResultAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> RemoveProjectsAsync(IReadOnlyList<Guid> projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public Task RequestProjectEventsAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public Task SaveSolutionFilterFileAsync(string filterFileDirectory, string filterFileName, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> UnloadProjectsAsync(Guid[] projectIds, ProjectUnloadReason unloadReason, CancellationToken cancellationToken) => throw new NotImplementedException(); internal void SimulateFolderChange(IReadOnlyList<Uri> folderPaths) => this.openContainerObservable.Value = this.openContainerObservable.Value with { OpenFolderPaths = folderPaths }; private class BroadcastObservable<T> : IObservable<T> { private readonly BroadcastBlock<T> sourceBlock = new(v => v); private T value; internal BroadcastObservable(T initialValue) { this.sourceBlock.Post(this.value = initialValue); } internal T Value { get => this.value; set => this.sourceBlock.Post(this.value = value); } public IDisposable Subscribe(IObserver<T> observer) { var actionBlock = new ActionBlock<T>(observer.OnNext); actionBlock.Completion.ContinueWith( static (t, s) => { var observer = (IObserver<T>)s!; if (t.Exception is object) { observer.OnError(t.Exception); } else { observer.OnCompleted(); } }, observer, TaskScheduler.Default).Forget(); return this.sourceBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = 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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.VisualStudio.RpcContracts.Solution; using Microsoft.VisualStudio.Threading; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class SolutionServiceMock : ISolutionService { private readonly BroadcastObservable<OpenCodeContainersState> openContainerObservable = new BroadcastObservable<OpenCodeContainersState>(new OpenCodeContainersState()); public event EventHandler<ProjectsLoadedEventArgs>? ProjectsLoaded; public event EventHandler<ProjectsUnloadedEventArgs>? ProjectsUnloaded; public event EventHandler<ProjectsLoadProgressEventArgs>? ProjectLoadProgressChanged; internal Uri? SolutionFilePath { get => this.openContainerObservable.Value.SolutionFilePath; set => this.openContainerObservable.Value = this.openContainerObservable.Value with { SolutionFilePath = value }; } public ValueTask<bool[]> AreProjectsLoadedAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public Task<IDisposable> SubscribeToOpenCodeContainersStateAsync(IObserver<OpenCodeContainersState> observer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(this.openContainerObservable.Subscribe(observer)); } public Task<OpenCodeContainersState> GetOpenCodeContainersStateAsync(CancellationToken cancellationToken) => Task.FromResult(this.openContainerObservable.Value); public Task CloseSolutionAndFolderAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<IReadOnlyList<string?>> GetPropertyValuesAsync(IReadOnlyList<int> propertyIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<IReadOnlyList<string?>> GetSolutionTelemetryContextPropertyValuesAsync(IReadOnlyList<string> propertyNames, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> LoadProjectsAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<ProjectLoadResult> LoadProjectsWithResultAsync(Guid[] projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> RemoveProjectsAsync(IReadOnlyList<Guid> projectIds, CancellationToken cancellationToken) => throw new NotImplementedException(); public Task RequestProjectEventsAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public Task SaveSolutionFilterFileAsync(string filterFileDirectory, string filterFileName, CancellationToken cancellationToken) => throw new NotImplementedException(); public ValueTask<bool> UnloadProjectsAsync(Guid[] projectIds, ProjectUnloadReason unloadReason, CancellationToken cancellationToken) => throw new NotImplementedException(); internal void SimulateFolderChange(IReadOnlyList<Uri> folderPaths) => this.openContainerObservable.Value = this.openContainerObservable.Value with { OpenFolderPaths = folderPaths }; private class BroadcastObservable<T> : IObservable<T> { private readonly BroadcastBlock<T> sourceBlock = new(v => v); private T value; internal BroadcastObservable(T initialValue) { this.sourceBlock.Post(this.value = initialValue); } internal T Value { get => this.value; set => this.sourceBlock.Post(this.value = value); } public IDisposable Subscribe(IObserver<T> observer) { var actionBlock = new ActionBlock<T>(observer.OnNext); actionBlock.Completion.ContinueWith( static (t, s) => { var observer = (IObserver<T>)s!; if (t.Exception is object) { observer.OnError(t.Exception); } else { observer.OnCompleted(); } }, observer, TaskScheduler.Default).Forget(); return this.sourceBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true }); } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.TopLevelBulkConfigureSeverityCodeAction.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 Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => true; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class ConsecutiveBracePlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConsecutiveBracePlacementDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveBracePlacement, CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Consecutive_braces_must_not_have_a_blank_between_them), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeTree); private void AnalyzeTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces); if (option.Value) return; using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack); Recurse(context, option.Notification.Severity, stack); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ArrayBuilder<SyntaxNode> stack) { var tree = context.Tree; var cancellationToken = context.CancellationToken; var root = tree.GetRoot(cancellationToken); var text = tree.GetText(cancellationToken); stack.Add(root); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Last(); stack.RemoveLast(); // Don't bother analyzing nodes that have syntax errors in them. if (current.ContainsDiagnostics && current.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) continue; foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) stack.Add(child.AsNode()!); else if (child.IsToken) ProcessToken(context, severity, text, child.AsToken()); } } } private void ProcessToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SourceText text, SyntaxToken token) { if (!HasExcessBlankLinesAfter(text, token, out var secondBrace, out _)) return; context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, secondBrace.GetLocation(), severity, additionalLocations: null, properties: null)); } public static bool HasExcessBlankLinesAfter( SourceText text, SyntaxToken token, out SyntaxToken secondBrace, out SyntaxTrivia endOfLineTrivia) { secondBrace = default; endOfLineTrivia = default; if (!token.IsKind(SyntaxKind.CloseBraceToken)) return false; var nextToken = token.GetNextToken(); if (!nextToken.IsKind(SyntaxKind.CloseBraceToken)) return false; var firstBrace = token; secondBrace = nextToken; // two } tokens. They need to be on the same line, or if they are not on subsequent lines, then there needs // to be more than whitespace between them. var lines = text.Lines; var firstBraceLine = lines.GetLineFromPosition(firstBrace.SpanStart).LineNumber; var secondBraceLine = lines.GetLineFromPosition(secondBrace.SpanStart).LineNumber; var lineCount = secondBraceLine - firstBraceLine; // if they're both on the same line, or one line apart, then there's no problem. if (lineCount <= 1) return false; // they're multiple lines apart. This i not ok if those lines are all whitespace. for (var currentLine = firstBraceLine + 1; currentLine < secondBraceLine; currentLine++) { if (!IsAllWhitespace(lines[currentLine])) return false; } endOfLineTrivia = secondBrace.LeadingTrivia.Last(t => t.IsKind(SyntaxKind.EndOfLineTrivia)); return endOfLineTrivia != default; } private static bool IsAllWhitespace(TextLine textLine) { var text = textLine.Text!; for (var i = textLine.Start; i < textLine.End; i++) { if (!SyntaxFacts.IsWhitespace(text[i])) return false; } 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. using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class ConsecutiveBracePlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConsecutiveBracePlacementDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveBracePlacement, CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Consecutive_braces_must_not_have_a_blank_between_them), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeTree); private void AnalyzeTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces); if (option.Value) return; using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack); Recurse(context, option.Notification.Severity, stack); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ArrayBuilder<SyntaxNode> stack) { var tree = context.Tree; var cancellationToken = context.CancellationToken; var root = tree.GetRoot(cancellationToken); var text = tree.GetText(cancellationToken); stack.Add(root); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Last(); stack.RemoveLast(); // Don't bother analyzing nodes that have syntax errors in them. if (current.ContainsDiagnostics && current.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) continue; foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) stack.Add(child.AsNode()!); else if (child.IsToken) ProcessToken(context, severity, text, child.AsToken()); } } } private void ProcessToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SourceText text, SyntaxToken token) { if (!HasExcessBlankLinesAfter(text, token, out var secondBrace, out _)) return; context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, secondBrace.GetLocation(), severity, additionalLocations: null, properties: null)); } public static bool HasExcessBlankLinesAfter( SourceText text, SyntaxToken token, out SyntaxToken secondBrace, out SyntaxTrivia endOfLineTrivia) { secondBrace = default; endOfLineTrivia = default; if (!token.IsKind(SyntaxKind.CloseBraceToken)) return false; var nextToken = token.GetNextToken(); if (!nextToken.IsKind(SyntaxKind.CloseBraceToken)) return false; var firstBrace = token; secondBrace = nextToken; // two } tokens. They need to be on the same line, or if they are not on subsequent lines, then there needs // to be more than whitespace between them. var lines = text.Lines; var firstBraceLine = lines.GetLineFromPosition(firstBrace.SpanStart).LineNumber; var secondBraceLine = lines.GetLineFromPosition(secondBrace.SpanStart).LineNumber; var lineCount = secondBraceLine - firstBraceLine; // if they're both on the same line, or one line apart, then there's no problem. if (lineCount <= 1) return false; // they're multiple lines apart. This i not ok if those lines are all whitespace. for (var currentLine = firstBraceLine + 1; currentLine < secondBraceLine; currentLine++) { if (!IsAllWhitespace(lines[currentLine])) return false; } endOfLineTrivia = secondBrace.LeadingTrivia.Last(t => t.IsKind(SyntaxKind.EndOfLineTrivia)); return endOfLineTrivia != default; } private static bool IsAllWhitespace(TextLine textLine) { var text = textLine.Text!; for (var i = textLine.Start; i < textLine.End; i++) { if (!SyntaxFacts.IsWhitespace(text[i])) return false; } return true; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpTypeNameFormatter.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.CSharp.Symbols; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting { internal class CSharpTypeNameFormatter : CommonTypeNameFormatter { protected override CommonPrimitiveFormatter PrimitiveFormatter { get; } public CSharpTypeNameFormatter(CommonPrimitiveFormatter primitiveFormatter) { PrimitiveFormatter = primitiveFormatter; } protected override string GenericParameterOpening => "<"; protected override string GenericParameterClosing => ">"; protected override string ArrayOpening => "["; protected override string ArrayClosing => "]"; protected override string GetPrimitiveTypeName(SpecialType type) { switch (type) { case SpecialType.System_Boolean: return "bool"; case SpecialType.System_Byte: return "byte"; case SpecialType.System_Char: return "char"; case SpecialType.System_Decimal: return "decimal"; case SpecialType.System_Double: return "double"; case SpecialType.System_Int16: return "short"; case SpecialType.System_Int32: return "int"; case SpecialType.System_Int64: return "long"; case SpecialType.System_SByte: return "sbyte"; case SpecialType.System_Single: return "float"; case SpecialType.System_String: return "string"; case SpecialType.System_UInt16: return "ushort"; case SpecialType.System_UInt32: return "uint"; case SpecialType.System_UInt64: return "ulong"; case SpecialType.System_Object: return "object"; default: return null; } } public override string FormatTypeName(Type type, CommonTypeNameFormatterOptions options) { string stateMachineName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName)) { return stateMachineName; } return base.FormatTypeName(type, options); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting { internal class CSharpTypeNameFormatter : CommonTypeNameFormatter { protected override CommonPrimitiveFormatter PrimitiveFormatter { get; } public CSharpTypeNameFormatter(CommonPrimitiveFormatter primitiveFormatter) { PrimitiveFormatter = primitiveFormatter; } protected override string GenericParameterOpening => "<"; protected override string GenericParameterClosing => ">"; protected override string ArrayOpening => "["; protected override string ArrayClosing => "]"; protected override string GetPrimitiveTypeName(SpecialType type) { switch (type) { case SpecialType.System_Boolean: return "bool"; case SpecialType.System_Byte: return "byte"; case SpecialType.System_Char: return "char"; case SpecialType.System_Decimal: return "decimal"; case SpecialType.System_Double: return "double"; case SpecialType.System_Int16: return "short"; case SpecialType.System_Int32: return "int"; case SpecialType.System_Int64: return "long"; case SpecialType.System_SByte: return "sbyte"; case SpecialType.System_Single: return "float"; case SpecialType.System_String: return "string"; case SpecialType.System_UInt16: return "ushort"; case SpecialType.System_UInt32: return "uint"; case SpecialType.System_UInt64: return "ulong"; case SpecialType.System_Object: return "object"; default: return null; } } public override string FormatTypeName(Type type, CommonTypeNameFormatterOptions options) { string stateMachineName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName)) { return stateMachineName; } return base.FormatTypeName(type, options); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Portable/Symbols/FieldOrPropertyInitializer.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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field initializer, a property initializer, or a global statement in script code. /// </summary> internal struct FieldOrPropertyInitializer { /// <summary> /// The field being initialized (possibly a backing field of a property), or null if this is a top-level statement in script code. /// </summary> internal readonly FieldSymbol FieldOpt; /// <summary> /// A reference to <see cref="EqualsValueClauseSyntax"/>, /// or top-level <see cref="StatementSyntax"/> in script code, /// or <see cref="ParameterSyntax"/> for an initialization of a generated property based on record parameter. /// </summary> internal readonly SyntaxReference Syntax; public FieldOrPropertyInitializer(FieldSymbol fieldOpt, SyntaxNode syntax) { Debug.Assert(((syntax.IsKind(SyntaxKind.EqualsValueClause) || syntax.IsKind(SyntaxKind.Parameter)) && fieldOpt != null) || syntax is StatementSyntax); FieldOpt = fieldOpt; Syntax = syntax.GetReference(); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field initializer, a property initializer, or a global statement in script code. /// </summary> internal struct FieldOrPropertyInitializer { /// <summary> /// The field being initialized (possibly a backing field of a property), or null if this is a top-level statement in script code. /// </summary> internal readonly FieldSymbol FieldOpt; /// <summary> /// A reference to <see cref="EqualsValueClauseSyntax"/>, /// or top-level <see cref="StatementSyntax"/> in script code, /// or <see cref="ParameterSyntax"/> for an initialization of a generated property based on record parameter. /// </summary> internal readonly SyntaxReference Syntax; public FieldOrPropertyInitializer(FieldSymbol fieldOpt, SyntaxNode syntax) { Debug.Assert(((syntax.IsKind(SyntaxKind.EqualsValueClause) || syntax.IsKind(SyntaxKind.Parameter)) && fieldOpt != null) || syntax is StatementSyntax); FieldOpt = fieldOpt; Syntax = syntax.GetReference(); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormattingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; #if !CODE_STYLE using Microsoft.CodeAnalysis.Host; #endif namespace Microsoft.CodeAnalysis.Formatting { internal interface ISyntaxFormattingService #if !CODE_STYLE : ILanguageService #endif { IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules(); IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; #if !CODE_STYLE using Microsoft.CodeAnalysis.Host; #endif namespace Microsoft.CodeAnalysis.Formatting { internal interface ISyntaxFormattingService #if !CODE_STYLE : ILanguageService #endif { IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules(); IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenClosureLambdaTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenClosureLambdaTests : CSharpTestBase { [Fact] public void LambdaInIndexerAndBinaryOperator() { var verifier = CompileAndVerify(@" using System; class C { private static Func<int> _f1; private static Func<int> _f2; public static void Main() { var c = new C(); c[() => 0] += 1; Console.WriteLine(object.ReferenceEquals(_f1, _f2)); } int this[Func<int> f] { get { _f1 = f; return 0; } set { _f2 = f; } } }", expectedOutput: "True"); } [Fact] public void MethodGroupInIndexerAndBinaryOperator() { CompileAndVerify(@" using System; class C { private static Func<int> _f1; private static Func<int> _f2; public static void Main() { var c = new C(); c[F] += 1; Console.WriteLine(object.ReferenceEquals(_f1, _f2)); } static int F() => 0; public int this[Func<int> f] { get { _f1 = f; return 0; } set { _f2 = f; } } }", expectedOutput: "True"); } [Fact] public void EnvironmentChainContainsUnusedEnvironment() { CompileAndVerify(@" using System; class C { void M(int x) { { int y = 10; Action f1 = () => Console.WriteLine(y); { int z = 5; Action f2 = () => Console.WriteLine(z + x); f2(); } f1(); } } public static void Main() => new C().M(3); }", expectedOutput: @"8 10"); } [Fact] public void CaptureThisAsFramePointer() { var comp = @" using System; using System.Collections.Generic; class C { int _z = 0; void M(IEnumerable<int> xs) { foreach (var x in xs) { Func<int, int> captureFunc = k => x + _z; } } }"; CompileAndVerify(comp); } [Fact] public void StaticClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { D d1 = new D(() => Console.Write(1)); d1(); D d2 = () => Console.WriteLine(2); d2(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"12"); compilation.VerifyIL("C.Main", @" { // Code size 73 (0x49) .maxstack 2 IL_0000: ldsfld ""D C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""void C.<>c.<Main>b__0_0()"" IL_0014: newobj ""D..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D C.<>c.<>9__0_0"" IL_001f: callvirt ""void D.Invoke()"" IL_0024: ldsfld ""D C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""void C.<>c.<Main>b__0_1()"" IL_0038: newobj ""D..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""D C.<>c.<>9__0_1"" IL_0043: callvirt ""void D.Invoke()"" IL_0048: ret } "); } [Fact] public void ThisOnlyClosure() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { new C().M(); } int n = 1; int m = 2; public void M() { for (int i = 0; i < 2; i++) { D d1 = new D(() => Console.Write(n)); d1(); D d2 = () => Console.WriteLine(m); d2(); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"12 12"); compilation.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_002a IL_0004: ldarg.0 IL_0005: ldftn ""void C.<M>b__3_0()"" IL_000b: newobj ""D..ctor(object, System.IntPtr)"" IL_0010: callvirt ""void D.Invoke()"" IL_0015: ldarg.0 IL_0016: ldftn ""void C.<M>b__3_1()"" IL_001c: newobj ""D..ctor(object, System.IntPtr)"" IL_0021: callvirt ""void D.Invoke()"" IL_0026: ldloc.0 IL_0027: ldc.i4.1 IL_0028: add IL_0029: stloc.0 IL_002a: ldloc.0 IL_002b: ldc.i4.2 IL_002c: blt.s IL_0004 IL_002e: ret }"); } [Fact] public void StaticClosure02() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { new C().F(); } void F() { D d1 = () => Console.WriteLine(1); d1(); } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact] public void StaticClosure03() { string source = @"using System; delegate int D(int x); class Program { static void Main(string[] args) { int @string = 10; D d = delegate (int @class) { return @class + @string; }; Console.WriteLine(d(2)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void InstanceClosure01() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { D d1 = () => Console.WriteLine(X); d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure02() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { D d1 = () => { C c = this; Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure03() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { C c = this; D d1 = () => { Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure04() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { F(new C(12)); } static void F(C c) { D d1 = () => { Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure05() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { { C c = new C(12); D d = () => { Console.WriteLine(c.X); }; d(); } { C c = new C(13); D d = () => { Console.WriteLine(c.X); }; d(); } } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void InstanceClosure06() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { Console.WriteLine(K); Console.WriteLine(i); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 "); } [Fact] public void LoopClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { D d1 = null, d2 = null; int i = 0; while (i < 10) { int j = i; if (i == 5) { d1 = () => Console.WriteLine(j); d2 = () => Console.WriteLine(i); } i = i + 1; } d1(); d2(); } }"; CompileAndVerify(source, expectedOutput: @" 5 10 "); } [Fact] public void NestedClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { D d2 = () => { Console.WriteLine(i); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void NestedClosure02() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 "); } [Fact] public void NestedClosure10() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void NestedClosure11() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { int j = 13; D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 13 "); } [Fact] public void NestedClosure20() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { int j = i + 1; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void NestedClosure21() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { int j = i + 1; D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 13 "); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void NestedClosureThisConstructorInitializer() { string source = @"using System; delegate void D(); delegate void D1(int i); class C { public int l = 15; public C():this((int i) => { int k = 14; D d15 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); }; d2(); }; d15(); }) {func((int i) => { int k = 14; D d15 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); Console.WriteLine(l); }; d2(); }; d15(); }); } public C(D1 d1){int i=12; d1(i);} public void func(D1 d1) { int i=12;d1(i); } public static void Main(string[] args) { new C(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 14 12 13 14 15 "); } [Fact] public void FilterParameterClosure01() { string source = @" using System; class Program { static void Main() { string s = ""xxx""; try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<Exception, bool>(x => x.Message == s)(e)) { Console.Write(""pass""); } } }"; CompileAndVerify(source, expectedOutput: "pass"); } [Fact] public void FilterParameterClosure02() { string source = @" using System; class Program { static void Main() { string s = ""xxx""; try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<Exception, bool>(x => x.Message == s)(e)) { Console.Write(s + ""pass""); } } }"; CompileAndVerify(source, expectedOutput: "xxxpass"); } [WorkItem(541258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541258")] [Fact] public void CatchVarLifted1() { string source = @"using System; class Program { static void Main() { Action a = null; try { throw new Exception(""pass""); } catch (Exception e) { a = () => Console.Write(e.Message); } a(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (System.Action V_0, //a Program.<>c__DisplayClass0_0 V_1, //CS$<>8__locals0 System.Exception V_2) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldstr ""pass"" IL_0007: newobj ""System.Exception..ctor(string)"" IL_000c: throw } catch System.Exception { IL_000d: newobj ""Program.<>c__DisplayClass0_0..ctor()"" IL_0012: stloc.1 IL_0013: stloc.2 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: stfld ""System.Exception Program.<>c__DisplayClass0_0.e"" IL_001b: ldloc.1 IL_001c: ldftn ""void Program.<>c__DisplayClass0_0.<Main>b__0()"" IL_0022: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0027: stloc.0 IL_0028: leave.s IL_002a } IL_002a: ldloc.0 IL_002b: callvirt ""void System.Action.Invoke()"" IL_0030: ret } "); } [Fact] public void CatchVarLifted2() { var source = @" using System; class Program { static bool Goo(Action x) { x(); return true; } static void Main() { try { throw new Exception(""fail""); } catch (Exception ex) when (Goo(() => { ex = new Exception(""pass""); })) { Console.Write(ex.Message); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 79 (0x4f) .maxstack 2 .locals init (Program.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Exception V_1) .try { IL_0000: ldstr ""fail"" IL_0005: newobj ""System.Exception..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""System.Exception"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0039 IL_0017: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_001c: stloc.0 IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldloc.1 IL_0020: stfld ""System.Exception Program.<>c__DisplayClass1_0.ex"" IL_0025: ldloc.0 IL_0026: ldftn ""void Program.<>c__DisplayClass1_0.<Main>b__0()"" IL_002c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0031: call ""bool Program.Goo(System.Action)"" IL_0036: ldc.i4.0 IL_0037: cgt.un IL_0039: endfilter } // end filter { // handler IL_003b: pop IL_003c: ldloc.0 IL_003d: ldfld ""System.Exception Program.<>c__DisplayClass1_0.ex"" IL_0042: callvirt ""string System.Exception.Message.get"" IL_0047: call ""void System.Console.Write(string)"" IL_004c: leave.s IL_004e } IL_004e: ret } "); } [Fact] public void CatchVarLifted2a() { var source = @" using System; class Program { static bool Goo(Action x) { x(); return true; } static void Main() { try { throw new Exception(""fail""); } catch (ArgumentException ex) when (Goo(() => { ex = new ArgumentException(""fail""); })) { Console.Write(ex.Message); } catch (Exception ex) when (Goo(() => { ex = new Exception(""pass""); })) { Console.Write(ex.Message); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); } [Fact] public void CatchVarLifted3() { string source = @" using System; class Program { static void Main() { try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<bool>(() => e.Message == ""xxx"")()) { Console.Write(""pass""); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 2 .locals init (Program.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Exception V_1) .try { IL_0000: ldstr ""xxx"" IL_0005: newobj ""System.Exception..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""System.Exception"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0039 IL_0017: newobj ""Program.<>c__DisplayClass0_0..ctor()"" IL_001c: stloc.0 IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldloc.1 IL_0020: stfld ""System.Exception Program.<>c__DisplayClass0_0.e"" IL_0025: ldloc.0 IL_0026: ldftn ""bool Program.<>c__DisplayClass0_0.<Main>b__0()"" IL_002c: newobj ""System.Func<bool>..ctor(object, System.IntPtr)"" IL_0031: callvirt ""bool System.Func<bool>.Invoke()"" IL_0036: ldc.i4.0 IL_0037: cgt.un IL_0039: endfilter } // end filter { // handler IL_003b: pop IL_003c: ldstr ""pass"" IL_0041: call ""void System.Console.Write(string)"" IL_0046: leave.s IL_0048 } IL_0048: ret } "); } [Fact] public void CatchVarLifted_Generic1() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { new Action(() => { try { throw new IOException(""xxx""); } catch (T e) when (e.Message == ""xxx"") { Console.Write(""pass""); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.<>c__1<T>.<F>b__1_0", @" { // Code size 67 (0x43) .maxstack 2 .try { IL_0000: ldstr ""xxx"" IL_0005: newobj ""System.IO.IOException..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""T"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0033 IL_0017: unbox.any ""T"" IL_001c: box ""T"" IL_0021: callvirt ""string System.Exception.Message.get"" IL_0026: ldstr ""xxx"" IL_002b: call ""bool string.op_Equality(string, string)"" IL_0030: ldc.i4.0 IL_0031: cgt.un IL_0033: endfilter } // end filter { // handler IL_0035: pop IL_0036: ldstr ""pass"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: leave.s IL_0042 } IL_0042: ret } "); } [Fact] public void CatchVarLifted_Generic2() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { string x = ""x""; new Action(() => { string y = ""y""; try { throw new IOException(""xy""); } catch (T e) when (new Func<bool>(() => e.Message == x + y)()) { Console.Write(""pass_"" + x + y); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass_xy"); verifier.VerifyIL("Program.<>c__DisplayClass1_0<T>.<F>b__0", @" { // Code size 113 (0x71) .maxstack 3 .locals init (Program.<>c__DisplayClass1_1<T> V_0, //CS$<>8__locals0 T V_1) IL_0000: newobj ""Program.<>c__DisplayClass1_1<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.<>c__DisplayClass1_0<T> Program.<>c__DisplayClass1_1<T>.CS$<>8__locals1"" IL_000d: ldloc.0 IL_000e: ldstr ""y"" IL_0013: stfld ""string Program.<>c__DisplayClass1_1<T>.y"" .try { IL_0018: ldstr ""xy"" IL_001d: newobj ""System.IO.IOException..ctor(string)"" IL_0022: throw } filter { IL_0023: isinst ""T"" IL_0028: dup IL_0029: brtrue.s IL_002f IL_002b: pop IL_002c: ldc.i4.0 IL_002d: br.s IL_0050 IL_002f: unbox.any ""T"" IL_0034: stloc.1 IL_0035: ldloc.0 IL_0036: ldloc.1 IL_0037: stfld ""T Program.<>c__DisplayClass1_1<T>.e"" IL_003c: ldloc.0 IL_003d: ldftn ""bool Program.<>c__DisplayClass1_1<T>.<F>b__1()"" IL_0043: newobj ""System.Func<bool>..ctor(object, System.IntPtr)"" IL_0048: callvirt ""bool System.Func<bool>.Invoke()"" IL_004d: ldc.i4.0 IL_004e: cgt.un IL_0050: endfilter } // end filter { // handler IL_0052: pop IL_0053: ldstr ""pass_"" IL_0058: ldarg.0 IL_0059: ldfld ""string Program.<>c__DisplayClass1_0<T>.x"" IL_005e: ldloc.0 IL_005f: ldfld ""string Program.<>c__DisplayClass1_1<T>.y"" IL_0064: call ""string string.Concat(string, string, string)"" IL_0069: call ""void System.Console.Write(string)"" IL_006e: leave.s IL_0070 } IL_0070: ret } "); } [Fact] public void CatchVarLifted_Generic3() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { string x = ""x""; new Action(() => { string y = ""y""; try { throw new IOException(""a""); } catch (T e1) when (new Func<bool>(() => { string z = ""z""; try { throw new IOException(""xyz""); } catch (T e2) when (e2.Message == x + y + z) { return true; } })()) { Console.Write(""pass_"" + x + y); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass_xy"); } [Fact] public void ForeachParameterClosure01() { string source = @"using System; using System.Collections.Generic; delegate void D(); class C { public static void Main(string[] args) { List<string> list = new List<string>(new string[] {""A"", ""B""}); D d = null; foreach (string s in list) { if (s == ""A"") { d = () => { Console.WriteLine(s); }; } } d(); } }"; // Dev10 prints B, but we have intentionally changed the scope // of the loop variable. CompileAndVerify(source, expectedOutput: "A"); } [Fact] public void LambdaParameterClosure01() { string source = @"using System; delegate void D0(); delegate void D1(string s); class C { public static void Main(string[] args) { D0 d0 = null; D1 d1 = (string s) => { d0 = () => { Console.WriteLine(s); }; }; d1(""goo""); d0(); } }"; CompileAndVerify(source, expectedOutput: "goo"); } [Fact] public void BaseInvocation01() { string source = @"using System; class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main() { base.F(); } public static void Main(string[] args) { new C().Main(); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure01() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main() { D d = () => { base.F(); }; d(); } public static void Main(string[] args) { new C().Main(); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure02() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main(int x) { D d = () => { x = x + 1; base.F(); }; d(); } public static void Main(string[] args) { new C().Main(3); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure03() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main(int x) { D d = base.F; d(); } public static void Main(string[] args) { new C().Main(3); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseAccessInClosure_01() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { var s = ""this: ""; Func<string> f = () => s + this.F(); Console.WriteLine(f()); } public void TestBase() { var s = ""base: ""; Func<string> f = () => s + base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"this: D::F{Environment.NewLine}base: B1::F"); } [Fact] public void BaseAccessInClosure_02() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestThis() { var s = ""this: ""; Func<string> f = () => s + this.F(); Console.WriteLine(f()); } public void TestBase() { var s = ""base: ""; Func<string> f = () => s + base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"this: D::F{Environment.NewLine}base: B1::F"); } [Fact] public void BaseAccessInClosure_03_WithILCheck() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestBase() { Func<string> f = () => base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: "B1::F"). VerifyIL("M1.B2.<TestBase>b__1_0", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string M1.B1.F()"" IL_0006: ret }"); } [Fact] public void BaseAccessInClosure_03a_WithILCheck() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { public override string F() { return ""B1a::F""; } } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestBase() { Func<string> f = () => base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: "B1a::F"). VerifyIL("M1.B2.<TestBase>b__1_0", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string M1.B1a.F()"" IL_0006: ret }"); } [Fact] public void BaseAccessInClosure_04() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { Func<string> f = this.F; Console.WriteLine(f()); } public void TestBase() { Func<string> f = base.F; Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_05() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { Func<Func<string>> f = () => this.F; Console.WriteLine(f()()); } public void TestBase() { Func<Func<string>> f = () => base.F; Console.WriteLine(f()()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_06() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { int s = 0; Func<Func<string>> f = () => { s++; return this.F; }; Console.WriteLine(f()()); } public void TestBase() { int s = 0; Func<Func<string>> f = () => { s++; return base.F; }; Console.WriteLine(f()()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_07() { string source = @"using System; static class M1 { class B1 { public virtual string F { get { Console.Write(""B1::F.Get;""); return null; } set { Console.Write(""B1::F.Set;""); } } } class B2 : B1 { public override string F { get { Console.Write(""B2::F.Get;""); return null; } set { Console.Write(""B2::F.Set;""); } } public void Test() { int s = 0; Action f = () => { s++; this.F = base.F; base.F = this.F; }; f(); } } class D : B2 { public override string F { get { Console.Write(""D::F.Get;""); return null; } set { Console.Write(""F::F.Set;""); } } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F.Get;F::F.Set;D::F.Get;B1::F.Set;"); } [Fact] public void BaseAccessInClosure_08() { string source = @"using System; static class M1 { class B1 { public virtual void F<T>(T t) { Console.Write(""B1::F;""); } } class B2 : B1 { public override void F<T>(T t) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Action f = () => { s++; this.F<int>(0); base.F<string>(""""); }; f(); } } class D : B2 { public override void F<T>(T t) { Console.Write(""D::F;""); } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "D::F;B1::F;"); } [Fact] public void BaseAccessInClosure_09() { string source = @"using System; static class M1 { class B1 { public virtual void F<T>(T t) { Console.Write(""B1::F;""); } } class B2 : B1 { public override void F<T>(T t) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<int>> f1 = () => { s++; return base.F<int>; }; f1()(0); Func<Action<string>> f2 = () => { s++; return this.F<string>; }; f2()(null); } } class D : B2 { public override void F<T>(T t) { Console.Write(""D::F;""); } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_10() { string source = @"using System; static class M1 { class B1<T> { public virtual void F<U>(T t, U u) { Console.Write(""B1::F;""); } } class B2<T> : B1<T> { public override void F<U>(T t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<T, int>> f1 = () => { s++; return base.F<int>; }; f1()(default(T), 0); Func<Action<T, string>> f2 = () => { s++; return this.F<string>; }; f2()(default(T), null); } } class D<T> : B2<T> { public override void F<U>(T t, U u) { Console.Write(""D::F;""); } } static void Main() { (new D<int>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_11() { string source = @"using System; static class M1 { class B1<T> { public virtual void F<U>(T t, U u) { Console.Write(""B1::F;""); } } class Outer<V> { public class B2 : B1<V> { public override void F<U>(V t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<V, int>> f1 = () => { s++; return base.F<int>; }; f1()(default(V), 0); Func<Action<V, string>> f2 = () => { s++; return this.F<string>; }; f2()(default(V), null); } } } class D<X> : Outer<X>.B2 { public override void F<U>(X t, U u) { Console.Write(""D::F;""); } } static void Main() { (new D<int>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_12() { string source = @"using System; static class M1 { public class Outer<T> { public class B1 { public virtual string F1(T t) { return ""B1::F1;""; } public virtual string F2(T t) { return ""B1::F2;""; } } } public class B2 : Outer<int>.B1 { public override string F1(int t) { return ""B2::F2;""; } public void Test() { int s = 0; Func<string> f1 = () => new Func<int, string>(this.F1)(s) + new Func<int, string>(base.F1)(s); Func<string> f2 = () => new Func<int, string>(this.F2)(s) + new Func<int, string>(base.F2)(s); Console.WriteLine(f1() + f2()); } } class D : B2 { public override string F1(int t) { return ""D::F2;""; } public override string F2(int t) { return ""D::F2;""; } } static void Main() { (new D()).Test(); } } "; CompileAndVerify(source, expectedOutput: "D::F2;B1::F1;D::F2;B1::F2;"); } [Fact] public void BaseAccessInClosure_13() { string source = @"using System; static class M1 { interface I{} class B1<T> where T : I { public virtual void F<U>(T t, U u) where U : struct, T { Console.Write(""B1::F;""); } } class Outer<V> where V : struct, I { public class B2 : B1<V> { public override void F<U>(V t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<V, V>> f1 = () => { s++; return base.F<V>; }; f1()(default(V), default(V)); Func<Action<V, V>> f2 = () => { s++; return this.F<V>; }; f2()(default(V), default(V)); } } } class D<X> : Outer<X>.B2 where X : struct, I { public override void F<U>(X t, U u) { Console.Write(""D::F;""); } } struct C : I { } static void Main() { (new D<C>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_14_WithILCheck() { string source = @"using System; static class M1 { public class Outer<T> { public class B1 { public virtual string F<U>(T t, U u) { return ""B1:F""; } } } public class B2 : Outer<int>.B1 { public override string F<U>(int t, U u) { return ""B2:F""; } public void Test() { int s = 0; Func<string> f1 = () => new Func<int, int, string>(base.F<int>)(s, s); Console.WriteLine(f1()); } } static void Main() { (new B2()).Test(); } }"; CompileAndVerify(source, expectedOutput: @"B1:F" ). VerifyIL("M1.B2.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""string M1.Outer<int>.B1.F<U>(int, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_15_WithILCheck() { string source = @"using System; static class M1 { public interface I { } public interface II : I { } public class C : II { public C() { } } public class Outer<T> where T : I, new() { public class B1 { public virtual string F<U>(T t, U u) where U : T, new() { return ""B1::F;""; } } } public class B2 : Outer<C>.B1 { public override string F<U>(C t, U u) { return ""B2::F;""; } public void Test() { C s = new C(); Func<string> f1 = () => new Func<C, C, string>(base.F)(s, s); Console.WriteLine(f1()); } } static void Main() { (new B2()).Test(); } }"; CompileAndVerify(source, expectedOutput: @"B1::F;" ). VerifyIL("M1.B2.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 35 (0x23) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""M1.B2 M1.B2.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""string M1.B2.<>n__0<M1.C>(M1.C, M1.C)"" IL_000c: newobj ""System.Func<M1.C, M1.C, string>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""M1.C M1.B2.<>c__DisplayClass1_0.s"" IL_0017: ldarg.0 IL_0018: ldfld ""M1.C M1.B2.<>c__DisplayClass1_0.s"" IL_001d: callvirt ""string System.Func<M1.C, M1.C, string>.Invoke(M1.C, M1.C)"" IL_0022: ret }"). VerifyIL("M1.B2.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""string M1.Outer<M1.C>.B1.F<U>(M1.C, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_16() { string source = @"using System; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.CompilerServices; static class M1 { public interface I { } public interface II : I { } public class C : II { public C() { } } public class Outer<T> where T : I, new() { public class B1 { public virtual string F<U>(T t, U u) where U : I, T, new() { return ""B1::F;""; } } } public class B2 : Outer<C>.B1 { public override string F<U>(C t, U u) { return ""B2::F;""; } public void Test() { C s = new C(); Func<string> f1 = () => new Func<C, C, string>(base.F)(s, s); Console.WriteLine(f1()); } } static void Main() { var type = (new B2()).GetType(); var method = type.GetMethod(""<>n__0"", BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine(Attribute.IsDefined(method, typeof(CompilerGeneratedAttribute))); Console.WriteLine(method.IsPrivate); Console.WriteLine(method.IsVirtual); Console.WriteLine(method.IsGenericMethod); var genericDef = method.GetGenericMethodDefinition(); var arguments = genericDef.GetGenericArguments(); Console.WriteLine(arguments.Length); var arg0 = arguments[0]; GenericParameterAttributes attributes = arg0.GenericParameterAttributes; Console.WriteLine(attributes.ToString()); var arg0constraints = arg0.GetGenericParameterConstraints(); Console.WriteLine(arg0constraints.Length); Console.WriteLine(arg0constraints[0]); Console.WriteLine(arg0constraints[1]); } }"; CompileAndVerify(source, expectedOutput: @" True True False True 1 DefaultConstructorConstraint 2 M1+I M1+C" ); } [Fact] public void BaseAccessInClosure_17_WithILCheck() { string source = @"using System; class Base<T> { public virtual void Func<U>(T t, U u) { Console.Write(typeof (T)); Console.Write("" ""); Console.Write(typeof (U)); } public class Derived : Base<int> { public void Test() { int i = 0; T t = default(T); Action d = () => { base.Func<T>(i, t); }; d(); } } } class Program { static void Main() { new Base<string>.Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "System.Int32 System.String" ). VerifyIL("Base<T>.Derived.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""void Base<int>.Func<U>(int, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_18_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { base.F(j); this.F(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;Derived::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @" { // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldarg.0 IL_0007: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_000c: call ""void Base.F(int)"" IL_0011: ldarg.0 IL_0012: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0017: ldarg.0 IL_0018: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_001d: call ""void Derived.F(int)"" IL_0022: ret }"); } [Fact] public void BaseAccessInClosure_19_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { Action<int> b = base.F; b(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""void Base.F(int)"" IL_000c: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_0017: callvirt ""void System.Action<int>.Invoke(int)"" IL_001c: ret }"); } [Fact] public void BaseAccessInClosure_20_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { Action<int> b = new Action<int>(base.F); b(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""void Base.F(int)"" IL_000c: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_0017: callvirt ""void System.Action<int>.Invoke(int)"" IL_001c: ret }"); } [Fact] public void UnsafeInvocationClosure01() { string source = @"using System; delegate void D(); class C { static unsafe void F() { D d = () => { Console.WriteLine(""F""); }; d(); } public static void Main(string[] args) { D d = () => { F(); }; d(); } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F", verify: Verification.Passes); } [Fact] public void LambdaWithParameters01() { var source = @" delegate void D(int x); class LWP { public static void Main(string[] args) { D d1 = x => { System.Console.Write(x); }; d1(123); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters02() { var source = @" delegate void D(int x); class LWP { public static void Main(string[] args) { int local; D d1 = x => { local = 12; System.Console.Write(x); }; d1(123); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters03() { var source = @" delegate void D(int x); class LWP { void M() { D d1 = x => { System.Console.Write(x); }; d1(123); } public static void Main(string[] args) { new LWP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters04() { var source = @" delegate void D(int x); class LWP { void M() { int local; D d1 = x => { local = 2; System.Console.Write(x); }; d1(123); } public static void Main(string[] args) { new LWP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter01() { var source = @" delegate D D(int x); class CLP { public static void Main(string[] args) { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter02() { var source = @" delegate D D(int x); class CLP { void M() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter03() { var source = @" delegate D D(int x); class CLP { public static void Main(string[] args) { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } } "; CompileAndVerify(source, expectedOutput: "4123"); } [Fact] public void CapturedLambdaParameter04() { var source = @" delegate D D(int x); class CLP { void M() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M(); } } "; CompileAndVerify(source, expectedOutput: "4123"); } [Fact] public void GenericClosure01() { string source = @"using System; delegate void D(); class G<T> { public static void F(T t) { D d = () => { Console.WriteLine(t); }; d(); } } class C { public static void Main(string[] args) { G<int>.F(12); G<string>.F(""goo""); } }"; CompileAndVerify(source, expectedOutput: @" 12 goo "); } [Fact] public void GenericClosure02() { string source = @"using System; delegate void D(); class G { public static void F<T>(T t) { D d = () => { Console.WriteLine(t); }; d(); } } class C { public static void Main(string[] args) { G.F<int>(12); G.F<string>(""goo""); } }"; CompileAndVerify(source, expectedOutput: @" 12 goo "); } [Fact] public void GenericClosure03() { var source = @"using System; delegate U D<U>(); class GenericClosure { static D<T> Default<T>(T value) { return () => value; } public static void Main(string[] args) { D<string> dHello = Default(""Hello""); Console.WriteLine(dHello()); D<int> d1234 = Default(1234); Console.WriteLine(d1234()); } } "; var expectedOutput = @"Hello 1234"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void GenericClosure04() { var source = @"using System; delegate T D<T>(); class GenericClosure { static D<T> Default<T>(T value) { return () => default(T); } public static void Main(string[] args) { D<string> dHello = Default(""Hello""); Console.WriteLine(dHello()); D<int> d1234 = Default(1234); Console.WriteLine(d1234()); } } "; var expectedOutput = @" 0"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void GenericCapturedLambdaParameter01() { var source = @" delegate D D(int x); class CLP { void M<T>() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M<int>(); new CLP().M<string>(); } } "; CompileAndVerify(source, expectedOutput: "123123"); } [Fact] public void GenericCapturedLambdaParameter02() { var source = @" delegate D D(int x); class CLP { static void M<T>() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "123123"); } [Fact] public void GenericCapturedLambdaParameter03() { var source = @" delegate D D(int x); class CLP { void M<T>() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M<int>(); new CLP().M<string>(); } } "; CompileAndVerify(source, expectedOutput: "41234123"); } [Fact] public void GenericCapturedLambdaParameter04() { var source = @" delegate D D(int x); class CLP { static void M<T>() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "41234123"); } [Fact] public void GenericCapturedTypeParameterLocal() { var source = @" delegate void D(); class CLP { static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; System.Console.Write("""" + t0 + t1 + t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureConstructedMethodInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { static void P<T>(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; P(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureConstructionInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { class P<T> { public P(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; new P<T>(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureDelegateConversionInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { delegate void D3<T>(T t0, T t1, T t2); public static void P<T>(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; D3<T> d3 = P; d3(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureFieldInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { class HolderClass<T> { public static T t; } delegate void D3<T>(T t0, T t1, T t2); static void M<T>() { D d = () => { System.Console.Write(string.Concat(HolderClass<T>.t)); }; d(); } public static void Main(string[] args) { HolderClass<int>.t = 12; HolderClass<string>.t = ""he""; CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "12he"); } [Fact] public void CaptureReadonly01() { var source = @" using System; class Program { private static readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(3), ""he"")); } }"; CompileAndVerify(source, expectedOutput: "15he"); } [Fact] public void CaptureReadonly02() { var source = @" using System; class Program { private readonly int v = 5; delegate int del(int i); void M() { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(3), ""he"")); } static void Main(string[] args) { new Program().M(); } }"; CompileAndVerify(source, expectedOutput: "15he"); } [Fact] public void CaptureLoopIndex() { var source = @" using System; delegate void D(); class Program { static void Main(string[] args) { D d0 = null; for (int i = 0; i < 4; i++) { D d = d0 = () => { Console.Write(i); }; d(); } d0(); } }"; CompileAndVerify(source, expectedOutput: "01234"); } // see Roslyn bug 5956 [Fact] public void CapturedIncrement() { var source = @" class Program { delegate int Func(); static void Main(string[] args) { int i = 0; Func query; if (true) { query = () => { i = 6; Goo(i++); return i; }; } i = 3; System.Console.WriteLine(query.Invoke()); } public static int Goo(int i) { i = 4; return i; } } "; CompileAndVerify(source, expectedOutput: "7"); } [Fact] public void StructDelegate() { var source = @" using System; class Program { static void Main() { int x = 42; Func<string> f = x.ToString; Console.Write(f.Invoke()); } }" ; CompileAndVerify(source, expectedOutput: "42"); } [Fact] public void StructDelegate1() { var source = @" using System; class Program { public static void Goo<T>(T x) { Func<string> f = x.ToString; Console.Write(f.Invoke()); } static void Main() { string s = ""Hi""; Goo(s); int x = 42; Goo(x); } }" ; CompileAndVerify(source, expectedOutput: "Hi42"); } [Fact] public void StaticDelegateFromMethodGroupInLambda() { var source = @"using System; class Program { static void M() { Console.WriteLine(12); } public static void Main(string[] args) { Action a = () => { Action b = new Action(M); b(); }; a(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void StaticDelegateFromMethodGroupInLambda2() { var source = @"using System; class Program { static void M() { Console.WriteLine(12); } void G() { Action a = () => { Action b = new Action(M); b(); }; a(); } public static void Main(string[] args) { new Program().G(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [WorkItem(539346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539346")] [Fact] public void CachedLambdas() { var source = @"using System; public class Program { private static void Assert(bool b) { if (!b) throw new Exception(); } public static void Test1() { Action a0 = null; for (int i = 0; i < 2; i++) { Action a = () => { }; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public void Test2() { Action a0 = null; for (int i = 0; i < 2; i++) { Action a = () => { }; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public static void Test3() { int inEnclosing = 12; Func<int> a0 = null; for (int i = 0; i < 2; i++) { Func<int> a = () => inEnclosing; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public void Test4() { Func<Program> a0 = null; for (int i = 0; i < 2; i++) { Func<Program> a = () => this; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); // Roslyn misses this } } } public static void Test5() { int i = 12; Func<Action> D = () => () => Console.WriteLine(i); Action a1 = D(); Action a2 = D(); Assert(ReferenceEquals(a1, a2)); // native compiler misses this } public static void Test6() { Func<int> a1 = Goo<int>.Bar<int>(); Func<int> a2 = Goo<int>.Bar<int>(); Assert(ReferenceEquals(a1, a2)); // both native compiler and Roslyn miss this } public static void Main(string[] args) { Test1(); new Program().Test2(); Test3(); // new Program().Test4(); Test5(); // Test6(); } } class Goo<T> { static T t; public static Func<U> Bar<U>() { return () => Goo<U>.t; } }"; CompileAndVerify(source, expectedOutput: ""); } [Fact] public void ParentFrame01() { //IMPORTANT: the parent frame field in Program.c1.<>c__DisplayClass1 should be named CS$<>8__locals, not <>4__this. string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<int, Func<int, int>>>> ff = null; if (2.ToString() != null) { int a = 4; ff = () => () => (z) => (zz) => x + y + z + a + zz; } Console.WriteLine(ff()()(3)(3)); } } }"; CompileAndVerify(source, expectedOutput: "13"). VerifyIL("Program.c1.<>c__DisplayClass1_0.<Test>b__2", @"{ // Code size 31 (0x1f) .maxstack 3 IL_0000: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_000c: dup IL_000d: ldarg.1 IL_000e: stfld ""int Program.c1.<>c__DisplayClass1_1.z"" IL_0013: ldftn ""int Program.c1.<>c__DisplayClass1_1.<Test>b__3(int)"" IL_0019: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_001e: ret }"); } [Fact] public void ParentFrame02() { string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<int, Func<int>>>> ff = null; if (2.ToString() != null) { int a = 4; ff = () => () => (z) => () => x + y + z + a; } if (2.ToString() != null) { int a = 4; ff = () => () => (z) => () => x + y + z + a; } Console.WriteLine(ff()()(3)()); } } } "; CompileAndVerify(source, expectedOutput: "10"). VerifyIL("Program.c1.Test", @"{ // Code size 134 (0x86) .maxstack 3 .locals init (Program.c1.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Func<System.Func<System.Func<int, System.Func<int>>>> V_1, //ff int V_2) IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld ""int Program.c1.<>c__DisplayClass1_0.y"" IL_0014: ldnull IL_0015: stloc.1 IL_0016: ldc.i4.2 IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""string int.ToString()"" IL_001f: brfalse.s IL_0040 IL_0021: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0026: dup IL_0027: ldloc.0 IL_0028: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_002d: dup IL_002e: ldc.i4.4 IL_002f: stfld ""int Program.c1.<>c__DisplayClass1_1.a"" IL_0034: ldftn ""System.Func<System.Func<int, System.Func<int>>> Program.c1.<>c__DisplayClass1_1.<Test>b__0()"" IL_003a: newobj ""System.Func<System.Func<System.Func<int, System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_003f: stloc.1 IL_0040: ldc.i4.2 IL_0041: stloc.2 IL_0042: ldloca.s V_2 IL_0044: call ""string int.ToString()"" IL_0049: brfalse.s IL_006a IL_004b: newobj ""Program.c1.<>c__DisplayClass1_3..ctor()"" IL_0050: dup IL_0051: ldloc.0 IL_0052: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_3.CS$<>8__locals3"" IL_0057: dup IL_0058: ldc.i4.4 IL_0059: stfld ""int Program.c1.<>c__DisplayClass1_3.a"" IL_005e: ldftn ""System.Func<System.Func<int, System.Func<int>>> Program.c1.<>c__DisplayClass1_3.<Test>b__4()"" IL_0064: newobj ""System.Func<System.Func<System.Func<int, System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: callvirt ""System.Func<System.Func<int, System.Func<int>>> System.Func<System.Func<System.Func<int, System.Func<int>>>>.Invoke()"" IL_0070: callvirt ""System.Func<int, System.Func<int>> System.Func<System.Func<int, System.Func<int>>>.Invoke()"" IL_0075: ldc.i4.3 IL_0076: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_007b: callvirt ""int System.Func<int>.Invoke()"" IL_0080: call ""void System.Console.WriteLine(int)"" IL_0085: ret }"); } [Fact] public void ParentFrame03() { string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<Func<int>>>> ff = null; if (2.ToString() != null) { int z = 3; ff = () => () => () => () => x + y + z; } if (2.ToString() != null) { int z = 3; ff = () => () => () => () => x + y + z; } Console.WriteLine(ff()()()()); } } } "; CompileAndVerify(source, expectedOutput: "6"). VerifyIL("Program.c1.Test", @"{ // Code size 133 (0x85) .maxstack 3 .locals init (Program.c1.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Func<System.Func<System.Func<System.Func<int>>>> V_1, //ff int V_2) IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld ""int Program.c1.<>c__DisplayClass1_0.y"" IL_0014: ldnull IL_0015: stloc.1 IL_0016: ldc.i4.2 IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""string int.ToString()"" IL_001f: brfalse.s IL_0040 IL_0021: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0026: dup IL_0027: ldloc.0 IL_0028: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_002d: dup IL_002e: ldc.i4.3 IL_002f: stfld ""int Program.c1.<>c__DisplayClass1_1.z"" IL_0034: ldftn ""System.Func<System.Func<System.Func<int>>> Program.c1.<>c__DisplayClass1_1.<Test>b__0()"" IL_003a: newobj ""System.Func<System.Func<System.Func<System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_003f: stloc.1 IL_0040: ldc.i4.2 IL_0041: stloc.2 IL_0042: ldloca.s V_2 IL_0044: call ""string int.ToString()"" IL_0049: brfalse.s IL_006a IL_004b: newobj ""Program.c1.<>c__DisplayClass1_2..ctor()"" IL_0050: dup IL_0051: ldloc.0 IL_0052: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_2.CS$<>8__locals2"" IL_0057: dup IL_0058: ldc.i4.3 IL_0059: stfld ""int Program.c1.<>c__DisplayClass1_2.z"" IL_005e: ldftn ""System.Func<System.Func<System.Func<int>>> Program.c1.<>c__DisplayClass1_2.<Test>b__4()"" IL_0064: newobj ""System.Func<System.Func<System.Func<System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: callvirt ""System.Func<System.Func<System.Func<int>>> System.Func<System.Func<System.Func<System.Func<int>>>>.Invoke()"" IL_0070: callvirt ""System.Func<System.Func<int>> System.Func<System.Func<System.Func<int>>>.Invoke()"" IL_0075: callvirt ""System.Func<int> System.Func<System.Func<int>>.Invoke()"" IL_007a: callvirt ""int System.Func<int>.Invoke()"" IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: ret } "); } [Fact] public void ParentFrame04() { string source = @" using System; public static class Program { public static void Main() { var c = new c1(); System.Console.WriteLine(c.Test()); } class c1 { public int goo = 42; public object Test() { if (T()) { Func<int, Boolean> a = (s) => s == goo && ((Func<bool>)(() => s == goo)).Invoke(); return a.Invoke(42); } int aaa = 42; if (T()) { Func<int, bool> a = (s) => aaa == goo; return a.Invoke(42); } return null; } private bool T() { return true; } } } "; CompileAndVerify(source, expectedOutput: "True"). VerifyIL("Program.c1.Test", @" { // Code size 89 (0x59) .maxstack 2 .locals init (Program.c1.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldarg.0 IL_000e: call ""bool Program.c1.T()"" IL_0013: brfalse.s IL_002e IL_0015: ldloc.0 IL_0016: ldftn ""bool Program.c1.<>c__DisplayClass1_0.<Test>b__0(int)"" IL_001c: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0021: ldc.i4.s 42 IL_0023: callvirt ""bool System.Func<int, bool>.Invoke(int)"" IL_0028: box ""bool"" IL_002d: ret IL_002e: ldloc.0 IL_002f: ldc.i4.s 42 IL_0031: stfld ""int Program.c1.<>c__DisplayClass1_0.aaa"" IL_0036: ldarg.0 IL_0037: call ""bool Program.c1.T()"" IL_003c: brfalse.s IL_0057 IL_003e: ldloc.0 IL_003f: ldftn ""bool Program.c1.<>c__DisplayClass1_0.<Test>b__2(int)"" IL_0045: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_004a: ldc.i4.s 42 IL_004c: callvirt ""bool System.Func<int, bool>.Invoke(int)"" IL_0051: box ""bool"" IL_0056: ret IL_0057: ldnull IL_0058: ret } "); } [Fact] public void ParentFrame05() { // IMPORTANT: Program.c1.<>c__DisplayClass1_0 should not capture any frame pointers. string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { Func<int> ff = null; Func<int> aa = null; if (T()) { int a = 1; if (T()) { int b = 4; ff = () => a + b; aa = () => x; } } Console.WriteLine(ff() + aa()); } private bool T() { return true; } } } "; CompileAndVerify(source, expectedOutput: "6"). VerifyIL("Program.c1.Test", @"{ // Code size 85 (0x55) .maxstack 2 .locals init (System.Func<int> V_0, //ff System.Func<int> V_1, //aa Program.c1.<>c__DisplayClass1_0 V_2) //CS$<>8__locals0 IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldarg.0 IL_0005: call ""bool Program.c1.T()"" IL_000a: brfalse.s IL_0042 IL_000c: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.1 IL_0014: stfld ""int Program.c1.<>c__DisplayClass1_0.a"" IL_0019: ldarg.0 IL_001a: call ""bool Program.c1.T()"" IL_001f: brfalse.s IL_0042 IL_0021: ldloc.2 IL_0022: ldc.i4.4 IL_0023: stfld ""int Program.c1.<>c__DisplayClass1_0.b"" IL_0028: ldloc.2 IL_0029: ldftn ""int Program.c1.<>c__DisplayClass1_0.<Test>b__0()"" IL_002f: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0034: stloc.0 IL_0035: ldarg.0 IL_0036: ldftn ""int Program.c1.<Test>b__1_1()"" IL_003c: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0041: stloc.1 IL_0042: ldloc.0 IL_0043: callvirt ""int System.Func<int>.Invoke()"" IL_0048: ldloc.1 IL_0049: callvirt ""int System.Func<int>.Invoke()"" IL_004e: add IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: ret }"); } [Fact] public void ClosuresInConstructorAndInitializers1() { string source = @" using System; class C { int f1 = new Func<int, int>(x => 1)(1); int f2 = new Func<int, int>(x => 2)(1); C() { int l = new Func<int, int>(x => 3)(1); } }"; CompileAndVerify(source); } [Fact] public void ClosuresInConstructorAndInitializers2() { string source = @" using System; class C { int f1 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); int f2 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } }"; CompileAndVerify(source); } [Fact] public void ClosuresInConstructorAndInitializers3() { string source = @" using System; class C { static int f1 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static int f2 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } }"; CompileAndVerify(source); } [Fact] public void GenericStaticFrames() { string source = @" using System; public class C { public static void F<TF>() { var f = new Func<TF>(() => default(TF)); } public static void G<TG>() { var f = new Func<TG>(() => default(TG)); } public static void F<TF1, TF2>() { var f = new Func<TF1, TF2>(a => default(TF2)); } public static void G<TG1, TG2>() { var f = new Func<TG1, TG2>(a => default(TG2)); } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.Equal(new[] { "C.<>c__0<TF>", "C.<>c__1<TG>", "C.<>c__2<TF1, TF2>", "C.<>c__3<TG1, TG2>" }, c.GetMembers().Where(member => member.Kind == SymbolKind.NamedType).Select(member => member.ToString())); var c0 = c.GetMember<NamedTypeSymbol>("<>c__0"); AssertEx.SetEqual(new[] { "C.<>c__0<TF>.<>9", "C.<>c__0<TF>.<>9__0_0", "C.<>c__0<TF>.<>c__0()", "C.<>c__0<TF>.<>c__0()", "C.<>c__0<TF>.<F>b__0_0()", }, c0.GetMembers().Select(member => member.ToString())); var c1 = c.GetMember<NamedTypeSymbol>("<>c__1"); AssertEx.SetEqual(new[] { "C.<>c__1<TG>.<>9", "C.<>c__1<TG>.<>9__1_0", "C.<>c__1<TG>.<>c__1()", "C.<>c__1<TG>.<>c__1()", "C.<>c__1<TG>.<G>b__1_0()", }, c1.GetMembers().Select(member => member.ToString())); var c2 = c.GetMember<NamedTypeSymbol>("<>c__2"); AssertEx.SetEqual(new[] { "C.<>c__2<TF1, TF2>.<>9", "C.<>c__2<TF1, TF2>.<>9__2_0", "C.<>c__2<TF1, TF2>.<>c__2()", "C.<>c__2<TF1, TF2>.<>c__2()", "C.<>c__2<TF1, TF2>.<F>b__2_0(TF1)", }, c2.GetMembers().Select(member => member.ToString())); var c3 = c.GetMember<NamedTypeSymbol>("<>c__3"); AssertEx.SetEqual(new[] { "C.<>c__3<TG1, TG2>.<>9", "C.<>c__3<TG1, TG2>.<>9__3_0", "C.<>c__3<TG1, TG2>.<>c__3()", "C.<>c__3<TG1, TG2>.<>c__3()", "C.<>c__3<TG1, TG2>.<G>b__3_0(TG1)", }, c3.GetMembers().Select(member => member.ToString())); }); } [Fact] public void GenericStaticFramesWithConstraints() { string source = @" using System; public class C { public static void F<TF>() where TF : class { var f = new Func<TF>(() => default(TF)); } public static void G<TG>() where TG : struct { var f = new Func<TG>(() => default(TG)); } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.Equal(new[] { "C.<>c__0<TF>", "C.<>c__1<TG>", }, c.GetMembers().Where(member => member.Kind == SymbolKind.NamedType).Select(member => member.ToString())); }); } [Fact] public void GenericInstance() { string source = @" using System; public class C { public void F<TF>() { var f = new Func<TF>(() => { this.F(); return default(TF); }); } public void G<TG>() { var f = new Func<TG>(() => { this.F(); return default(TG); }); } public void F<TF1, TF2>() { var f = new Func<TF1, TF2>(a => { this.F(); return default(TF2); }); } public void G<TG1, TG2>() { var f = new Func<TG1, TG2>(a => { this.F(); return default(TG2); }); } private void F() {} }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.SetEqual(new[] { "C.F<TF>()", "C.G<TG>()", "C.F<TF1, TF2>()", "C.G<TG1, TG2>()", "C.F()", "C.C()", "C.<F>b__0_0<TF>()", "C.<G>b__1_0<TG>()", "C.<F>b__2_0<TF1, TF2>(TF1)", "C.<G>b__3_0<TG1, TG2>(TG1)", }, c.GetMembers().Select(member => member.ToString())); }); } #region "Regressions" [WorkItem(539439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539439")] [Fact] public void LambdaWithReturn() { string source = @" using System; class Program { delegate int Func(int i, int r); static void Main(string[] args) { Func fnc = (arg, arg2) => { return 1 + 2; }; Console.Write(fnc(3, 4)); } }"; CompileAndVerify(source, expectedOutput: @"3"); } /// <remarks> /// Based on MadsT blog post: /// http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx /// </remarks> [WorkItem(540034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540034")] [Fact] public void YCombinatorTest() { var source = @" using System; using System.Linq; public class Program { delegate T SelfApplicable<T>(SelfApplicable<T> self); static void Main() { // The Y combinator SelfApplicable< Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> > Y = y => f => x => f(y(y)(f))(x); // The fixed point generator Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> Fix = Y(Y); // The higher order function describing factorial Func<Func<int, int>, Func<int, int>> F = fac => x => { if (x == 0) { return 1; } else { return x * fac(x - 1); } }; // The factorial function itself Func<int, int> factorial = Fix(F); Console.WriteLine(string.Join( Environment.NewLine, Enumerable.Select(Enumerable.Range(0, 12), factorial))); } } "; CompileAndVerify( source, expectedOutput: @"1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800" ); } [WorkItem(540035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540035")] [Fact] public void LongNameTest() { var source = @" using System; namespace Lambda.Bugs { public interface I<T> { void Goo(int x); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo(int x) { Func<int> f = () => x; Console.WriteLine(f()); } } } public class Program { public static void Main() { I<OuterGenericClass<int, int>.NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> x = new OuterGenericClass<int, int>.C(); x.Goo(1); } } } "; CreateCompilation(source).VerifyEmitDiagnostics( // (17,81): error CS7013: Name 'Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo' exceeds the maximum length allowed in metadata. // void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo(int x) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo").WithLocation(17, 81), // (19,31): error CS7013: Name '<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0' exceeds the maximum length allowed in metadata. // Func<int> f = () => x; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => x").WithArguments("<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0").WithLocation(19, 31), // (19,31): error CS7013: Name '<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0' exceeds the maximum length allowed in metadata. // Func<int> f = () => x; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => x").WithArguments("<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0").WithLocation(19, 31) ); } [WorkItem(540049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540049")] [Fact] public void LambdaWithUnreachableCode() { var source = @" using System; class Program { static void Main() { int x = 7; Action f = () => { int y; Console.Write(x); return; int z = y; }; f(); } } "; CompileAndVerify(source, expectedOutput: "7"); } [Fact] [WorkItem(1019237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019237")] [WorkItem(10838, "https://github.com/mono/mono/issues/10838")] public void OrderOfDelegateMembers() { var source = @" using System.Linq; class Program { delegate int D1(); static void Main() { foreach (var member in typeof(D1).GetMembers( System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).OrderBy(m=>m.MetadataToken)) { System.Console.WriteLine(member.ToString()); } } } "; // ref emit would just have different metadata tokens // we are not interested in testing that CompileAndVerify(source, expectedOutput: @" Void .ctor(System.Object, IntPtr) Int32 Invoke() System.IAsyncResult BeginInvoke(System.AsyncCallback, System.Object) Int32 EndInvoke(System.IAsyncResult) "); } [WorkItem(540092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540092")] [Fact] public void NestedAnonymousMethodsUsingLocalAndField() { string source = @" using System; delegate void MyDel(int i); class Test { int j = 1; static int Main() { Test t = new Test(); t.goo(); return 0; } void goo() { int l = 0; MyDel d = delegate { Console.WriteLine(l++); }; d = delegate(int i) { MyDel dd = delegate(int k) { Console.WriteLine(i + j + k); }; dd(10); }; d(100); } } "; CompileAndVerify(source, expectedOutput: "111"); } [WorkItem(540129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540129")] [Fact] public void CacheStaticAnonymousMethodInField() { string source = @" using System; delegate void D(); public delegate void E<T, U>(T t, U u); public class Gen<T> { public static void Goo<U>(T t, U u) { ((D)delegate { ((E<T, U>)delegate(T t2, U u2) { // do nothing in order to allow this anonymous method to be cached in a static field })(t, u); })(); } } public class Test { public static void Main() { Gen<int>.Goo<string>(1, ""2""); Console.WriteLine(""PASS""); } } "; CompileAndVerify(source, expectedOutput: "PASS"); } [WorkItem(540147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540147")] [Fact] public void CapturedVariableNamedThis() { var source = @" using System; class A { public int N; public A(int n) { this.N = n; } public void Goo(A @this) { Action a = () => Bar(@this); a.Invoke(); } public void Bar(A other) { Console.Write(this.N); Console.Write(other.N); } static void Main() { A a = new A(1); A b = new A(2); a.Goo(b); } } "; var verifier = CompileAndVerify( source, expectedOutput: "12"); } [Fact] public void StaticClosureSerialize() { string source = @" using System; class Program { static void Main(string[] args) { Func<int> x = () => 42; System.Console.WriteLine(x.Target.GetType().IsSerializable); Func<int> y = () => x(); System.Console.WriteLine(y.Target.GetType().IsSerializable); } } "; var compilation = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"True False"); } [Fact] public void StaticClosureSerializeD() { string source = @" using System; class Program { static void Main(string[] args) { Func<int> x = () => 42; System.Console.WriteLine(x.Target.GetType().IsSerializable); Func<int> y = () => x(); System.Console.WriteLine(y.Target.GetType().IsSerializable); } } "; var compilation = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"True False"); } [WorkItem(540178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540178")] [Fact] public void NestedGenericLambda() { var source = @" using System; class Program { static void Main() { Goo<int>()()(); } static Func<Func<T>> Goo<T>() { T[] x = new T[1]; return () => () => x[0]; } } "; var verifier = CompileAndVerify( source, expectedOutput: ""); } [WorkItem(540768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540768")] [Fact] public void TestClosureMethodAccessibility() { var source = @" using System; class Test { static void Main() { } Func<int, int> f = (x) => 0; Func<string, string> Goo() { string s = """"; Console.WriteLine(s); return (a) => s; } }"; // Dev11 emits "public", we emit "internal" visibility for <Goo>b__1: CompileAndVerify(source, expectedSignatures: new[] { Signature("Test+<>c__DisplayClass2_0", "<Goo>b__0", ".method assembly hidebysig instance System.String <Goo>b__0(System.String a) cil managed"), }); } [WorkItem(541008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541008")] [Fact] public void TooEarlyForThis() { // this tests for the C# analogue of VB bug 7520 var source = @"using System; class Program { int x; Program(int x) : this(z => x + 10) { this.x = x + 100; F(z => z + x + this.x + 1000); } Program(Func<int, int> func) {} void F(Func<int, int> func) { Console.Write(func(10000)); } public static void Main(string[] args) { new Program(1); } }"; var verifier = CompileAndVerify( source, expectedOutput: "11102"); } [WorkItem(542062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542062")] [Fact] public void TestLambdaNoClosureClass() { var source = @" using System; delegate int D(); class Test { static D field = () => field2; static short field2 = -1; public static void Main() { D myd = delegate() { return 1; }; Console.WriteLine(""({0},{1})"", myd(), field()); } } "; //IMPORTANT!!! we should not be caching static lambda in static initializer. CompileAndVerify(source, expectedOutput: "(1,-1)").VerifyIL("Test..cctor", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldsfld ""Test.<>c Test.<>c.<>9"" IL_0005: ldftn ""int Test.<>c.<.cctor>b__4_0()"" IL_000b: newobj ""D..ctor(object, System.IntPtr)"" IL_0010: stsfld ""D Test.field"" IL_0015: ldc.i4.m1 IL_0016: stsfld ""short Test.field2"" IL_001b: ret } "); } [WorkItem(543087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543087")] [Fact] public void LambdaInGenericMethod() { var source = @" using System; delegate bool D(); class G<T> where T : class { public T Fld = default(T); public static bool RunTest<U>(U u) where U : class { G<U> g = new G<U>(); g.Fld = u; return ((D)(() => Test.Eval(g.Fld == u, true)))(); } } class Test { public static bool Eval(object obj1, object obj2) { return obj1.Equals(obj2); } static void Main() { var ret = G<string>.RunTest((string)null); Console.Write(ret); } } "; var verifier = CompileAndVerify( source, expectedOutput: "True"); } [WorkItem(543344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543344")] [Fact] public void AnonymousMethodOmitParameterList() { var source = @" using System; class C { public int M() { Func<C, int> f = delegate { return 9; } ; return f(new C()); } static void Main() { int r = new C().M(); Console.WriteLine((r == 9) ? 0 : 1); } } "; var verifier = CompileAndVerify( source, expectedOutput: "0"); } [WorkItem(543345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543345")] [Fact()] public void ExtraCompilerGeneratedAttribute() { string source = @"using System; using System.Reflection; using System.Runtime.CompilerServices; class Test { static public System.Collections.IEnumerable myIterator(int start, int end) { for (int i = start; i <= end; i++) { yield return (Func<int,int>)((x) => { return i + x; }); } yield break; } static void Main() { var type = typeof(Test); var nested = type.GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance); var total = 0; if (nested.Length > 0 && nested[0].Name.StartsWith(""<>c__DisplayClass"", StringComparison.Ordinal)) { foreach (MemberInfo mi in nested[0].GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { var ca = mi.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false); foreach (var a in ca) Console.WriteLine(mi + "": "" + a); total += ca.Length; } } Console.WriteLine(total); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(545430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545430")] [Fact] public void CacheNonStaticLambdaInGenericMethod() { var source = @" using System.Collections.Generic; using System.Linq; class C { static void M<T>(List<T> dd, int p) where T : D { do{ if (dd != null) { var last = dd.LastOrDefault(m => m.P <= p); if (dd.Count() > 1) { dd.Reverse(); } } } while(false); } } class D { public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp, expectedSignatures: new[] { Signature("C+<>c__DisplayClass0_0`1", "<>9__0", ".field public instance System.Func`2[T,System.Boolean] <>9__0") }); verifier.VerifyIL("C.M<T>", @" { // Code size 70 (0x46) .maxstack 4 .locals init (C.<>c__DisplayClass0_0<T> V_0, //CS$<>8__locals0 System.Func<T, bool> V_1) IL_0000: newobj ""C.<>c__DisplayClass0_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""int C.<>c__DisplayClass0_0<T>.p"" IL_000d: ldarg.0 IL_000e: brfalse.s IL_0045 IL_0010: ldarg.0 IL_0011: ldloc.0 IL_0012: ldfld ""System.Func<T, bool> C.<>c__DisplayClass0_0<T>.<>9__0"" IL_0017: dup IL_0018: brtrue.s IL_0030 IL_001a: pop IL_001b: ldloc.0 IL_001c: ldloc.0 IL_001d: ldftn ""bool C.<>c__DisplayClass0_0<T>.<M>b__0(T)"" IL_0023: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stloc.1 IL_002a: stfld ""System.Func<T, bool> C.<>c__DisplayClass0_0<T>.<>9__0"" IL_002f: ldloc.1 IL_0030: call ""T System.Linq.Enumerable.LastOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)"" IL_0035: pop IL_0036: ldarg.0 IL_0037: call ""int System.Linq.Enumerable.Count<T>(System.Collections.Generic.IEnumerable<T>)"" IL_003c: ldc.i4.1 IL_003d: ble.s IL_0045 IL_003f: ldarg.0 IL_0040: callvirt ""void System.Collections.Generic.List<T>.Reverse()"" IL_0045: ret } "); } [Fact] public void CacheNonStaticLambda001() { var source = @" using System; class Program { static void Main(string[] args) { } class Executor { public void Execute(Func<int, int> f) { f(42); } } Executor[] arr = new Executor[] { new Executor() }; void Test() { int x = 123; for (int i = 1; i < 10; i++) { if (i < 2) { arr[i].Execute(arg => arg + x); // delegate should be cached } } for (int i = 1; i < 10; i++) { var val = i; if (i < 2) { int y = i + i; System.Console.WriteLine(y); arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop) } } } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp); verifier.VerifyIL("Program.Test", @" { // Code size 142 (0x8e) .maxstack 4 .locals init (Program.<>c__DisplayClass3_0 V_0, //CS$<>8__locals0 int V_1, //i System.Func<int, int> V_2, int V_3, //i Program.<>c__DisplayClass3_1 V_4) //CS$<>8__locals1 IL_0000: newobj ""Program.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.s 123 IL_0009: stfld ""int Program.<>c__DisplayClass3_0.x"" IL_000e: ldc.i4.1 IL_000f: stloc.1 IL_0010: br.s IL_0046 IL_0012: ldloc.1 IL_0013: ldc.i4.2 IL_0014: bge.s IL_0042 IL_0016: ldarg.0 IL_0017: ldfld ""Program.Executor[] Program.arr"" IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: ldloc.0 IL_001f: ldfld ""System.Func<int, int> Program.<>c__DisplayClass3_0.<>9__0"" IL_0024: dup IL_0025: brtrue.s IL_003d IL_0027: pop IL_0028: ldloc.0 IL_0029: ldloc.0 IL_002a: ldftn ""int Program.<>c__DisplayClass3_0.<Test>b__0(int)"" IL_0030: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0035: dup IL_0036: stloc.2 IL_0037: stfld ""System.Func<int, int> Program.<>c__DisplayClass3_0.<>9__0"" IL_003c: ldloc.2 IL_003d: callvirt ""void Program.Executor.Execute(System.Func<int, int>)"" IL_0042: ldloc.1 IL_0043: ldc.i4.1 IL_0044: add IL_0045: stloc.1 IL_0046: ldloc.1 IL_0047: ldc.i4.s 10 IL_0049: blt.s IL_0012 IL_004b: ldc.i4.1 IL_004c: stloc.3 IL_004d: br.s IL_0088 IL_004f: newobj ""Program.<>c__DisplayClass3_1..ctor()"" IL_0054: stloc.s V_4 IL_0056: ldloc.s V_4 IL_0058: ldloc.3 IL_0059: stfld ""int Program.<>c__DisplayClass3_1.val"" IL_005e: ldloc.3 IL_005f: ldc.i4.2 IL_0060: bge.s IL_0084 IL_0062: ldloc.3 IL_0063: ldloc.3 IL_0064: add IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: ldarg.0 IL_006b: ldfld ""Program.Executor[] Program.arr"" IL_0070: ldloc.3 IL_0071: ldelem.ref IL_0072: ldloc.s V_4 IL_0074: ldftn ""int Program.<>c__DisplayClass3_1.<Test>b__1(int)"" IL_007a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_007f: callvirt ""void Program.Executor.Execute(System.Func<int, int>)"" IL_0084: ldloc.3 IL_0085: ldc.i4.1 IL_0086: add IL_0087: stloc.3 IL_0088: ldloc.3 IL_0089: ldc.i4.s 10 IL_008b: blt.s IL_004f IL_008d: ret } "); } [Fact] public void CacheNonStaticLambda002() { var source = @" using System; class Program { static void Main(string[] args) { } void Test() { int y = 123; Func<int, Func<int>> f1 = // should be cached (x) => { if (x > 0) { int z = 123; System.Console.WriteLine(z); return () => y; } return null; }; f1(1); Func<int, Func<int>> f2 = // should NOT be cached (x) => { if (x > 0) { int z = 123; System.Console.WriteLine(z); return () => x; } return null; }; f2(1); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp); verifier.VerifyIL("Program.Test", @" { // Code size 70 (0x46) .maxstack 3 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: dup IL_0006: ldc.i4.s 123 IL_0008: stfld ""int Program.<>c__DisplayClass1_0.y"" IL_000d: ldftn ""System.Func<int> Program.<>c__DisplayClass1_0.<Test>b__0(int)"" IL_0013: newobj ""System.Func<int, System.Func<int>>..ctor(object, System.IntPtr)"" IL_0018: ldc.i4.1 IL_0019: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_001e: pop IL_001f: ldsfld ""System.Func<int, System.Func<int>> Program.<>c.<>9__1_1"" IL_0024: dup IL_0025: brtrue.s IL_003e IL_0027: pop IL_0028: ldsfld ""Program.<>c Program.<>c.<>9"" IL_002d: ldftn ""System.Func<int> Program.<>c.<Test>b__1_1(int)"" IL_0033: newobj ""System.Func<int, System.Func<int>>..ctor(object, System.IntPtr)"" IL_0038: dup IL_0039: stsfld ""System.Func<int, System.Func<int>> Program.<>c.<>9__1_1"" IL_003e: ldc.i4.1 IL_003f: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_0044: pop IL_0045: ret } "); verifier.VerifyIL("Program.<>c.<Test>b__1_1(int)", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (Program.<>c__DisplayClass1_1 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_1..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""int Program.<>c__DisplayClass1_1.x"" IL_000d: ldloc.0 IL_000e: ldfld ""int Program.<>c__DisplayClass1_1.x"" IL_0013: ldc.i4.0 IL_0014: ble.s IL_002a IL_0016: ldc.i4.s 123 IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: ldloc.0 IL_001e: ldftn ""int Program.<>c__DisplayClass1_1.<Test>b__3()"" IL_0024: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0029: ret IL_002a: ldnull IL_002b: ret } " ); verifier.VerifyIL("Program.<>c__DisplayClass1_0.<Test>b__0(int)", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Func<int> V_0) IL_0000: ldarg.1 IL_0001: ldc.i4.0 IL_0002: ble.s IL_002b IL_0004: ldc.i4.s 123 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: ldarg.0 IL_000c: ldfld ""System.Func<int> Program.<>c__DisplayClass1_0.<>9__2"" IL_0011: dup IL_0012: brtrue.s IL_002a IL_0014: pop IL_0015: ldarg.0 IL_0016: ldarg.0 IL_0017: ldftn ""int Program.<>c__DisplayClass1_0.<Test>b__2()"" IL_001d: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0022: dup IL_0023: stloc.0 IL_0024: stfld ""System.Func<int> Program.<>c__DisplayClass1_0.<>9__2"" IL_0029: ldloc.0 IL_002a: ret IL_002b: ldnull IL_002c: ret } " ); } [WorkItem(546211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546211")] [Fact] public void LambdaInCatchInLambdaInInstance() { var source = @"using System; static class Utilities { internal static void ReportException(object _componentModelHost, Exception e, string p) { } internal static void BeginInvoke(Action a) { } } class VsCatalogProvider { private object _componentModelHost = null; static void Main() { Console.WriteLine(""success""); } private void TryIsolatedOperation() { Action action = new Action(() => { try { } catch (Exception ex) { Utilities.BeginInvoke(new Action(() => { Utilities.ReportException(_componentModelHost, ex, string.Empty); })); } }); } }"; var compilation = CompileAndVerify(source, expectedOutput: "success"); } [WorkItem(546748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546748")] [Fact] public void LambdaWithCatchTypeParameter() { var source = @"using System; class Program { static void Main() { } public static void Sleep<TException>(Func<bool> sleepDelegate) where TException : Exception { Func<bool> x = delegate { try { return sleepDelegate(); } catch (TException e) { } return false; }; } }"; CompileAndVerify(source); } [WorkItem(546748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546748")] [Fact] public void LambdaWithCapturedCatchTypeParameter() { var source = @"using System; class Program { static void Main() { } public static void Sleep<TException>(Func<bool> sleepDelegate) where TException : Exception { Func<bool> x = delegate { try { return sleepDelegate(); } catch (TException e) { Func<bool> x2 = delegate { return e == null; }; } return false; }; } }"; var compilation = CompileAndVerify(source); } [WorkItem(530911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530911")] [Fact] public void LambdaWithOutParameter() { var source = @" using System; delegate D D(out D d); class Program { static void Main() { D tmpD = delegate (out D d) { throw new System.Exception(); }; D d01 = delegate (out D d) { tmpD(out d); d(out d); return d; }; } } "; var compilation = CompileAndVerify(source); } [WorkItem(691006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691006")] [Fact] public void LambdaWithSwitch() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication16 { class Program { public static Task<IEnumerable<TResult>> Iterate<TResult>(IEnumerable<Task> asyncIterator, CancellationToken cancellationToken = default(CancellationToken)) { var results = new List<TResult>(); var tcs = new TaskCompletionSource<IEnumerable<TResult>>(); IEnumerator<Task> enumerator = asyncIterator.GetEnumerator(); Action recursiveBody = null; recursiveBody = () => { try { if (cancellationToken.IsCancellationRequested) { tcs.TrySetCanceled(); } else if (enumerator.MoveNext()) { enumerator.Current.ContinueWith(previous => { switch (previous.Status) { case TaskStatus.Faulted: case TaskStatus.Canceled: tcs.SetResult((previous as Task<IEnumerable<TResult>>).Result); break; default: var previousWithResult = previous as Task<TResult>; if (previousWithResult != null) { results.Add(previousWithResult.Result); } else { results.Add(default(TResult)); } recursiveBody(); break; } }); } else { tcs.TrySetResult(results); } } catch (Exception e) { tcs.TrySetException(e); } }; recursiveBody(); return tcs.Task; } static void Main(string[] args) { } } } "; CompileAndVerify(source); } #endregion [Fact] public void LambdaInQuery_Let() { var source = @" using System; using System.Linq; class C { public void F(int[] array) { var f = from item in array let a = new Func<int>(() => item) select a() + new Func<int>(() => item)(); } }"; CompileAndVerify(source); } [Fact] public void LambdaInQuery_From() { var source = @" using System; using System.Linq; class C { public void F(int[] array) { var f = from item1 in new Func<int[]>(() => array)() from item2 in new Func<int[]>(() => array)() select item1 + item2; } }"; CompileAndVerify(source); } [Fact] public void EmbeddedStatementClosures1() { var source = @" using System; using System.Collections.Generic; using System.IO; using System.Linq; class C { public void G<T>(Func<T> f) {} public void F() { for (int x = 1, y = 2; x < 10; x++) G(() => x + y); for (int x = 1, y = 2; x < 10; x++) { G(() => x + y); } foreach (var x in new[] { 1, 2, 3 }) G(() => x); foreach (var x in new[] { 1, 2, 3 }) { G(() => x); } foreach (var x in new[,] { {1}, {2}, {3} }) G(() => x); foreach (var x in new[,] { {1}, {2}, {3} }) { G(() => x); } foreach (var x in ""123"") G(() => x); foreach (var x in ""123"") { G(() => x); } foreach (var x in new List<string>()) G(() => x); foreach (var x in new List<string>()) { G(() => x); } using (var x = new MemoryStream()) G(() => x); using (var x = new MemoryStream()) G(() => x); } }"; CompileAndVerify(source); } [Fact, WorkItem(2549, "https://github.com/dotnet/roslyn/issues/2549")] public void NestedLambdaWithExtensionMethodsInGeneric() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class BadBaby { IEnumerable<object> Children; public object Goo<T>() { return from child in Children select from T ch in Children select false; } }"; CompileAndVerify(source); } [WorkItem(9131, "https://github.com/dotnet/roslyn/issues/9131")] [Fact] public void ClosureInSwitchStatementWithNullableExpression() { string source = @"using System; class C { static void Main() { int? i = null; switch (i) { default: object o = null; Func<object> f = () => o; Console.Write(""{0}"", f() == null); break; case 0: o = 1; break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"True"); compilation.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (int? V_0, //i C.<>c__DisplayClass0_0 V_1, //CS$<>8__locals0 System.Func<object> V_2) //f IL_0000: ldloca.s V_0 IL_0002: initobj ""int?"" IL_0008: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_0 IL_0010: call ""bool int?.HasValue.get"" IL_0015: brfalse.s IL_0020 IL_0017: ldloca.s V_0 IL_0019: call ""int int?.GetValueOrDefault()"" IL_001e: brfalse.s IL_004d IL_0020: ldloc.1 IL_0021: ldnull IL_0022: stfld ""object C.<>c__DisplayClass0_0.o"" IL_0027: ldloc.1 IL_0028: ldftn ""object C.<>c__DisplayClass0_0.<Main>b__0()"" IL_002e: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0033: stloc.2 IL_0034: ldstr ""{0}"" IL_0039: ldloc.2 IL_003a: callvirt ""object System.Func<object>.Invoke()"" IL_003f: ldnull IL_0040: ceq IL_0042: box ""bool"" IL_0047: call ""void System.Console.Write(string, object)"" IL_004c: ret IL_004d: ldloc.1 IL_004e: ldc.i4.1 IL_004f: box ""int"" IL_0054: stfld ""object C.<>c__DisplayClass0_0.o"" IL_0059: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly() { // The lambda passed into StaticMethod depends on TLocal type argument of LocalMethod // so if the delegate is cached outside the method the type argument reference is broken // and code throws BadImageFormatException. Such a broken code will looks like: // class DisplayClass // { // Func<TLocal, string> _cachedDelegate; // // void LocalMethod<TLocal>() // { // ... // } // // The test checks that it is not the issue. string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } /// <summary> /// Check <see cref="LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly"/> summary /// for the test case description /// </summary> [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter2_CompilesCorrectly() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { InnerLocalFunction(); void InnerLocalFunction() { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } /// <summary> /// Check <see cref="LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly"/> summary /// for the test case description /// </summary> [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter3_CompilesCorrectly() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; OuterLocalFunction(); void OuterLocalFunction() { for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideLocalFunctionInsideLoop_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalMethod() { StaticMethod(message, _ => message); } message = i.ToString(); LocalMethod(); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.<>c__DisplayClass0_0.<Main>g__LocalMethod|0()", @"{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Func<string, string> V_0) IL_0000: ldarg.0 IL_0001: ldfld ""string Program.<>c__DisplayClass0_0.message"" IL_0006: ldarg.0 IL_0007: ldfld ""System.Func<string, string> Program.<>c__DisplayClass0_0.<>9__1"" IL_000c: dup IL_000d: brtrue.s IL_0025 IL_000f: pop IL_0010: ldarg.0 IL_0011: ldarg.0 IL_0012: ldftn ""string Program.<>c__DisplayClass0_0.<Main>b__1(string)"" IL_0018: newobj ""System.Func<string, string>..ctor(object, System.IntPtr)"" IL_001d: dup IL_001e: stloc.0 IL_001f: stfld ""System.Func<string, string> Program.<>c__DisplayClass0_0.<>9__1"" IL_0024: ldloc.0 IL_0025: call ""void Program.StaticMethod<string, string>(string, System.Func<string, string>)"" IL_002a: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingMethodTypeParameter_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { message = i.ToString(); StaticMethod(param, _ => message); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.TestMethod<T>(T)", @"{ // Code size 80 (0x50) .maxstack 4 .locals init (Program.<>c__DisplayClass1_0<T> V_0, //CS$<>8__locals0 int V_1, //i System.Func<T, string> V_2) IL_0000: newobj ""Program.<>c__DisplayClass1_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld ""string string.Empty"" IL_000c: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_004b IL_0015: ldloc.0 IL_0016: ldloca.s V_1 IL_0018: call ""string int.ToString()"" IL_001d: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0022: ldarg.0 IL_0023: ldloc.0 IL_0024: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0029: dup IL_002a: brtrue.s IL_0042 IL_002c: pop IL_002d: ldloc.0 IL_002e: ldloc.0 IL_002f: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__0(T)"" IL_0035: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_003a: dup IL_003b: stloc.2 IL_003c: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0041: ldloc.2 IL_0042: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_0047: ldloc.1 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: ldc.i4.1 IL_004d: blt.s IL_0015 IL_004f: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideGenericLocalFunction_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(param, _ => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.<>c__DisplayClass1_0<T>.<TestMethod>g__LocalFunction|0<TLocal>(TLocal)", @"{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Func<T, string> V_0) IL_0000: ldarg.0 IL_0001: ldfld ""T Program.<>c__DisplayClass1_0<T>.param"" IL_0006: ldarg.0 IL_0007: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__1"" IL_000c: dup IL_000d: brtrue.s IL_0025 IL_000f: pop IL_0010: ldarg.0 IL_0011: ldarg.0 IL_0012: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__1<TLocal>(T)"" IL_0018: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_001d: dup IL_001e: stloc.0 IL_001f: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__1"" IL_0024: ldloc.0 IL_0025: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_002a: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideGenericMethod_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { message = i.ToString(); StaticMethod(param, _ => message); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.TestMethod<T>(T)", @"{ // Code size 80 (0x50) .maxstack 4 .locals init (Program.<>c__DisplayClass1_0<T> V_0, //CS$<>8__locals0 int V_1, //i System.Func<T, string> V_2) IL_0000: newobj ""Program.<>c__DisplayClass1_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld ""string string.Empty"" IL_000c: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_004b IL_0015: ldloc.0 IL_0016: ldloca.s V_1 IL_0018: call ""string int.ToString()"" IL_001d: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0022: ldarg.0 IL_0023: ldloc.0 IL_0024: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0029: dup IL_002a: brtrue.s IL_0042 IL_002c: pop IL_002d: ldloc.0 IL_002e: ldloc.0 IL_002f: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__0(T)"" IL_0035: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_003a: dup IL_003b: stloc.2 IL_003c: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0041: ldloc.2 IL_0042: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_0047: ldloc.1 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: ldc.i4.1 IL_004d: blt.s IL_0015 IL_004f: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenClosureLambdaTests : CSharpTestBase { [Fact] public void LambdaInIndexerAndBinaryOperator() { var verifier = CompileAndVerify(@" using System; class C { private static Func<int> _f1; private static Func<int> _f2; public static void Main() { var c = new C(); c[() => 0] += 1; Console.WriteLine(object.ReferenceEquals(_f1, _f2)); } int this[Func<int> f] { get { _f1 = f; return 0; } set { _f2 = f; } } }", expectedOutput: "True"); } [Fact] public void MethodGroupInIndexerAndBinaryOperator() { CompileAndVerify(@" using System; class C { private static Func<int> _f1; private static Func<int> _f2; public static void Main() { var c = new C(); c[F] += 1; Console.WriteLine(object.ReferenceEquals(_f1, _f2)); } static int F() => 0; public int this[Func<int> f] { get { _f1 = f; return 0; } set { _f2 = f; } } }", expectedOutput: "True"); } [Fact] public void EnvironmentChainContainsUnusedEnvironment() { CompileAndVerify(@" using System; class C { void M(int x) { { int y = 10; Action f1 = () => Console.WriteLine(y); { int z = 5; Action f2 = () => Console.WriteLine(z + x); f2(); } f1(); } } public static void Main() => new C().M(3); }", expectedOutput: @"8 10"); } [Fact] public void CaptureThisAsFramePointer() { var comp = @" using System; using System.Collections.Generic; class C { int _z = 0; void M(IEnumerable<int> xs) { foreach (var x in xs) { Func<int, int> captureFunc = k => x + _z; } } }"; CompileAndVerify(comp); } [Fact] public void StaticClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { D d1 = new D(() => Console.Write(1)); d1(); D d2 = () => Console.WriteLine(2); d2(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"12"); compilation.VerifyIL("C.Main", @" { // Code size 73 (0x49) .maxstack 2 IL_0000: ldsfld ""D C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""void C.<>c.<Main>b__0_0()"" IL_0014: newobj ""D..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""D C.<>c.<>9__0_0"" IL_001f: callvirt ""void D.Invoke()"" IL_0024: ldsfld ""D C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""void C.<>c.<Main>b__0_1()"" IL_0038: newobj ""D..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""D C.<>c.<>9__0_1"" IL_0043: callvirt ""void D.Invoke()"" IL_0048: ret } "); } [Fact] public void ThisOnlyClosure() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { new C().M(); } int n = 1; int m = 2; public void M() { for (int i = 0; i < 2; i++) { D d1 = new D(() => Console.Write(n)); d1(); D d2 = () => Console.WriteLine(m); d2(); } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"12 12"); compilation.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_002a IL_0004: ldarg.0 IL_0005: ldftn ""void C.<M>b__3_0()"" IL_000b: newobj ""D..ctor(object, System.IntPtr)"" IL_0010: callvirt ""void D.Invoke()"" IL_0015: ldarg.0 IL_0016: ldftn ""void C.<M>b__3_1()"" IL_001c: newobj ""D..ctor(object, System.IntPtr)"" IL_0021: callvirt ""void D.Invoke()"" IL_0026: ldloc.0 IL_0027: ldc.i4.1 IL_0028: add IL_0029: stloc.0 IL_002a: ldloc.0 IL_002b: ldc.i4.2 IL_002c: blt.s IL_0004 IL_002e: ret }"); } [Fact] public void StaticClosure02() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { new C().F(); } void F() { D d1 = () => Console.WriteLine(1); d1(); } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact] public void StaticClosure03() { string source = @"using System; delegate int D(int x); class Program { static void Main(string[] args) { int @string = 10; D d = delegate (int @class) { return @class + @string; }; Console.WriteLine(d(2)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void InstanceClosure01() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { D d1 = () => Console.WriteLine(X); d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure02() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { D d1 = () => { C c = this; Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure03() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { new C(12).F(); } void F() { C c = this; D d1 = () => { Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure04() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { F(new C(12)); } static void F(C c) { D d1 = () => { Console.WriteLine(c.X); }; d1(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void InstanceClosure05() { string source = @"using System; delegate void D(); class C { int X; C(int x) { this.X = x; } public static void Main(string[] args) { { C c = new C(12); D d = () => { Console.WriteLine(c.X); }; d(); } { C c = new C(13); D d = () => { Console.WriteLine(c.X); }; d(); } } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void InstanceClosure06() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { Console.WriteLine(K); Console.WriteLine(i); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 "); } [Fact] public void LoopClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { D d1 = null, d2 = null; int i = 0; while (i < 10) { int j = i; if (i == 5) { d1 = () => Console.WriteLine(j); d2 = () => Console.WriteLine(i); } i = i + 1; } d1(); d2(); } }"; CompileAndVerify(source, expectedOutput: @" 5 10 "); } [Fact] public void NestedClosure01() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { D d2 = () => { Console.WriteLine(i); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void NestedClosure02() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 "); } [Fact] public void NestedClosure10() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void NestedClosure11() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { int j = 13; D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 13 "); } [Fact] public void NestedClosure20() { string source = @"using System; delegate void D(); class C { public static void Main(string[] args) { int i = 12; D d1 = () => { int j = i + 1; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 "); } [Fact] public void NestedClosure21() { string source = @"using System; delegate void D(); class C { int K = 11; public static void Main(string[] args) { new C().F(); } void F() { int i = 12; D d1 = () => { int j = i + 1; D d2 = () => { Console.WriteLine(K); Console.WriteLine(i); Console.WriteLine(j); }; d2(); }; d1(); } }"; CompileAndVerify(source, expectedOutput: @" 11 12 13 "); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void NestedClosureThisConstructorInitializer() { string source = @"using System; delegate void D(); delegate void D1(int i); class C { public int l = 15; public C():this((int i) => { int k = 14; D d15 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); }; d2(); }; d15(); }) {func((int i) => { int k = 14; D d15 = () => { int j = 13; D d2 = () => { Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); Console.WriteLine(l); }; d2(); }; d15(); }); } public C(D1 d1){int i=12; d1(i);} public void func(D1 d1) { int i=12;d1(i); } public static void Main(string[] args) { new C(); } }"; CompileAndVerify(source, expectedOutput: @" 12 13 14 12 13 14 15 "); } [Fact] public void FilterParameterClosure01() { string source = @" using System; class Program { static void Main() { string s = ""xxx""; try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<Exception, bool>(x => x.Message == s)(e)) { Console.Write(""pass""); } } }"; CompileAndVerify(source, expectedOutput: "pass"); } [Fact] public void FilterParameterClosure02() { string source = @" using System; class Program { static void Main() { string s = ""xxx""; try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<Exception, bool>(x => x.Message == s)(e)) { Console.Write(s + ""pass""); } } }"; CompileAndVerify(source, expectedOutput: "xxxpass"); } [WorkItem(541258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541258")] [Fact] public void CatchVarLifted1() { string source = @"using System; class Program { static void Main() { Action a = null; try { throw new Exception(""pass""); } catch (Exception e) { a = () => Console.Write(e.Message); } a(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (System.Action V_0, //a Program.<>c__DisplayClass0_0 V_1, //CS$<>8__locals0 System.Exception V_2) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldstr ""pass"" IL_0007: newobj ""System.Exception..ctor(string)"" IL_000c: throw } catch System.Exception { IL_000d: newobj ""Program.<>c__DisplayClass0_0..ctor()"" IL_0012: stloc.1 IL_0013: stloc.2 IL_0014: ldloc.1 IL_0015: ldloc.2 IL_0016: stfld ""System.Exception Program.<>c__DisplayClass0_0.e"" IL_001b: ldloc.1 IL_001c: ldftn ""void Program.<>c__DisplayClass0_0.<Main>b__0()"" IL_0022: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0027: stloc.0 IL_0028: leave.s IL_002a } IL_002a: ldloc.0 IL_002b: callvirt ""void System.Action.Invoke()"" IL_0030: ret } "); } [Fact] public void CatchVarLifted2() { var source = @" using System; class Program { static bool Goo(Action x) { x(); return true; } static void Main() { try { throw new Exception(""fail""); } catch (Exception ex) when (Goo(() => { ex = new Exception(""pass""); })) { Console.Write(ex.Message); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 79 (0x4f) .maxstack 2 .locals init (Program.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Exception V_1) .try { IL_0000: ldstr ""fail"" IL_0005: newobj ""System.Exception..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""System.Exception"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0039 IL_0017: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_001c: stloc.0 IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldloc.1 IL_0020: stfld ""System.Exception Program.<>c__DisplayClass1_0.ex"" IL_0025: ldloc.0 IL_0026: ldftn ""void Program.<>c__DisplayClass1_0.<Main>b__0()"" IL_002c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0031: call ""bool Program.Goo(System.Action)"" IL_0036: ldc.i4.0 IL_0037: cgt.un IL_0039: endfilter } // end filter { // handler IL_003b: pop IL_003c: ldloc.0 IL_003d: ldfld ""System.Exception Program.<>c__DisplayClass1_0.ex"" IL_0042: callvirt ""string System.Exception.Message.get"" IL_0047: call ""void System.Console.Write(string)"" IL_004c: leave.s IL_004e } IL_004e: ret } "); } [Fact] public void CatchVarLifted2a() { var source = @" using System; class Program { static bool Goo(Action x) { x(); return true; } static void Main() { try { throw new Exception(""fail""); } catch (ArgumentException ex) when (Goo(() => { ex = new ArgumentException(""fail""); })) { Console.Write(ex.Message); } catch (Exception ex) when (Goo(() => { ex = new Exception(""pass""); })) { Console.Write(ex.Message); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); } [Fact] public void CatchVarLifted3() { string source = @" using System; class Program { static void Main() { try { throw new Exception(""xxx""); } catch (Exception e) when (new Func<bool>(() => e.Message == ""xxx"")()) { Console.Write(""pass""); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.Main", @" { // Code size 73 (0x49) .maxstack 2 .locals init (Program.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Exception V_1) .try { IL_0000: ldstr ""xxx"" IL_0005: newobj ""System.Exception..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""System.Exception"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0039 IL_0017: newobj ""Program.<>c__DisplayClass0_0..ctor()"" IL_001c: stloc.0 IL_001d: stloc.1 IL_001e: ldloc.0 IL_001f: ldloc.1 IL_0020: stfld ""System.Exception Program.<>c__DisplayClass0_0.e"" IL_0025: ldloc.0 IL_0026: ldftn ""bool Program.<>c__DisplayClass0_0.<Main>b__0()"" IL_002c: newobj ""System.Func<bool>..ctor(object, System.IntPtr)"" IL_0031: callvirt ""bool System.Func<bool>.Invoke()"" IL_0036: ldc.i4.0 IL_0037: cgt.un IL_0039: endfilter } // end filter { // handler IL_003b: pop IL_003c: ldstr ""pass"" IL_0041: call ""void System.Console.Write(string)"" IL_0046: leave.s IL_0048 } IL_0048: ret } "); } [Fact] public void CatchVarLifted_Generic1() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { new Action(() => { try { throw new IOException(""xxx""); } catch (T e) when (e.Message == ""xxx"") { Console.Write(""pass""); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass"); verifier.VerifyIL("Program.<>c__1<T>.<F>b__1_0", @" { // Code size 67 (0x43) .maxstack 2 .try { IL_0000: ldstr ""xxx"" IL_0005: newobj ""System.IO.IOException..ctor(string)"" IL_000a: throw } filter { IL_000b: isinst ""T"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldc.i4.0 IL_0015: br.s IL_0033 IL_0017: unbox.any ""T"" IL_001c: box ""T"" IL_0021: callvirt ""string System.Exception.Message.get"" IL_0026: ldstr ""xxx"" IL_002b: call ""bool string.op_Equality(string, string)"" IL_0030: ldc.i4.0 IL_0031: cgt.un IL_0033: endfilter } // end filter { // handler IL_0035: pop IL_0036: ldstr ""pass"" IL_003b: call ""void System.Console.Write(string)"" IL_0040: leave.s IL_0042 } IL_0042: ret } "); } [Fact] public void CatchVarLifted_Generic2() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { string x = ""x""; new Action(() => { string y = ""y""; try { throw new IOException(""xy""); } catch (T e) when (new Func<bool>(() => e.Message == x + y)()) { Console.Write(""pass_"" + x + y); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass_xy"); verifier.VerifyIL("Program.<>c__DisplayClass1_0<T>.<F>b__0", @" { // Code size 113 (0x71) .maxstack 3 .locals init (Program.<>c__DisplayClass1_1<T> V_0, //CS$<>8__locals0 T V_1) IL_0000: newobj ""Program.<>c__DisplayClass1_1<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.<>c__DisplayClass1_0<T> Program.<>c__DisplayClass1_1<T>.CS$<>8__locals1"" IL_000d: ldloc.0 IL_000e: ldstr ""y"" IL_0013: stfld ""string Program.<>c__DisplayClass1_1<T>.y"" .try { IL_0018: ldstr ""xy"" IL_001d: newobj ""System.IO.IOException..ctor(string)"" IL_0022: throw } filter { IL_0023: isinst ""T"" IL_0028: dup IL_0029: brtrue.s IL_002f IL_002b: pop IL_002c: ldc.i4.0 IL_002d: br.s IL_0050 IL_002f: unbox.any ""T"" IL_0034: stloc.1 IL_0035: ldloc.0 IL_0036: ldloc.1 IL_0037: stfld ""T Program.<>c__DisplayClass1_1<T>.e"" IL_003c: ldloc.0 IL_003d: ldftn ""bool Program.<>c__DisplayClass1_1<T>.<F>b__1()"" IL_0043: newobj ""System.Func<bool>..ctor(object, System.IntPtr)"" IL_0048: callvirt ""bool System.Func<bool>.Invoke()"" IL_004d: ldc.i4.0 IL_004e: cgt.un IL_0050: endfilter } // end filter { // handler IL_0052: pop IL_0053: ldstr ""pass_"" IL_0058: ldarg.0 IL_0059: ldfld ""string Program.<>c__DisplayClass1_0<T>.x"" IL_005e: ldloc.0 IL_005f: ldfld ""string Program.<>c__DisplayClass1_1<T>.y"" IL_0064: call ""string string.Concat(string, string, string)"" IL_0069: call ""void System.Console.Write(string)"" IL_006e: leave.s IL_0070 } IL_0070: ret } "); } [Fact] public void CatchVarLifted_Generic3() { string source = @" using System; using System.IO; class Program { static void Main() { F<IOException>(); } static void F<T>() where T : Exception { string x = ""x""; new Action(() => { string y = ""y""; try { throw new IOException(""a""); } catch (T e1) when (new Func<bool>(() => { string z = ""z""; try { throw new IOException(""xyz""); } catch (T e2) when (e2.Message == x + y + z) { return true; } })()) { Console.Write(""pass_"" + x + y); } })(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "pass_xy"); } [Fact] public void ForeachParameterClosure01() { string source = @"using System; using System.Collections.Generic; delegate void D(); class C { public static void Main(string[] args) { List<string> list = new List<string>(new string[] {""A"", ""B""}); D d = null; foreach (string s in list) { if (s == ""A"") { d = () => { Console.WriteLine(s); }; } } d(); } }"; // Dev10 prints B, but we have intentionally changed the scope // of the loop variable. CompileAndVerify(source, expectedOutput: "A"); } [Fact] public void LambdaParameterClosure01() { string source = @"using System; delegate void D0(); delegate void D1(string s); class C { public static void Main(string[] args) { D0 d0 = null; D1 d1 = (string s) => { d0 = () => { Console.WriteLine(s); }; }; d1(""goo""); d0(); } }"; CompileAndVerify(source, expectedOutput: "goo"); } [Fact] public void BaseInvocation01() { string source = @"using System; class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main() { base.F(); } public static void Main(string[] args) { new C().Main(); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure01() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main() { D d = () => { base.F(); }; d(); } public static void Main(string[] args) { new C().Main(); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure02() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main(int x) { D d = () => { x = x + 1; base.F(); }; d(); } public static void Main(string[] args) { new C().Main(3); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseInvocationClosure03() { string source = @"using System; delegate void D(); class B { public virtual void F() { Console.WriteLine(""base""); } } class C : B { public override void F() { Console.WriteLine(""derived""); } void Main(int x) { D d = base.F; d(); } public static void Main(string[] args) { new C().Main(3); } }"; CompileAndVerify(source, expectedOutput: "base"); } [Fact] public void BaseAccessInClosure_01() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { var s = ""this: ""; Func<string> f = () => s + this.F(); Console.WriteLine(f()); } public void TestBase() { var s = ""base: ""; Func<string> f = () => s + base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"this: D::F{Environment.NewLine}base: B1::F"); } [Fact] public void BaseAccessInClosure_02() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestThis() { var s = ""this: ""; Func<string> f = () => s + this.F(); Console.WriteLine(f()); } public void TestBase() { var s = ""base: ""; Func<string> f = () => s + base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"this: D::F{Environment.NewLine}base: B1::F"); } [Fact] public void BaseAccessInClosure_03_WithILCheck() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestBase() { Func<string> f = () => base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: "B1::F"). VerifyIL("M1.B2.<TestBase>b__1_0", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string M1.B1.F()"" IL_0006: ret }"); } [Fact] public void BaseAccessInClosure_03a_WithILCheck() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B1a : B1 { public override string F() { return ""B1a::F""; } } class B2 : B1a { public override string F() { return ""B2::F""; } public void TestBase() { Func<string> f = () => base.F(); Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: "B1a::F"). VerifyIL("M1.B2.<TestBase>b__1_0", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string M1.B1a.F()"" IL_0006: ret }"); } [Fact] public void BaseAccessInClosure_04() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { Func<string> f = this.F; Console.WriteLine(f()); } public void TestBase() { Func<string> f = base.F; Console.WriteLine(f()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_05() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { Func<Func<string>> f = () => this.F; Console.WriteLine(f()()); } public void TestBase() { Func<Func<string>> f = () => base.F; Console.WriteLine(f()()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_06() { string source = @"using System; static class M1 { class B1 { public virtual string F() { return ""B1::F""; } } class B2 : B1 { public override string F() { return ""B2::F""; } public void TestThis() { int s = 0; Func<Func<string>> f = () => { s++; return this.F; }; Console.WriteLine(f()()); } public void TestBase() { int s = 0; Func<Func<string>> f = () => { s++; return base.F; }; Console.WriteLine(f()()); } } class D : B2 { public override string F() { return ""D::F""; } } static void Main() { (new D()).TestThis(); (new D()).TestBase(); } } "; CompileAndVerify(source, expectedOutput: $"D::F{Environment.NewLine}B1::F"); } [Fact] public void BaseAccessInClosure_07() { string source = @"using System; static class M1 { class B1 { public virtual string F { get { Console.Write(""B1::F.Get;""); return null; } set { Console.Write(""B1::F.Set;""); } } } class B2 : B1 { public override string F { get { Console.Write(""B2::F.Get;""); return null; } set { Console.Write(""B2::F.Set;""); } } public void Test() { int s = 0; Action f = () => { s++; this.F = base.F; base.F = this.F; }; f(); } } class D : B2 { public override string F { get { Console.Write(""D::F.Get;""); return null; } set { Console.Write(""F::F.Set;""); } } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F.Get;F::F.Set;D::F.Get;B1::F.Set;"); } [Fact] public void BaseAccessInClosure_08() { string source = @"using System; static class M1 { class B1 { public virtual void F<T>(T t) { Console.Write(""B1::F;""); } } class B2 : B1 { public override void F<T>(T t) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Action f = () => { s++; this.F<int>(0); base.F<string>(""""); }; f(); } } class D : B2 { public override void F<T>(T t) { Console.Write(""D::F;""); } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "D::F;B1::F;"); } [Fact] public void BaseAccessInClosure_09() { string source = @"using System; static class M1 { class B1 { public virtual void F<T>(T t) { Console.Write(""B1::F;""); } } class B2 : B1 { public override void F<T>(T t) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<int>> f1 = () => { s++; return base.F<int>; }; f1()(0); Func<Action<string>> f2 = () => { s++; return this.F<string>; }; f2()(null); } } class D : B2 { public override void F<T>(T t) { Console.Write(""D::F;""); } } static void Main() { (new D()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_10() { string source = @"using System; static class M1 { class B1<T> { public virtual void F<U>(T t, U u) { Console.Write(""B1::F;""); } } class B2<T> : B1<T> { public override void F<U>(T t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<T, int>> f1 = () => { s++; return base.F<int>; }; f1()(default(T), 0); Func<Action<T, string>> f2 = () => { s++; return this.F<string>; }; f2()(default(T), null); } } class D<T> : B2<T> { public override void F<U>(T t, U u) { Console.Write(""D::F;""); } } static void Main() { (new D<int>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_11() { string source = @"using System; static class M1 { class B1<T> { public virtual void F<U>(T t, U u) { Console.Write(""B1::F;""); } } class Outer<V> { public class B2 : B1<V> { public override void F<U>(V t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<V, int>> f1 = () => { s++; return base.F<int>; }; f1()(default(V), 0); Func<Action<V, string>> f2 = () => { s++; return this.F<string>; }; f2()(default(V), null); } } } class D<X> : Outer<X>.B2 { public override void F<U>(X t, U u) { Console.Write(""D::F;""); } } static void Main() { (new D<int>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_12() { string source = @"using System; static class M1 { public class Outer<T> { public class B1 { public virtual string F1(T t) { return ""B1::F1;""; } public virtual string F2(T t) { return ""B1::F2;""; } } } public class B2 : Outer<int>.B1 { public override string F1(int t) { return ""B2::F2;""; } public void Test() { int s = 0; Func<string> f1 = () => new Func<int, string>(this.F1)(s) + new Func<int, string>(base.F1)(s); Func<string> f2 = () => new Func<int, string>(this.F2)(s) + new Func<int, string>(base.F2)(s); Console.WriteLine(f1() + f2()); } } class D : B2 { public override string F1(int t) { return ""D::F2;""; } public override string F2(int t) { return ""D::F2;""; } } static void Main() { (new D()).Test(); } } "; CompileAndVerify(source, expectedOutput: "D::F2;B1::F1;D::F2;B1::F2;"); } [Fact] public void BaseAccessInClosure_13() { string source = @"using System; static class M1 { interface I{} class B1<T> where T : I { public virtual void F<U>(T t, U u) where U : struct, T { Console.Write(""B1::F;""); } } class Outer<V> where V : struct, I { public class B2 : B1<V> { public override void F<U>(V t, U u) { Console.Write(""B2::F;""); } public void Test() { int s = 0; Func<Action<V, V>> f1 = () => { s++; return base.F<V>; }; f1()(default(V), default(V)); Func<Action<V, V>> f2 = () => { s++; return this.F<V>; }; f2()(default(V), default(V)); } } } class D<X> : Outer<X>.B2 where X : struct, I { public override void F<U>(X t, U u) { Console.Write(""D::F;""); } } struct C : I { } static void Main() { (new D<C>()).Test(); } }"; CompileAndVerify(source, expectedOutput: "B1::F;D::F;"); } [Fact] public void BaseAccessInClosure_14_WithILCheck() { string source = @"using System; static class M1 { public class Outer<T> { public class B1 { public virtual string F<U>(T t, U u) { return ""B1:F""; } } } public class B2 : Outer<int>.B1 { public override string F<U>(int t, U u) { return ""B2:F""; } public void Test() { int s = 0; Func<string> f1 = () => new Func<int, int, string>(base.F<int>)(s, s); Console.WriteLine(f1()); } } static void Main() { (new B2()).Test(); } }"; CompileAndVerify(source, expectedOutput: @"B1:F" ). VerifyIL("M1.B2.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""string M1.Outer<int>.B1.F<U>(int, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_15_WithILCheck() { string source = @"using System; static class M1 { public interface I { } public interface II : I { } public class C : II { public C() { } } public class Outer<T> where T : I, new() { public class B1 { public virtual string F<U>(T t, U u) where U : T, new() { return ""B1::F;""; } } } public class B2 : Outer<C>.B1 { public override string F<U>(C t, U u) { return ""B2::F;""; } public void Test() { C s = new C(); Func<string> f1 = () => new Func<C, C, string>(base.F)(s, s); Console.WriteLine(f1()); } } static void Main() { (new B2()).Test(); } }"; CompileAndVerify(source, expectedOutput: @"B1::F;" ). VerifyIL("M1.B2.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 35 (0x23) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld ""M1.B2 M1.B2.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""string M1.B2.<>n__0<M1.C>(M1.C, M1.C)"" IL_000c: newobj ""System.Func<M1.C, M1.C, string>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""M1.C M1.B2.<>c__DisplayClass1_0.s"" IL_0017: ldarg.0 IL_0018: ldfld ""M1.C M1.B2.<>c__DisplayClass1_0.s"" IL_001d: callvirt ""string System.Func<M1.C, M1.C, string>.Invoke(M1.C, M1.C)"" IL_0022: ret }"). VerifyIL("M1.B2.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""string M1.Outer<M1.C>.B1.F<U>(M1.C, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_16() { string source = @"using System; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.CompilerServices; static class M1 { public interface I { } public interface II : I { } public class C : II { public C() { } } public class Outer<T> where T : I, new() { public class B1 { public virtual string F<U>(T t, U u) where U : I, T, new() { return ""B1::F;""; } } } public class B2 : Outer<C>.B1 { public override string F<U>(C t, U u) { return ""B2::F;""; } public void Test() { C s = new C(); Func<string> f1 = () => new Func<C, C, string>(base.F)(s, s); Console.WriteLine(f1()); } } static void Main() { var type = (new B2()).GetType(); var method = type.GetMethod(""<>n__0"", BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine(Attribute.IsDefined(method, typeof(CompilerGeneratedAttribute))); Console.WriteLine(method.IsPrivate); Console.WriteLine(method.IsVirtual); Console.WriteLine(method.IsGenericMethod); var genericDef = method.GetGenericMethodDefinition(); var arguments = genericDef.GetGenericArguments(); Console.WriteLine(arguments.Length); var arg0 = arguments[0]; GenericParameterAttributes attributes = arg0.GenericParameterAttributes; Console.WriteLine(attributes.ToString()); var arg0constraints = arg0.GetGenericParameterConstraints(); Console.WriteLine(arg0constraints.Length); Console.WriteLine(arg0constraints[0]); Console.WriteLine(arg0constraints[1]); } }"; CompileAndVerify(source, expectedOutput: @" True True False True 1 DefaultConstructorConstraint 2 M1+I M1+C" ); } [Fact] public void BaseAccessInClosure_17_WithILCheck() { string source = @"using System; class Base<T> { public virtual void Func<U>(T t, U u) { Console.Write(typeof (T)); Console.Write("" ""); Console.Write(typeof (U)); } public class Derived : Base<int> { public void Test() { int i = 0; T t = default(T); Action d = () => { base.Func<T>(i, t); }; d(); } } } class Program { static void Main() { new Base<string>.Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "System.Int32 System.String" ). VerifyIL("Base<T>.Derived.<>n__0<U>", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""void Base<int>.Func<U>(int, U)"" IL_0008: ret }"); } [Fact] public void BaseAccessInClosure_18_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { base.F(j); this.F(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;Derived::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @" { // Code size 35 (0x23) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldarg.0 IL_0007: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_000c: call ""void Base.F(int)"" IL_0011: ldarg.0 IL_0012: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0017: ldarg.0 IL_0018: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_001d: call ""void Derived.F(int)"" IL_0022: ret }"); } [Fact] public void BaseAccessInClosure_19_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { Action<int> b = base.F; b(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""void Base.F(int)"" IL_000c: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_0017: callvirt ""void System.Action<int>.Invoke(int)"" IL_001c: ret }"); } [Fact] public void BaseAccessInClosure_20_WithILCheck() { string source = @"using System; class Base { public void F(int i) { Console.Write(""Base::F;""); } } class Derived : Base { public new void F(int i) { Console.Write(""Derived::F;""); } public void Test() { int j = 0; Action a = () => { Action<int> b = new Action<int>(base.F); b(j); }; a(); } static void Main(string[] args) { new Derived().Test(); } } "; CompileAndVerify(source, expectedOutput: "Base::F;" ). VerifyIL("Derived.<>c__DisplayClass1_0.<Test>b__0", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldftn ""void Base.F(int)"" IL_000c: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0011: ldarg.0 IL_0012: ldfld ""int Derived.<>c__DisplayClass1_0.j"" IL_0017: callvirt ""void System.Action<int>.Invoke(int)"" IL_001c: ret }"); } [Fact] public void UnsafeInvocationClosure01() { string source = @"using System; delegate void D(); class C { static unsafe void F() { D d = () => { Console.WriteLine(""F""); }; d(); } public static void Main(string[] args) { D d = () => { F(); }; d(); } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F", verify: Verification.Passes); } [Fact] public void LambdaWithParameters01() { var source = @" delegate void D(int x); class LWP { public static void Main(string[] args) { D d1 = x => { System.Console.Write(x); }; d1(123); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters02() { var source = @" delegate void D(int x); class LWP { public static void Main(string[] args) { int local; D d1 = x => { local = 12; System.Console.Write(x); }; d1(123); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters03() { var source = @" delegate void D(int x); class LWP { void M() { D d1 = x => { System.Console.Write(x); }; d1(123); } public static void Main(string[] args) { new LWP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void LambdaWithParameters04() { var source = @" delegate void D(int x); class LWP { void M() { int local; D d1 = x => { local = 2; System.Console.Write(x); }; d1(123); } public static void Main(string[] args) { new LWP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter01() { var source = @" delegate D D(int x); class CLP { public static void Main(string[] args) { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter02() { var source = @" delegate D D(int x); class CLP { void M() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M(); } } "; CompileAndVerify(source, expectedOutput: "123"); } [Fact] public void CapturedLambdaParameter03() { var source = @" delegate D D(int x); class CLP { public static void Main(string[] args) { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } } "; CompileAndVerify(source, expectedOutput: "4123"); } [Fact] public void CapturedLambdaParameter04() { var source = @" delegate D D(int x); class CLP { void M() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M(); } } "; CompileAndVerify(source, expectedOutput: "4123"); } [Fact] public void GenericClosure01() { string source = @"using System; delegate void D(); class G<T> { public static void F(T t) { D d = () => { Console.WriteLine(t); }; d(); } } class C { public static void Main(string[] args) { G<int>.F(12); G<string>.F(""goo""); } }"; CompileAndVerify(source, expectedOutput: @" 12 goo "); } [Fact] public void GenericClosure02() { string source = @"using System; delegate void D(); class G { public static void F<T>(T t) { D d = () => { Console.WriteLine(t); }; d(); } } class C { public static void Main(string[] args) { G.F<int>(12); G.F<string>(""goo""); } }"; CompileAndVerify(source, expectedOutput: @" 12 goo "); } [Fact] public void GenericClosure03() { var source = @"using System; delegate U D<U>(); class GenericClosure { static D<T> Default<T>(T value) { return () => value; } public static void Main(string[] args) { D<string> dHello = Default(""Hello""); Console.WriteLine(dHello()); D<int> d1234 = Default(1234); Console.WriteLine(d1234()); } } "; var expectedOutput = @"Hello 1234"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void GenericClosure04() { var source = @"using System; delegate T D<T>(); class GenericClosure { static D<T> Default<T>(T value) { return () => default(T); } public static void Main(string[] args) { D<string> dHello = Default(""Hello""); Console.WriteLine(dHello()); D<int> d1234 = Default(1234); Console.WriteLine(d1234()); } } "; var expectedOutput = @" 0"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void GenericCapturedLambdaParameter01() { var source = @" delegate D D(int x); class CLP { void M<T>() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M<int>(); new CLP().M<string>(); } } "; CompileAndVerify(source, expectedOutput: "123123"); } [Fact] public void GenericCapturedLambdaParameter02() { var source = @" delegate D D(int x); class CLP { static void M<T>() { D d1 = x => y => z => { System.Console.Write(x + y + z); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "123123"); } [Fact] public void GenericCapturedLambdaParameter03() { var source = @" delegate D D(int x); class CLP { void M<T>() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { new CLP().M<int>(); new CLP().M<string>(); } } "; CompileAndVerify(source, expectedOutput: "41234123"); } [Fact] public void GenericCapturedLambdaParameter04() { var source = @" delegate D D(int x); class CLP { static void M<T>() { int K = 4000; D d1 = x => y => z => { System.Console.Write(x + y + z + K); return null; }; d1(100)(20)(3); } public static void Main(string[] args) { CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "41234123"); } [Fact] public void GenericCapturedTypeParameterLocal() { var source = @" delegate void D(); class CLP { static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; System.Console.Write("""" + t0 + t1 + t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureConstructedMethodInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { static void P<T>(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; P(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureConstructionInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { class P<T> { public P(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; new P<T>(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureDelegateConversionInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { delegate void D3<T>(T t0, T t1, T t2); public static void P<T>(T t0, T t1, T t2) { System.Console.Write(string.Concat(t0, t1, t2)); } static void M<T>(T t0) { T t1 = t0; D d = () => { T t2 = t1; D3<T> d3 = P; d3(t0, t1, t2); }; d(); } public static void Main(string[] args) { CLP.M<int>(0); CLP.M<string>(""h""); } } "; CompileAndVerify(source, expectedOutput: "000hhh"); } [Fact] public void CaptureFieldInvolvingTypeParameter() { var source = @" delegate void D(); class CLP { class HolderClass<T> { public static T t; } delegate void D3<T>(T t0, T t1, T t2); static void M<T>() { D d = () => { System.Console.Write(string.Concat(HolderClass<T>.t)); }; d(); } public static void Main(string[] args) { HolderClass<int>.t = 12; HolderClass<string>.t = ""he""; CLP.M<int>(); CLP.M<string>(); } } "; CompileAndVerify(source, expectedOutput: "12he"); } [Fact] public void CaptureReadonly01() { var source = @" using System; class Program { private static readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(3), ""he"")); } }"; CompileAndVerify(source, expectedOutput: "15he"); } [Fact] public void CaptureReadonly02() { var source = @" using System; class Program { private readonly int v = 5; delegate int del(int i); void M() { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(3), ""he"")); } static void Main(string[] args) { new Program().M(); } }"; CompileAndVerify(source, expectedOutput: "15he"); } [Fact] public void CaptureLoopIndex() { var source = @" using System; delegate void D(); class Program { static void Main(string[] args) { D d0 = null; for (int i = 0; i < 4; i++) { D d = d0 = () => { Console.Write(i); }; d(); } d0(); } }"; CompileAndVerify(source, expectedOutput: "01234"); } // see Roslyn bug 5956 [Fact] public void CapturedIncrement() { var source = @" class Program { delegate int Func(); static void Main(string[] args) { int i = 0; Func query; if (true) { query = () => { i = 6; Goo(i++); return i; }; } i = 3; System.Console.WriteLine(query.Invoke()); } public static int Goo(int i) { i = 4; return i; } } "; CompileAndVerify(source, expectedOutput: "7"); } [Fact] public void StructDelegate() { var source = @" using System; class Program { static void Main() { int x = 42; Func<string> f = x.ToString; Console.Write(f.Invoke()); } }" ; CompileAndVerify(source, expectedOutput: "42"); } [Fact] public void StructDelegate1() { var source = @" using System; class Program { public static void Goo<T>(T x) { Func<string> f = x.ToString; Console.Write(f.Invoke()); } static void Main() { string s = ""Hi""; Goo(s); int x = 42; Goo(x); } }" ; CompileAndVerify(source, expectedOutput: "Hi42"); } [Fact] public void StaticDelegateFromMethodGroupInLambda() { var source = @"using System; class Program { static void M() { Console.WriteLine(12); } public static void Main(string[] args) { Action a = () => { Action b = new Action(M); b(); }; a(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [Fact] public void StaticDelegateFromMethodGroupInLambda2() { var source = @"using System; class Program { static void M() { Console.WriteLine(12); } void G() { Action a = () => { Action b = new Action(M); b(); }; a(); } public static void Main(string[] args) { new Program().G(); } }"; CompileAndVerify(source, expectedOutput: "12"); } [WorkItem(539346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539346")] [Fact] public void CachedLambdas() { var source = @"using System; public class Program { private static void Assert(bool b) { if (!b) throw new Exception(); } public static void Test1() { Action a0 = null; for (int i = 0; i < 2; i++) { Action a = () => { }; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public void Test2() { Action a0 = null; for (int i = 0; i < 2; i++) { Action a = () => { }; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public static void Test3() { int inEnclosing = 12; Func<int> a0 = null; for (int i = 0; i < 2; i++) { Func<int> a = () => inEnclosing; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); } } } public void Test4() { Func<Program> a0 = null; for (int i = 0; i < 2; i++) { Func<Program> a = () => this; if (i == 0) { a0 = a; } else { Assert(ReferenceEquals(a, a0)); // Roslyn misses this } } } public static void Test5() { int i = 12; Func<Action> D = () => () => Console.WriteLine(i); Action a1 = D(); Action a2 = D(); Assert(ReferenceEquals(a1, a2)); // native compiler misses this } public static void Test6() { Func<int> a1 = Goo<int>.Bar<int>(); Func<int> a2 = Goo<int>.Bar<int>(); Assert(ReferenceEquals(a1, a2)); // both native compiler and Roslyn miss this } public static void Main(string[] args) { Test1(); new Program().Test2(); Test3(); // new Program().Test4(); Test5(); // Test6(); } } class Goo<T> { static T t; public static Func<U> Bar<U>() { return () => Goo<U>.t; } }"; CompileAndVerify(source, expectedOutput: ""); } [Fact] public void ParentFrame01() { //IMPORTANT: the parent frame field in Program.c1.<>c__DisplayClass1 should be named CS$<>8__locals, not <>4__this. string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<int, Func<int, int>>>> ff = null; if (2.ToString() != null) { int a = 4; ff = () => () => (z) => (zz) => x + y + z + a + zz; } Console.WriteLine(ff()()(3)(3)); } } }"; CompileAndVerify(source, expectedOutput: "13"). VerifyIL("Program.c1.<>c__DisplayClass1_0.<Test>b__2", @"{ // Code size 31 (0x1f) .maxstack 3 IL_0000: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_000c: dup IL_000d: ldarg.1 IL_000e: stfld ""int Program.c1.<>c__DisplayClass1_1.z"" IL_0013: ldftn ""int Program.c1.<>c__DisplayClass1_1.<Test>b__3(int)"" IL_0019: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_001e: ret }"); } [Fact] public void ParentFrame02() { string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<int, Func<int>>>> ff = null; if (2.ToString() != null) { int a = 4; ff = () => () => (z) => () => x + y + z + a; } if (2.ToString() != null) { int a = 4; ff = () => () => (z) => () => x + y + z + a; } Console.WriteLine(ff()()(3)()); } } } "; CompileAndVerify(source, expectedOutput: "10"). VerifyIL("Program.c1.Test", @"{ // Code size 134 (0x86) .maxstack 3 .locals init (Program.c1.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Func<System.Func<System.Func<int, System.Func<int>>>> V_1, //ff int V_2) IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld ""int Program.c1.<>c__DisplayClass1_0.y"" IL_0014: ldnull IL_0015: stloc.1 IL_0016: ldc.i4.2 IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""string int.ToString()"" IL_001f: brfalse.s IL_0040 IL_0021: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0026: dup IL_0027: ldloc.0 IL_0028: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_002d: dup IL_002e: ldc.i4.4 IL_002f: stfld ""int Program.c1.<>c__DisplayClass1_1.a"" IL_0034: ldftn ""System.Func<System.Func<int, System.Func<int>>> Program.c1.<>c__DisplayClass1_1.<Test>b__0()"" IL_003a: newobj ""System.Func<System.Func<System.Func<int, System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_003f: stloc.1 IL_0040: ldc.i4.2 IL_0041: stloc.2 IL_0042: ldloca.s V_2 IL_0044: call ""string int.ToString()"" IL_0049: brfalse.s IL_006a IL_004b: newobj ""Program.c1.<>c__DisplayClass1_3..ctor()"" IL_0050: dup IL_0051: ldloc.0 IL_0052: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_3.CS$<>8__locals3"" IL_0057: dup IL_0058: ldc.i4.4 IL_0059: stfld ""int Program.c1.<>c__DisplayClass1_3.a"" IL_005e: ldftn ""System.Func<System.Func<int, System.Func<int>>> Program.c1.<>c__DisplayClass1_3.<Test>b__4()"" IL_0064: newobj ""System.Func<System.Func<System.Func<int, System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: callvirt ""System.Func<System.Func<int, System.Func<int>>> System.Func<System.Func<System.Func<int, System.Func<int>>>>.Invoke()"" IL_0070: callvirt ""System.Func<int, System.Func<int>> System.Func<System.Func<int, System.Func<int>>>.Invoke()"" IL_0075: ldc.i4.3 IL_0076: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_007b: callvirt ""int System.Func<int>.Invoke()"" IL_0080: call ""void System.Console.WriteLine(int)"" IL_0085: ret }"); } [Fact] public void ParentFrame03() { string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { int y = 2; Func<Func<Func<Func<int>>>> ff = null; if (2.ToString() != null) { int z = 3; ff = () => () => () => () => x + y + z; } if (2.ToString() != null) { int z = 3; ff = () => () => () => () => x + y + z; } Console.WriteLine(ff()()()()); } } } "; CompileAndVerify(source, expectedOutput: "6"). VerifyIL("Program.c1.Test", @"{ // Code size 133 (0x85) .maxstack 3 .locals init (Program.c1.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Func<System.Func<System.Func<System.Func<int>>>> V_1, //ff int V_2) IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldloc.0 IL_000e: ldc.i4.2 IL_000f: stfld ""int Program.c1.<>c__DisplayClass1_0.y"" IL_0014: ldnull IL_0015: stloc.1 IL_0016: ldc.i4.2 IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""string int.ToString()"" IL_001f: brfalse.s IL_0040 IL_0021: newobj ""Program.c1.<>c__DisplayClass1_1..ctor()"" IL_0026: dup IL_0027: ldloc.0 IL_0028: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_1.CS$<>8__locals1"" IL_002d: dup IL_002e: ldc.i4.3 IL_002f: stfld ""int Program.c1.<>c__DisplayClass1_1.z"" IL_0034: ldftn ""System.Func<System.Func<System.Func<int>>> Program.c1.<>c__DisplayClass1_1.<Test>b__0()"" IL_003a: newobj ""System.Func<System.Func<System.Func<System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_003f: stloc.1 IL_0040: ldc.i4.2 IL_0041: stloc.2 IL_0042: ldloca.s V_2 IL_0044: call ""string int.ToString()"" IL_0049: brfalse.s IL_006a IL_004b: newobj ""Program.c1.<>c__DisplayClass1_2..ctor()"" IL_0050: dup IL_0051: ldloc.0 IL_0052: stfld ""Program.c1.<>c__DisplayClass1_0 Program.c1.<>c__DisplayClass1_2.CS$<>8__locals2"" IL_0057: dup IL_0058: ldc.i4.3 IL_0059: stfld ""int Program.c1.<>c__DisplayClass1_2.z"" IL_005e: ldftn ""System.Func<System.Func<System.Func<int>>> Program.c1.<>c__DisplayClass1_2.<Test>b__4()"" IL_0064: newobj ""System.Func<System.Func<System.Func<System.Func<int>>>>..ctor(object, System.IntPtr)"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: callvirt ""System.Func<System.Func<System.Func<int>>> System.Func<System.Func<System.Func<System.Func<int>>>>.Invoke()"" IL_0070: callvirt ""System.Func<System.Func<int>> System.Func<System.Func<System.Func<int>>>.Invoke()"" IL_0075: callvirt ""System.Func<int> System.Func<System.Func<int>>.Invoke()"" IL_007a: callvirt ""int System.Func<int>.Invoke()"" IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: ret } "); } [Fact] public void ParentFrame04() { string source = @" using System; public static class Program { public static void Main() { var c = new c1(); System.Console.WriteLine(c.Test()); } class c1 { public int goo = 42; public object Test() { if (T()) { Func<int, Boolean> a = (s) => s == goo && ((Func<bool>)(() => s == goo)).Invoke(); return a.Invoke(42); } int aaa = 42; if (T()) { Func<int, bool> a = (s) => aaa == goo; return a.Invoke(42); } return null; } private bool T() { return true; } } } "; CompileAndVerify(source, expectedOutput: "True"). VerifyIL("Program.c1.Test", @" { // Code size 89 (0x59) .maxstack 2 .locals init (Program.c1.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""Program.c1 Program.c1.<>c__DisplayClass1_0.<>4__this"" IL_000d: ldarg.0 IL_000e: call ""bool Program.c1.T()"" IL_0013: brfalse.s IL_002e IL_0015: ldloc.0 IL_0016: ldftn ""bool Program.c1.<>c__DisplayClass1_0.<Test>b__0(int)"" IL_001c: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0021: ldc.i4.s 42 IL_0023: callvirt ""bool System.Func<int, bool>.Invoke(int)"" IL_0028: box ""bool"" IL_002d: ret IL_002e: ldloc.0 IL_002f: ldc.i4.s 42 IL_0031: stfld ""int Program.c1.<>c__DisplayClass1_0.aaa"" IL_0036: ldarg.0 IL_0037: call ""bool Program.c1.T()"" IL_003c: brfalse.s IL_0057 IL_003e: ldloc.0 IL_003f: ldftn ""bool Program.c1.<>c__DisplayClass1_0.<Test>b__2(int)"" IL_0045: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_004a: ldc.i4.s 42 IL_004c: callvirt ""bool System.Func<int, bool>.Invoke(int)"" IL_0051: box ""bool"" IL_0056: ret IL_0057: ldnull IL_0058: ret } "); } [Fact] public void ParentFrame05() { // IMPORTANT: Program.c1.<>c__DisplayClass1_0 should not capture any frame pointers. string source = @" using System; class Program { static void Main(string[] args) { var t = new c1(); t.Test(); } class c1 { int x = 1; public void Test() { Func<int> ff = null; Func<int> aa = null; if (T()) { int a = 1; if (T()) { int b = 4; ff = () => a + b; aa = () => x; } } Console.WriteLine(ff() + aa()); } private bool T() { return true; } } } "; CompileAndVerify(source, expectedOutput: "6"). VerifyIL("Program.c1.Test", @"{ // Code size 85 (0x55) .maxstack 2 .locals init (System.Func<int> V_0, //ff System.Func<int> V_1, //aa Program.c1.<>c__DisplayClass1_0 V_2) //CS$<>8__locals0 IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldarg.0 IL_0005: call ""bool Program.c1.T()"" IL_000a: brfalse.s IL_0042 IL_000c: newobj ""Program.c1.<>c__DisplayClass1_0..ctor()"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.1 IL_0014: stfld ""int Program.c1.<>c__DisplayClass1_0.a"" IL_0019: ldarg.0 IL_001a: call ""bool Program.c1.T()"" IL_001f: brfalse.s IL_0042 IL_0021: ldloc.2 IL_0022: ldc.i4.4 IL_0023: stfld ""int Program.c1.<>c__DisplayClass1_0.b"" IL_0028: ldloc.2 IL_0029: ldftn ""int Program.c1.<>c__DisplayClass1_0.<Test>b__0()"" IL_002f: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0034: stloc.0 IL_0035: ldarg.0 IL_0036: ldftn ""int Program.c1.<Test>b__1_1()"" IL_003c: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0041: stloc.1 IL_0042: ldloc.0 IL_0043: callvirt ""int System.Func<int>.Invoke()"" IL_0048: ldloc.1 IL_0049: callvirt ""int System.Func<int>.Invoke()"" IL_004e: add IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: ret }"); } [Fact] public void ClosuresInConstructorAndInitializers1() { string source = @" using System; class C { int f1 = new Func<int, int>(x => 1)(1); int f2 = new Func<int, int>(x => 2)(1); C() { int l = new Func<int, int>(x => 3)(1); } }"; CompileAndVerify(source); } [Fact] public void ClosuresInConstructorAndInitializers2() { string source = @" using System; class C { int f1 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); int f2 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } }"; CompileAndVerify(source); } [Fact] public void ClosuresInConstructorAndInitializers3() { string source = @" using System; class C { static int f1 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static int f2 = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } }"; CompileAndVerify(source); } [Fact] public void GenericStaticFrames() { string source = @" using System; public class C { public static void F<TF>() { var f = new Func<TF>(() => default(TF)); } public static void G<TG>() { var f = new Func<TG>(() => default(TG)); } public static void F<TF1, TF2>() { var f = new Func<TF1, TF2>(a => default(TF2)); } public static void G<TG1, TG2>() { var f = new Func<TG1, TG2>(a => default(TG2)); } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.Equal(new[] { "C.<>c__0<TF>", "C.<>c__1<TG>", "C.<>c__2<TF1, TF2>", "C.<>c__3<TG1, TG2>" }, c.GetMembers().Where(member => member.Kind == SymbolKind.NamedType).Select(member => member.ToString())); var c0 = c.GetMember<NamedTypeSymbol>("<>c__0"); AssertEx.SetEqual(new[] { "C.<>c__0<TF>.<>9", "C.<>c__0<TF>.<>9__0_0", "C.<>c__0<TF>.<>c__0()", "C.<>c__0<TF>.<>c__0()", "C.<>c__0<TF>.<F>b__0_0()", }, c0.GetMembers().Select(member => member.ToString())); var c1 = c.GetMember<NamedTypeSymbol>("<>c__1"); AssertEx.SetEqual(new[] { "C.<>c__1<TG>.<>9", "C.<>c__1<TG>.<>9__1_0", "C.<>c__1<TG>.<>c__1()", "C.<>c__1<TG>.<>c__1()", "C.<>c__1<TG>.<G>b__1_0()", }, c1.GetMembers().Select(member => member.ToString())); var c2 = c.GetMember<NamedTypeSymbol>("<>c__2"); AssertEx.SetEqual(new[] { "C.<>c__2<TF1, TF2>.<>9", "C.<>c__2<TF1, TF2>.<>9__2_0", "C.<>c__2<TF1, TF2>.<>c__2()", "C.<>c__2<TF1, TF2>.<>c__2()", "C.<>c__2<TF1, TF2>.<F>b__2_0(TF1)", }, c2.GetMembers().Select(member => member.ToString())); var c3 = c.GetMember<NamedTypeSymbol>("<>c__3"); AssertEx.SetEqual(new[] { "C.<>c__3<TG1, TG2>.<>9", "C.<>c__3<TG1, TG2>.<>9__3_0", "C.<>c__3<TG1, TG2>.<>c__3()", "C.<>c__3<TG1, TG2>.<>c__3()", "C.<>c__3<TG1, TG2>.<G>b__3_0(TG1)", }, c3.GetMembers().Select(member => member.ToString())); }); } [Fact] public void GenericStaticFramesWithConstraints() { string source = @" using System; public class C { public static void F<TF>() where TF : class { var f = new Func<TF>(() => default(TF)); } public static void G<TG>() where TG : struct { var f = new Func<TG>(() => default(TG)); } }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.Equal(new[] { "C.<>c__0<TF>", "C.<>c__1<TG>", }, c.GetMembers().Where(member => member.Kind == SymbolKind.NamedType).Select(member => member.ToString())); }); } [Fact] public void GenericInstance() { string source = @" using System; public class C { public void F<TF>() { var f = new Func<TF>(() => { this.F(); return default(TF); }); } public void G<TG>() { var f = new Func<TG>(() => { this.F(); return default(TG); }); } public void F<TF1, TF2>() { var f = new Func<TF1, TF2>(a => { this.F(); return default(TF2); }); } public void G<TG1, TG2>() { var f = new Func<TG1, TG2>(a => { this.F(); return default(TG2); }); } private void F() {} }"; CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); AssertEx.SetEqual(new[] { "C.F<TF>()", "C.G<TG>()", "C.F<TF1, TF2>()", "C.G<TG1, TG2>()", "C.F()", "C.C()", "C.<F>b__0_0<TF>()", "C.<G>b__1_0<TG>()", "C.<F>b__2_0<TF1, TF2>(TF1)", "C.<G>b__3_0<TG1, TG2>(TG1)", }, c.GetMembers().Select(member => member.ToString())); }); } #region "Regressions" [WorkItem(539439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539439")] [Fact] public void LambdaWithReturn() { string source = @" using System; class Program { delegate int Func(int i, int r); static void Main(string[] args) { Func fnc = (arg, arg2) => { return 1 + 2; }; Console.Write(fnc(3, 4)); } }"; CompileAndVerify(source, expectedOutput: @"3"); } /// <remarks> /// Based on MadsT blog post: /// http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx /// </remarks> [WorkItem(540034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540034")] [Fact] public void YCombinatorTest() { var source = @" using System; using System.Linq; public class Program { delegate T SelfApplicable<T>(SelfApplicable<T> self); static void Main() { // The Y combinator SelfApplicable< Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> > Y = y => f => x => f(y(y)(f))(x); // The fixed point generator Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> Fix = Y(Y); // The higher order function describing factorial Func<Func<int, int>, Func<int, int>> F = fac => x => { if (x == 0) { return 1; } else { return x * fac(x - 1); } }; // The factorial function itself Func<int, int> factorial = Fix(F); Console.WriteLine(string.Join( Environment.NewLine, Enumerable.Select(Enumerable.Range(0, 12), factorial))); } } "; CompileAndVerify( source, expectedOutput: @"1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800" ); } [WorkItem(540035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540035")] [Fact] public void LongNameTest() { var source = @" using System; namespace Lambda.Bugs { public interface I<T> { void Goo(int x); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo(int x) { Func<int> f = () => x; Console.WriteLine(f()); } } } public class Program { public static void Main() { I<OuterGenericClass<int, int>.NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> x = new OuterGenericClass<int, int>.C(); x.Goo(1); } } } "; CreateCompilation(source).VerifyEmitDiagnostics( // (17,81): error CS7013: Name 'Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo' exceeds the maximum length allowed in metadata. // void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo(int x) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo").WithLocation(17, 81), // (19,31): error CS7013: Name '<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0' exceeds the maximum length allowed in metadata. // Func<int> f = () => x; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => x").WithArguments("<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0").WithLocation(19, 31), // (19,31): error CS7013: Name '<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0' exceeds the maximum length allowed in metadata. // Func<int> f = () => x; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => x").WithArguments("<Lambda.Bugs.I<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass,Lambda.Bugs.OuterGenericClass<Lambda.Bugs.OuterGenericClass<T,S>.NestedClass,Lambda.Bugs.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo>b__0").WithLocation(19, 31) ); } [WorkItem(540049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540049")] [Fact] public void LambdaWithUnreachableCode() { var source = @" using System; class Program { static void Main() { int x = 7; Action f = () => { int y; Console.Write(x); return; int z = y; }; f(); } } "; CompileAndVerify(source, expectedOutput: "7"); } [Fact] [WorkItem(1019237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019237")] [WorkItem(10838, "https://github.com/mono/mono/issues/10838")] public void OrderOfDelegateMembers() { var source = @" using System.Linq; class Program { delegate int D1(); static void Main() { foreach (var member in typeof(D1).GetMembers( System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).OrderBy(m=>m.MetadataToken)) { System.Console.WriteLine(member.ToString()); } } } "; // ref emit would just have different metadata tokens // we are not interested in testing that CompileAndVerify(source, expectedOutput: @" Void .ctor(System.Object, IntPtr) Int32 Invoke() System.IAsyncResult BeginInvoke(System.AsyncCallback, System.Object) Int32 EndInvoke(System.IAsyncResult) "); } [WorkItem(540092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540092")] [Fact] public void NestedAnonymousMethodsUsingLocalAndField() { string source = @" using System; delegate void MyDel(int i); class Test { int j = 1; static int Main() { Test t = new Test(); t.goo(); return 0; } void goo() { int l = 0; MyDel d = delegate { Console.WriteLine(l++); }; d = delegate(int i) { MyDel dd = delegate(int k) { Console.WriteLine(i + j + k); }; dd(10); }; d(100); } } "; CompileAndVerify(source, expectedOutput: "111"); } [WorkItem(540129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540129")] [Fact] public void CacheStaticAnonymousMethodInField() { string source = @" using System; delegate void D(); public delegate void E<T, U>(T t, U u); public class Gen<T> { public static void Goo<U>(T t, U u) { ((D)delegate { ((E<T, U>)delegate(T t2, U u2) { // do nothing in order to allow this anonymous method to be cached in a static field })(t, u); })(); } } public class Test { public static void Main() { Gen<int>.Goo<string>(1, ""2""); Console.WriteLine(""PASS""); } } "; CompileAndVerify(source, expectedOutput: "PASS"); } [WorkItem(540147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540147")] [Fact] public void CapturedVariableNamedThis() { var source = @" using System; class A { public int N; public A(int n) { this.N = n; } public void Goo(A @this) { Action a = () => Bar(@this); a.Invoke(); } public void Bar(A other) { Console.Write(this.N); Console.Write(other.N); } static void Main() { A a = new A(1); A b = new A(2); a.Goo(b); } } "; var verifier = CompileAndVerify( source, expectedOutput: "12"); } [Fact] public void StaticClosureSerialize() { string source = @" using System; class Program { static void Main(string[] args) { Func<int> x = () => 42; System.Console.WriteLine(x.Target.GetType().IsSerializable); Func<int> y = () => x(); System.Console.WriteLine(y.Target.GetType().IsSerializable); } } "; var compilation = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"True False"); } [Fact] public void StaticClosureSerializeD() { string source = @" using System; class Program { static void Main(string[] args) { Func<int> x = () => 42; System.Console.WriteLine(x.Target.GetType().IsSerializable); Func<int> y = () => x(); System.Console.WriteLine(y.Target.GetType().IsSerializable); } } "; var compilation = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"True False"); } [WorkItem(540178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540178")] [Fact] public void NestedGenericLambda() { var source = @" using System; class Program { static void Main() { Goo<int>()()(); } static Func<Func<T>> Goo<T>() { T[] x = new T[1]; return () => () => x[0]; } } "; var verifier = CompileAndVerify( source, expectedOutput: ""); } [WorkItem(540768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540768")] [Fact] public void TestClosureMethodAccessibility() { var source = @" using System; class Test { static void Main() { } Func<int, int> f = (x) => 0; Func<string, string> Goo() { string s = """"; Console.WriteLine(s); return (a) => s; } }"; // Dev11 emits "public", we emit "internal" visibility for <Goo>b__1: CompileAndVerify(source, expectedSignatures: new[] { Signature("Test+<>c__DisplayClass2_0", "<Goo>b__0", ".method assembly hidebysig instance System.String <Goo>b__0(System.String a) cil managed"), }); } [WorkItem(541008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541008")] [Fact] public void TooEarlyForThis() { // this tests for the C# analogue of VB bug 7520 var source = @"using System; class Program { int x; Program(int x) : this(z => x + 10) { this.x = x + 100; F(z => z + x + this.x + 1000); } Program(Func<int, int> func) {} void F(Func<int, int> func) { Console.Write(func(10000)); } public static void Main(string[] args) { new Program(1); } }"; var verifier = CompileAndVerify( source, expectedOutput: "11102"); } [WorkItem(542062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542062")] [Fact] public void TestLambdaNoClosureClass() { var source = @" using System; delegate int D(); class Test { static D field = () => field2; static short field2 = -1; public static void Main() { D myd = delegate() { return 1; }; Console.WriteLine(""({0},{1})"", myd(), field()); } } "; //IMPORTANT!!! we should not be caching static lambda in static initializer. CompileAndVerify(source, expectedOutput: "(1,-1)").VerifyIL("Test..cctor", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldsfld ""Test.<>c Test.<>c.<>9"" IL_0005: ldftn ""int Test.<>c.<.cctor>b__4_0()"" IL_000b: newobj ""D..ctor(object, System.IntPtr)"" IL_0010: stsfld ""D Test.field"" IL_0015: ldc.i4.m1 IL_0016: stsfld ""short Test.field2"" IL_001b: ret } "); } [WorkItem(543087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543087")] [Fact] public void LambdaInGenericMethod() { var source = @" using System; delegate bool D(); class G<T> where T : class { public T Fld = default(T); public static bool RunTest<U>(U u) where U : class { G<U> g = new G<U>(); g.Fld = u; return ((D)(() => Test.Eval(g.Fld == u, true)))(); } } class Test { public static bool Eval(object obj1, object obj2) { return obj1.Equals(obj2); } static void Main() { var ret = G<string>.RunTest((string)null); Console.Write(ret); } } "; var verifier = CompileAndVerify( source, expectedOutput: "True"); } [WorkItem(543344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543344")] [Fact] public void AnonymousMethodOmitParameterList() { var source = @" using System; class C { public int M() { Func<C, int> f = delegate { return 9; } ; return f(new C()); } static void Main() { int r = new C().M(); Console.WriteLine((r == 9) ? 0 : 1); } } "; var verifier = CompileAndVerify( source, expectedOutput: "0"); } [WorkItem(543345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543345")] [Fact()] public void ExtraCompilerGeneratedAttribute() { string source = @"using System; using System.Reflection; using System.Runtime.CompilerServices; class Test { static public System.Collections.IEnumerable myIterator(int start, int end) { for (int i = start; i <= end; i++) { yield return (Func<int,int>)((x) => { return i + x; }); } yield break; } static void Main() { var type = typeof(Test); var nested = type.GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance); var total = 0; if (nested.Length > 0 && nested[0].Name.StartsWith(""<>c__DisplayClass"", StringComparison.Ordinal)) { foreach (MemberInfo mi in nested[0].GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { var ca = mi.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false); foreach (var a in ca) Console.WriteLine(mi + "": "" + a); total += ca.Length; } } Console.WriteLine(total); } } "; var compilation = CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(545430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545430")] [Fact] public void CacheNonStaticLambdaInGenericMethod() { var source = @" using System.Collections.Generic; using System.Linq; class C { static void M<T>(List<T> dd, int p) where T : D { do{ if (dd != null) { var last = dd.LastOrDefault(m => m.P <= p); if (dd.Count() > 1) { dd.Reverse(); } } } while(false); } } class D { public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp, expectedSignatures: new[] { Signature("C+<>c__DisplayClass0_0`1", "<>9__0", ".field public instance System.Func`2[T,System.Boolean] <>9__0") }); verifier.VerifyIL("C.M<T>", @" { // Code size 70 (0x46) .maxstack 4 .locals init (C.<>c__DisplayClass0_0<T> V_0, //CS$<>8__locals0 System.Func<T, bool> V_1) IL_0000: newobj ""C.<>c__DisplayClass0_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""int C.<>c__DisplayClass0_0<T>.p"" IL_000d: ldarg.0 IL_000e: brfalse.s IL_0045 IL_0010: ldarg.0 IL_0011: ldloc.0 IL_0012: ldfld ""System.Func<T, bool> C.<>c__DisplayClass0_0<T>.<>9__0"" IL_0017: dup IL_0018: brtrue.s IL_0030 IL_001a: pop IL_001b: ldloc.0 IL_001c: ldloc.0 IL_001d: ldftn ""bool C.<>c__DisplayClass0_0<T>.<M>b__0(T)"" IL_0023: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stloc.1 IL_002a: stfld ""System.Func<T, bool> C.<>c__DisplayClass0_0<T>.<>9__0"" IL_002f: ldloc.1 IL_0030: call ""T System.Linq.Enumerable.LastOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)"" IL_0035: pop IL_0036: ldarg.0 IL_0037: call ""int System.Linq.Enumerable.Count<T>(System.Collections.Generic.IEnumerable<T>)"" IL_003c: ldc.i4.1 IL_003d: ble.s IL_0045 IL_003f: ldarg.0 IL_0040: callvirt ""void System.Collections.Generic.List<T>.Reverse()"" IL_0045: ret } "); } [Fact] public void CacheNonStaticLambda001() { var source = @" using System; class Program { static void Main(string[] args) { } class Executor { public void Execute(Func<int, int> f) { f(42); } } Executor[] arr = new Executor[] { new Executor() }; void Test() { int x = 123; for (int i = 1; i < 10; i++) { if (i < 2) { arr[i].Execute(arg => arg + x); // delegate should be cached } } for (int i = 1; i < 10; i++) { var val = i; if (i < 2) { int y = i + i; System.Console.WriteLine(y); arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop) } } } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp); verifier.VerifyIL("Program.Test", @" { // Code size 142 (0x8e) .maxstack 4 .locals init (Program.<>c__DisplayClass3_0 V_0, //CS$<>8__locals0 int V_1, //i System.Func<int, int> V_2, int V_3, //i Program.<>c__DisplayClass3_1 V_4) //CS$<>8__locals1 IL_0000: newobj ""Program.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.s 123 IL_0009: stfld ""int Program.<>c__DisplayClass3_0.x"" IL_000e: ldc.i4.1 IL_000f: stloc.1 IL_0010: br.s IL_0046 IL_0012: ldloc.1 IL_0013: ldc.i4.2 IL_0014: bge.s IL_0042 IL_0016: ldarg.0 IL_0017: ldfld ""Program.Executor[] Program.arr"" IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: ldloc.0 IL_001f: ldfld ""System.Func<int, int> Program.<>c__DisplayClass3_0.<>9__0"" IL_0024: dup IL_0025: brtrue.s IL_003d IL_0027: pop IL_0028: ldloc.0 IL_0029: ldloc.0 IL_002a: ldftn ""int Program.<>c__DisplayClass3_0.<Test>b__0(int)"" IL_0030: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0035: dup IL_0036: stloc.2 IL_0037: stfld ""System.Func<int, int> Program.<>c__DisplayClass3_0.<>9__0"" IL_003c: ldloc.2 IL_003d: callvirt ""void Program.Executor.Execute(System.Func<int, int>)"" IL_0042: ldloc.1 IL_0043: ldc.i4.1 IL_0044: add IL_0045: stloc.1 IL_0046: ldloc.1 IL_0047: ldc.i4.s 10 IL_0049: blt.s IL_0012 IL_004b: ldc.i4.1 IL_004c: stloc.3 IL_004d: br.s IL_0088 IL_004f: newobj ""Program.<>c__DisplayClass3_1..ctor()"" IL_0054: stloc.s V_4 IL_0056: ldloc.s V_4 IL_0058: ldloc.3 IL_0059: stfld ""int Program.<>c__DisplayClass3_1.val"" IL_005e: ldloc.3 IL_005f: ldc.i4.2 IL_0060: bge.s IL_0084 IL_0062: ldloc.3 IL_0063: ldloc.3 IL_0064: add IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: ldarg.0 IL_006b: ldfld ""Program.Executor[] Program.arr"" IL_0070: ldloc.3 IL_0071: ldelem.ref IL_0072: ldloc.s V_4 IL_0074: ldftn ""int Program.<>c__DisplayClass3_1.<Test>b__1(int)"" IL_007a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_007f: callvirt ""void Program.Executor.Execute(System.Func<int, int>)"" IL_0084: ldloc.3 IL_0085: ldc.i4.1 IL_0086: add IL_0087: stloc.3 IL_0088: ldloc.3 IL_0089: ldc.i4.s 10 IL_008b: blt.s IL_004f IL_008d: ret } "); } [Fact] public void CacheNonStaticLambda002() { var source = @" using System; class Program { static void Main(string[] args) { } void Test() { int y = 123; Func<int, Func<int>> f1 = // should be cached (x) => { if (x > 0) { int z = 123; System.Console.WriteLine(z); return () => y; } return null; }; f1(1); Func<int, Func<int>> f2 = // should NOT be cached (x) => { if (x > 0) { int z = 123; System.Console.WriteLine(z); return () => x; } return null; }; f2(1); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); var verifier = CompileAndVerify(comp); verifier.VerifyIL("Program.Test", @" { // Code size 70 (0x46) .maxstack 3 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: dup IL_0006: ldc.i4.s 123 IL_0008: stfld ""int Program.<>c__DisplayClass1_0.y"" IL_000d: ldftn ""System.Func<int> Program.<>c__DisplayClass1_0.<Test>b__0(int)"" IL_0013: newobj ""System.Func<int, System.Func<int>>..ctor(object, System.IntPtr)"" IL_0018: ldc.i4.1 IL_0019: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_001e: pop IL_001f: ldsfld ""System.Func<int, System.Func<int>> Program.<>c.<>9__1_1"" IL_0024: dup IL_0025: brtrue.s IL_003e IL_0027: pop IL_0028: ldsfld ""Program.<>c Program.<>c.<>9"" IL_002d: ldftn ""System.Func<int> Program.<>c.<Test>b__1_1(int)"" IL_0033: newobj ""System.Func<int, System.Func<int>>..ctor(object, System.IntPtr)"" IL_0038: dup IL_0039: stsfld ""System.Func<int, System.Func<int>> Program.<>c.<>9__1_1"" IL_003e: ldc.i4.1 IL_003f: callvirt ""System.Func<int> System.Func<int, System.Func<int>>.Invoke(int)"" IL_0044: pop IL_0045: ret } "); verifier.VerifyIL("Program.<>c.<Test>b__1_1(int)", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (Program.<>c__DisplayClass1_1 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_1..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld ""int Program.<>c__DisplayClass1_1.x"" IL_000d: ldloc.0 IL_000e: ldfld ""int Program.<>c__DisplayClass1_1.x"" IL_0013: ldc.i4.0 IL_0014: ble.s IL_002a IL_0016: ldc.i4.s 123 IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: ldloc.0 IL_001e: ldftn ""int Program.<>c__DisplayClass1_1.<Test>b__3()"" IL_0024: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0029: ret IL_002a: ldnull IL_002b: ret } " ); verifier.VerifyIL("Program.<>c__DisplayClass1_0.<Test>b__0(int)", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Func<int> V_0) IL_0000: ldarg.1 IL_0001: ldc.i4.0 IL_0002: ble.s IL_002b IL_0004: ldc.i4.s 123 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: ldarg.0 IL_000c: ldfld ""System.Func<int> Program.<>c__DisplayClass1_0.<>9__2"" IL_0011: dup IL_0012: brtrue.s IL_002a IL_0014: pop IL_0015: ldarg.0 IL_0016: ldarg.0 IL_0017: ldftn ""int Program.<>c__DisplayClass1_0.<Test>b__2()"" IL_001d: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0022: dup IL_0023: stloc.0 IL_0024: stfld ""System.Func<int> Program.<>c__DisplayClass1_0.<>9__2"" IL_0029: ldloc.0 IL_002a: ret IL_002b: ldnull IL_002c: ret } " ); } [WorkItem(546211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546211")] [Fact] public void LambdaInCatchInLambdaInInstance() { var source = @"using System; static class Utilities { internal static void ReportException(object _componentModelHost, Exception e, string p) { } internal static void BeginInvoke(Action a) { } } class VsCatalogProvider { private object _componentModelHost = null; static void Main() { Console.WriteLine(""success""); } private void TryIsolatedOperation() { Action action = new Action(() => { try { } catch (Exception ex) { Utilities.BeginInvoke(new Action(() => { Utilities.ReportException(_componentModelHost, ex, string.Empty); })); } }); } }"; var compilation = CompileAndVerify(source, expectedOutput: "success"); } [WorkItem(546748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546748")] [Fact] public void LambdaWithCatchTypeParameter() { var source = @"using System; class Program { static void Main() { } public static void Sleep<TException>(Func<bool> sleepDelegate) where TException : Exception { Func<bool> x = delegate { try { return sleepDelegate(); } catch (TException e) { } return false; }; } }"; CompileAndVerify(source); } [WorkItem(546748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546748")] [Fact] public void LambdaWithCapturedCatchTypeParameter() { var source = @"using System; class Program { static void Main() { } public static void Sleep<TException>(Func<bool> sleepDelegate) where TException : Exception { Func<bool> x = delegate { try { return sleepDelegate(); } catch (TException e) { Func<bool> x2 = delegate { return e == null; }; } return false; }; } }"; var compilation = CompileAndVerify(source); } [WorkItem(530911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530911")] [Fact] public void LambdaWithOutParameter() { var source = @" using System; delegate D D(out D d); class Program { static void Main() { D tmpD = delegate (out D d) { throw new System.Exception(); }; D d01 = delegate (out D d) { tmpD(out d); d(out d); return d; }; } } "; var compilation = CompileAndVerify(source); } [WorkItem(691006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/691006")] [Fact] public void LambdaWithSwitch() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication16 { class Program { public static Task<IEnumerable<TResult>> Iterate<TResult>(IEnumerable<Task> asyncIterator, CancellationToken cancellationToken = default(CancellationToken)) { var results = new List<TResult>(); var tcs = new TaskCompletionSource<IEnumerable<TResult>>(); IEnumerator<Task> enumerator = asyncIterator.GetEnumerator(); Action recursiveBody = null; recursiveBody = () => { try { if (cancellationToken.IsCancellationRequested) { tcs.TrySetCanceled(); } else if (enumerator.MoveNext()) { enumerator.Current.ContinueWith(previous => { switch (previous.Status) { case TaskStatus.Faulted: case TaskStatus.Canceled: tcs.SetResult((previous as Task<IEnumerable<TResult>>).Result); break; default: var previousWithResult = previous as Task<TResult>; if (previousWithResult != null) { results.Add(previousWithResult.Result); } else { results.Add(default(TResult)); } recursiveBody(); break; } }); } else { tcs.TrySetResult(results); } } catch (Exception e) { tcs.TrySetException(e); } }; recursiveBody(); return tcs.Task; } static void Main(string[] args) { } } } "; CompileAndVerify(source); } #endregion [Fact] public void LambdaInQuery_Let() { var source = @" using System; using System.Linq; class C { public void F(int[] array) { var f = from item in array let a = new Func<int>(() => item) select a() + new Func<int>(() => item)(); } }"; CompileAndVerify(source); } [Fact] public void LambdaInQuery_From() { var source = @" using System; using System.Linq; class C { public void F(int[] array) { var f = from item1 in new Func<int[]>(() => array)() from item2 in new Func<int[]>(() => array)() select item1 + item2; } }"; CompileAndVerify(source); } [Fact] public void EmbeddedStatementClosures1() { var source = @" using System; using System.Collections.Generic; using System.IO; using System.Linq; class C { public void G<T>(Func<T> f) {} public void F() { for (int x = 1, y = 2; x < 10; x++) G(() => x + y); for (int x = 1, y = 2; x < 10; x++) { G(() => x + y); } foreach (var x in new[] { 1, 2, 3 }) G(() => x); foreach (var x in new[] { 1, 2, 3 }) { G(() => x); } foreach (var x in new[,] { {1}, {2}, {3} }) G(() => x); foreach (var x in new[,] { {1}, {2}, {3} }) { G(() => x); } foreach (var x in ""123"") G(() => x); foreach (var x in ""123"") { G(() => x); } foreach (var x in new List<string>()) G(() => x); foreach (var x in new List<string>()) { G(() => x); } using (var x = new MemoryStream()) G(() => x); using (var x = new MemoryStream()) G(() => x); } }"; CompileAndVerify(source); } [Fact, WorkItem(2549, "https://github.com/dotnet/roslyn/issues/2549")] public void NestedLambdaWithExtensionMethodsInGeneric() { var source = @"using System; using System.Collections.Generic; using System.Linq; public class BadBaby { IEnumerable<object> Children; public object Goo<T>() { return from child in Children select from T ch in Children select false; } }"; CompileAndVerify(source); } [WorkItem(9131, "https://github.com/dotnet/roslyn/issues/9131")] [Fact] public void ClosureInSwitchStatementWithNullableExpression() { string source = @"using System; class C { static void Main() { int? i = null; switch (i) { default: object o = null; Func<object> f = () => o; Console.Write(""{0}"", f() == null); break; case 0: o = 1; break; } } }"; var compilation = CompileAndVerify(source, expectedOutput: @"True"); compilation.VerifyIL("C.Main", @"{ // Code size 90 (0x5a) .maxstack 3 .locals init (int? V_0, //i C.<>c__DisplayClass0_0 V_1, //CS$<>8__locals0 System.Func<object> V_2) //f IL_0000: ldloca.s V_0 IL_0002: initobj ""int?"" IL_0008: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_0 IL_0010: call ""bool int?.HasValue.get"" IL_0015: brfalse.s IL_0020 IL_0017: ldloca.s V_0 IL_0019: call ""int int?.GetValueOrDefault()"" IL_001e: brfalse.s IL_004d IL_0020: ldloc.1 IL_0021: ldnull IL_0022: stfld ""object C.<>c__DisplayClass0_0.o"" IL_0027: ldloc.1 IL_0028: ldftn ""object C.<>c__DisplayClass0_0.<Main>b__0()"" IL_002e: newobj ""System.Func<object>..ctor(object, System.IntPtr)"" IL_0033: stloc.2 IL_0034: ldstr ""{0}"" IL_0039: ldloc.2 IL_003a: callvirt ""object System.Func<object>.Invoke()"" IL_003f: ldnull IL_0040: ceq IL_0042: box ""bool"" IL_0047: call ""void System.Console.Write(string, object)"" IL_004c: ret IL_004d: ldloc.1 IL_004e: ldc.i4.1 IL_004f: box ""int"" IL_0054: stfld ""object C.<>c__DisplayClass0_0.o"" IL_0059: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly() { // The lambda passed into StaticMethod depends on TLocal type argument of LocalMethod // so if the delegate is cached outside the method the type argument reference is broken // and code throws BadImageFormatException. Such a broken code will looks like: // class DisplayClass // { // Func<TLocal, string> _cachedDelegate; // // void LocalMethod<TLocal>() // { // ... // } // // The test checks that it is not the issue. string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } /// <summary> /// Check <see cref="LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly"/> summary /// for the test case description /// </summary> [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter2_CompilesCorrectly() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { InnerLocalFunction(); void InnerLocalFunction() { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } /// <summary> /// Check <see cref="LambdaDependentOnEnclosingLocalFunctionTypeParameter1_CompilesCorrectly"/> summary /// for the test case description /// </summary> [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingLocalFunctionTypeParameter3_CompilesCorrectly() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; OuterLocalFunction(); void OuterLocalFunction() { for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(value, param, (_, __) => message); StaticMethod(new List<TLocal> { value }, param, (_, __) => message); StaticMethod(new TLocal[] { value }, param, (_, __) => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } } static void StaticMethod<TFirst, TSecond, TOut>(TFirst first, TSecond second, Func<TFirst, TSecond, TOut> func) { Console.Write($""{func(first, second)}-{typeof(TFirst)};""); } }"; CompileAndVerify(source, expectedOutput: @"0-System.String;0-System.Collections.Generic.List`1[System.String];0-System.String[];"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideLocalFunctionInsideLoop_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalMethod() { StaticMethod(message, _ => message); } message = i.ToString(); LocalMethod(); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.<>c__DisplayClass0_0.<Main>g__LocalMethod|0()", @"{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Func<string, string> V_0) IL_0000: ldarg.0 IL_0001: ldfld ""string Program.<>c__DisplayClass0_0.message"" IL_0006: ldarg.0 IL_0007: ldfld ""System.Func<string, string> Program.<>c__DisplayClass0_0.<>9__1"" IL_000c: dup IL_000d: brtrue.s IL_0025 IL_000f: pop IL_0010: ldarg.0 IL_0011: ldarg.0 IL_0012: ldftn ""string Program.<>c__DisplayClass0_0.<Main>b__1(string)"" IL_0018: newobj ""System.Func<string, string>..ctor(object, System.IntPtr)"" IL_001d: dup IL_001e: stloc.0 IL_001f: stfld ""System.Func<string, string> Program.<>c__DisplayClass0_0.<>9__1"" IL_0024: ldloc.0 IL_0025: call ""void Program.StaticMethod<string, string>(string, System.Func<string, string>)"" IL_002a: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaDependentOnEnclosingMethodTypeParameter_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { message = i.ToString(); StaticMethod(param, _ => message); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.TestMethod<T>(T)", @"{ // Code size 80 (0x50) .maxstack 4 .locals init (Program.<>c__DisplayClass1_0<T> V_0, //CS$<>8__locals0 int V_1, //i System.Func<T, string> V_2) IL_0000: newobj ""Program.<>c__DisplayClass1_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld ""string string.Empty"" IL_000c: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_004b IL_0015: ldloc.0 IL_0016: ldloca.s V_1 IL_0018: call ""string int.ToString()"" IL_001d: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0022: ldarg.0 IL_0023: ldloc.0 IL_0024: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0029: dup IL_002a: brtrue.s IL_0042 IL_002c: pop IL_002d: ldloc.0 IL_002e: ldloc.0 IL_002f: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__0(T)"" IL_0035: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_003a: dup IL_003b: stloc.2 IL_003c: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0041: ldloc.2 IL_0042: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_0047: ldloc.1 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: ldc.i4.1 IL_004d: blt.s IL_0015 IL_004f: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideGenericLocalFunction_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { void LocalFunction<TLocal>(TLocal value) { StaticMethod(param, _ => message); } message = i.ToString(); LocalFunction<string>(string.Empty); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.<>c__DisplayClass1_0<T>.<TestMethod>g__LocalFunction|0<TLocal>(TLocal)", @"{ // Code size 43 (0x2b) .maxstack 4 .locals init (System.Func<T, string> V_0) IL_0000: ldarg.0 IL_0001: ldfld ""T Program.<>c__DisplayClass1_0<T>.param"" IL_0006: ldarg.0 IL_0007: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__1"" IL_000c: dup IL_000d: brtrue.s IL_0025 IL_000f: pop IL_0010: ldarg.0 IL_0011: ldarg.0 IL_0012: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__1<TLocal>(T)"" IL_0018: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_001d: dup IL_001e: stloc.0 IL_001f: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__1"" IL_0024: ldloc.0 IL_0025: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_002a: ret }"); } [WorkItem(44720, "https://github.com/dotnet/roslyn/issues/44720")] [Fact] public void LambdaInsideGenericMethod_IsCached() { string source = @"using System; using System.Collections.Generic; static class Program { private static void Main() { TestMethod(string.Empty); } private static void TestMethod<T>(T param) { var message = string.Empty; for (int i = 0; i < 1; i++) { message = i.ToString(); StaticMethod(param, _ => message); } } static void StaticMethod<TIn, TOut>(TIn value, Func<TIn, TOut> func) { Console.Write($""{func(value)}-{typeof(TIn)};""); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"0-System.String;"); compilation.VerifyIL("Program.TestMethod<T>(T)", @"{ // Code size 80 (0x50) .maxstack 4 .locals init (Program.<>c__DisplayClass1_0<T> V_0, //CS$<>8__locals0 int V_1, //i System.Func<T, string> V_2) IL_0000: newobj ""Program.<>c__DisplayClass1_0<T>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld ""string string.Empty"" IL_000c: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0011: ldc.i4.0 IL_0012: stloc.1 IL_0013: br.s IL_004b IL_0015: ldloc.0 IL_0016: ldloca.s V_1 IL_0018: call ""string int.ToString()"" IL_001d: stfld ""string Program.<>c__DisplayClass1_0<T>.message"" IL_0022: ldarg.0 IL_0023: ldloc.0 IL_0024: ldfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0029: dup IL_002a: brtrue.s IL_0042 IL_002c: pop IL_002d: ldloc.0 IL_002e: ldloc.0 IL_002f: ldftn ""string Program.<>c__DisplayClass1_0<T>.<TestMethod>b__0(T)"" IL_0035: newobj ""System.Func<T, string>..ctor(object, System.IntPtr)"" IL_003a: dup IL_003b: stloc.2 IL_003c: stfld ""System.Func<T, string> Program.<>c__DisplayClass1_0<T>.<>9__0"" IL_0041: ldloc.2 IL_0042: call ""void Program.StaticMethod<T, string>(T, System.Func<T, string>)"" IL_0047: ldloc.1 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: ldc.i4.1 IL_004d: blt.s IL_0015 IL_004f: ret }"); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/LocalSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class LocalSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILocalSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) => t => IdentifiersMatch(syntaxFacts, name, t); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class LocalSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILocalSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) => t => IdentifiersMatch(syntaxFacts, name, t); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/VisualStudio/Core/Def/Utilities/IServiceProviderExtensions.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.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IServiceProviderExtensions { /// <inheritdoc cref="Shell.ServiceExtensions.GetService{TService, TInterface}(IServiceProvider, bool)"/> public static TInterface GetService<TService, TInterface>(this IServiceProvider sp) { var service = (TInterface)sp.GetService(typeof(TService)); Debug.Assert(service != null); return service; } /// <summary> /// Returns the specified service type from the service. /// </summary> public static TServiceType GetService<TServiceType>(this IServiceProvider sp) where TServiceType : class => sp.GetService<TServiceType, TServiceType>(); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IServiceProviderExtensions { /// <inheritdoc cref="Shell.ServiceExtensions.GetService{TService, TInterface}(IServiceProvider, bool)"/> public static TInterface GetService<TService, TInterface>(this IServiceProvider sp) { var service = (TInterface)sp.GetService(typeof(TService)); Debug.Assert(service != null); return service; } /// <summary> /// Returns the specified service type from the service. /// </summary> public static TServiceType GetService<TServiceType>(this IServiceProvider sp) where TServiceType : class => sp.GetService<TServiceType, TServiceType>(); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Test/Semantic/Semantics/SynthesizedStaticConstructorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SynthesizedStaticConstructorTests : CompilingTestBase { [Fact] public void NoStaticMembers() { var source = @" class C { int i1; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void NoStaticFields() { var source = @" class C { int i1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void NoStaticInitializers() { var source = @" class C { int i1; static int s1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void StaticInitializers() { var source = @" class C { int i1; static int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void ConstantInitializers() { var source = @" class C { int i1; const int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticMembers() { var source = @" class C { static C() { } int i1; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticFields() { var source = @" class C { static C() { } int i1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticInitializers() { var source = @" class C { static C() { } int i1; static int s1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorStaticInitializers() { var source = @" class C { static C() { } int i1; static int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorConstantInitializers() { var source = @" class C { static C() { } int i1; const int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal01() { var source = @" class C { const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal02() { var source = @" class C { static C() { } const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal03() { var source = @" class C { decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal04() { var source = @" class C { static C() { } decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal05() { var source = @" class C { static int s1 = 1; const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void StaticConstructorNullInitializer() { var source = @" #nullable enable class C { static string s1 = null!; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); // Although we do not emit the synthesized static constructor, the source type symbol will still appear to have one Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } private static SourceNamedTypeSymbol CompileAndExtractTypeSymbol(string source) { var compilation = CreateCompilation(source); var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single(); return typeSymbol; } private static bool HasSynthesizedStaticConstructor(NamedTypeSymbol typeSymbol) { foreach (var member in typeSymbol.GetMembers(WellKnownMemberNames.StaticConstructorName)) { if (member.IsImplicitlyDeclared) { return true; } } return false; } private static bool IsBeforeFieldInit(NamedTypeSymbol typeSymbol) { return ((Microsoft.Cci.ITypeDefinition)typeSymbol.GetCciAdapter()).IsBeforeFieldInit; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SynthesizedStaticConstructorTests : CompilingTestBase { [Fact] public void NoStaticMembers() { var source = @" class C { int i1; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void NoStaticFields() { var source = @" class C { int i1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void NoStaticInitializers() { var source = @" class C { int i1; static int s1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void StaticInitializers() { var source = @" class C { int i1; static int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void ConstantInitializers() { var source = @" class C { int i1; const int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticMembers() { var source = @" class C { static C() { } int i1; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticFields() { var source = @" class C { static C() { } int i1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorNoStaticInitializers() { var source = @" class C { static C() { } int i1; static int s1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorStaticInitializers() { var source = @" class C { static C() { } int i1; static int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [Fact] public void SourceStaticConstructorConstantInitializers() { var source = @" class C { static C() { } int i1; const int s1 = 1; static void Goo() { } }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal01() { var source = @" class C { const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal02() { var source = @" class C { static C() { } const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal03() { var source = @" class C { decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal04() { var source = @" class C { static C() { } decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.False(HasSynthesizedStaticConstructor(typeSymbol)); Assert.False(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void SourceStaticConstructorConstantInitializersDecimal05() { var source = @" class C { static int s1 = 1; const decimal dec1 = 12345; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [Fact] public void StaticConstructorNullInitializer() { var source = @" #nullable enable class C { static string s1 = null!; }"; var typeSymbol = CompileAndExtractTypeSymbol(source); // Although we do not emit the synthesized static constructor, the source type symbol will still appear to have one Assert.True(HasSynthesizedStaticConstructor(typeSymbol)); Assert.True(IsBeforeFieldInit(typeSymbol)); } private static SourceNamedTypeSymbol CompileAndExtractTypeSymbol(string source) { var compilation = CreateCompilation(source); var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single(); return typeSymbol; } private static bool HasSynthesizedStaticConstructor(NamedTypeSymbol typeSymbol) { foreach (var member in typeSymbol.GetMembers(WellKnownMemberNames.StaticConstructorName)) { if (member.IsImplicitlyDeclared) { return true; } } return false; } private static bool IsBeforeFieldInit(NamedTypeSymbol typeSymbol) { return ((Microsoft.Cci.ITypeDefinition)typeSymbol.GetCciAdapter()).IsBeforeFieldInit; } } }
-1