Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix 'await completion' adding async to the wrong member #75517

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1091,5 +1091,80 @@ static class Program
Await state.AssertLineTextAroundCaret(" await c!.SomeTask!.ConfigureAwait(false)", ";")
End Using
End Function

<WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/67952")>
Public Async Function AwaitCompletion_AfterLocalFunction1() As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Test()
{
void Image_ImageOpened()
{
}

awai$$ Goo();
}
}
]]>
</Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True)

state.SendTab()
Assert.Equal("
class C
{
public async void Test()
{
void Image_ImageOpened()
{
}

await Goo();
}
}
", state.GetDocumentText())
End Using
End Function

<WpfFact, WorkItem("https://github.com/dotnet/roslyn/issues/67952")>
Public Async Function AwaitCompletion_AfterLocalFunction2() As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class C
{
public void Test()
{
void Image_ImageOpened()
{
}

$$ Goo();
}
}
]]>
</Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContain(displayText:="await", displayTextSuffix:="")

state.SendTypeChars("awai")
state.SendTab()
Assert.Equal("
class C
{
public async void Test()
{
void Image_ImageOpened()
{
}

await Goo();
}
}
", state.GetDocumentText())
End Using
End Function
End Class
End Namespace
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,20 @@
using Microsoft.CodeAnalysis.CSharp.LanguageService;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers;

[ExportCompletionProvider(nameof(AwaitCompletionProvider), LanguageNames.CSharp)]
[ExportCompletionProvider(nameof(AwaitCompletionProvider), LanguageNames.CSharp), Shared]
[ExtensionOrder(After = nameof(KeywordCompletionProvider))]
[Shared]
internal sealed class AwaitCompletionProvider : AbstractAwaitCompletionProvider
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal sealed class AwaitCompletionProvider() : AbstractAwaitCompletionProvider(CSharpSyntaxFacts.Instance)
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AwaitCompletionProvider()
: base(CSharpSyntaxFacts.Instance)
{
}

internal override string Language => LanguageNames.CSharp;

public override ImmutableHashSet<char> TriggerCharacters => CompletionUtilities.CommonTriggerCharactersWithArgumentList;

protected override bool IsAwaitKeywordContext(SyntaxContext syntaxContext)
Expand All @@ -55,24 +51,35 @@ protected override int GetSpanStart(SyntaxNode declaration)
};
}

protected override SyntaxNode? GetAsyncSupportingDeclaration(SyntaxToken token)
protected override SyntaxNode? GetAsyncSupportingDeclaration(SyntaxToken leftToken, int position)
{
// In a case like
// someTask.$$
// await Test();
// someTask.await Test() is parsed as a local function statement.
// We skip this and look further up in the hierarchy.
var parent = token.Parent;
var parent = leftToken.Parent;
if (parent == null)
return null;

if (parent is QualifiedNameSyntax { Parent: LocalFunctionStatementSyntax localFunction } qualifiedName &&
localFunction.ReturnType == qualifiedName)
if (parent is NameSyntax { Parent: LocalFunctionStatementSyntax localFunction } name &&
localFunction.ReturnType == name)
{
parent = localFunction;
parent = localFunction.GetRequiredParent();
}

return parent.AncestorsAndSelf().FirstOrDefault(node => node.IsAsyncSupportingFunctionSyntax());
return parent.AncestorsAndSelf().FirstOrDefault(node =>
{
if (!node.IsAsyncSupportingFunctionSyntax())
return false;

// Ensure that if we were outside of the async-supporting-function that we don't return it as the thing to
// make async. We want to make its parent async.
if (position > leftToken.FullSpan.End)
return node.Span.Contains(position);

return node.Span.IntersectsWith(position);
});
}

protected override SyntaxNode? GetExpressionToPlaceAwaitInFrontOf(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ namespace Microsoft.CodeAnalysis.Completion.Providers;
/// </summary>
internal abstract class AbstractAwaitCompletionProvider : LSPCompletionProvider
{
private const string AwaitCompletionTargetTokenPosition = nameof(AwaitCompletionTargetTokenPosition);
private const string Position = nameof(Position);
private const string LeftTokenPosition = nameof(LeftTokenPosition);
private const string AppendConfigureAwait = nameof(AppendConfigureAwait);
private const string MakeContainerAsync = nameof(MakeContainerAsync);

Expand Down Expand Up @@ -59,7 +60,7 @@ protected AbstractAwaitCompletionProvider(ISyntaxFacts syntaxFacts)
/// </summary>
protected abstract int GetSpanStart(SyntaxNode declaration);

protected abstract SyntaxNode? GetAsyncSupportingDeclaration(SyntaxToken token);
protected abstract SyntaxNode? GetAsyncSupportingDeclaration(SyntaxToken leftToken, int position);

protected abstract ITypeSymbol? GetTypeSymbolOfExpression(SemanticModel semanticModel, SyntaxNode potentialAwaitableExpression, CancellationToken cancellationToken);
protected abstract SyntaxNode? GetExpressionToPlaceAwaitInFrontOf(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
Expand Down Expand Up @@ -95,12 +96,13 @@ public sealed override async Task ProvideCompletionsAsync(CompletionContext cont
if (!isAwaitKeywordContext && dotAwaitContext == DotAwaitContext.None)
return;

var token = syntaxContext.TargetToken;
var declaration = GetAsyncSupportingDeclaration(token);
var leftToken = syntaxContext.LeftToken;
var declaration = GetAsyncSupportingDeclaration(leftToken, position);

using var builder = TemporaryArray<KeyValuePair<string, string>>.Empty;

builder.Add(KeyValuePairUtil.Create(AwaitCompletionTargetTokenPosition, token.SpanStart.ToString()));
builder.Add(KeyValuePairUtil.Create(Position, position.ToString()));
builder.Add(KeyValuePairUtil.Create(LeftTokenPosition, leftToken.SpanStart.ToString()));

var makeContainerAsync = declaration is not null && !SyntaxGenerator.GetGenerator(document).GetModifiers(declaration).IsAsync;
if (makeContainerAsync)
Expand Down Expand Up @@ -178,8 +180,9 @@ public sealed override async Task<CompletionChange> GetChangeAsync(Document docu
if (item.TryGetProperty(MakeContainerAsync, out var _))
{
var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var tokenPosition = int.Parse(item.GetProperty(AwaitCompletionTargetTokenPosition));
var declaration = GetAsyncSupportingDeclaration(root.FindToken(tokenPosition));
var position = int.Parse(item.GetProperty(Position));
var leftTokenPosition = int.Parse(item.GetProperty(LeftTokenPosition));
var declaration = GetAsyncSupportingDeclaration(root.FindToken(leftTokenPosition), position);
if (declaration is null)
{
// IsComplexTextEdit should only be true when GetAsyncSupportingDeclaration returns non-null.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ Imports Microsoft.CodeAnalysis.VisualBasic.LanguageService
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(AwaitCompletionProvider), LanguageNames.VisualBasic)>
<ExportCompletionProvider(NameOf(AwaitCompletionProvider), LanguageNames.VisualBasic), [Shared]>
<ExtensionOrder(After:=NameOf(KeywordCompletionProvider))>
<[Shared]>
Friend NotInheritable Class AwaitCompletionProvider
Inherits AbstractAwaitCompletionProvider

Expand Down Expand Up @@ -47,8 +46,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Throw ExceptionUtilities.Unreachable
End Function

Protected Overrides Function GetAsyncSupportingDeclaration(token As SyntaxToken) As SyntaxNode
Return token.GetAncestor(Function(node) node.IsAsyncSupportedFunctionSyntax())
Protected Overrides Function GetAsyncSupportingDeclaration(targetToken As SyntaxToken, position As Integer) As SyntaxNode
Return targetToken.GetAncestor(Function(node) node.IsAsyncSupportedFunctionSyntax())
End Function

Protected Overrides Function GetTypeSymbolOfExpression(semanticModel As SemanticModel, potentialAwaitableExpression As SyntaxNode, cancellationToken As CancellationToken) As ITypeSymbol
Expand Down
Loading