Skip to content

Commit

Permalink
Fix deconstruct and fully qualified types in async foreach
Browse files Browse the repository at this point in the history
  • Loading branch information
GerardSmit committed Mar 22, 2024
1 parent 28761db commit 1b0b438
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Zomp.SyncMethodGenerator/AsyncToSyncRewriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1026,12 +1026,20 @@ bool ShouldRemoveArgumentLocal(ArgumentSyntax arg, int index)
var @base = (ForEachStatementSyntax)base.VisitForEachStatement(node)!;
if (TypeAlreadyQualified(node.Type))
{
return @base;
return @base.WithAwaitKeyword(default);
}

return @base.WithAwaitKeyword(default).WithType(ProcessType(node.Type)).WithTriviaFrom(@base);
}

/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
var @base = (ForEachVariableStatementSyntax)base.VisitForEachVariableStatement(node)!;

return @base.WithAwaitKeyword(default).WithTriviaFrom(@base);
}

public override SyntaxNode? VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node)
{
var @base = (ParenthesizedLambdaExpressionSyntax)base.VisitParenthesizedLambdaExpression(node)!;
Expand Down
39 changes: 39 additions & 0 deletions tests/Generator.Tests/ForEachTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
namespace Generator.Tests;

public class ForEachTests
{
[Fact]
public Task AsyncForEachQualified() => """
[CreateSyncVersion]
async Task<int> SumAsync(IAsyncEnumerable<int?> enumerable)
{
int sum = 0;
await foreach (int? i in enumerable)
{
if (i.HasValue)
{
sum += i.Value;
}
}
return sum;
}
""".Verify();

[Fact]
public Task AsyncForEachDeconstruct() => """
[CreateSyncVersion]
async Task<int> SumAsync(IAsyncEnumerable<(int a, int b)> enumerable)
{
int sum = 0;
await foreach (var (a, b) in enumerable)
{
sum += a + b;
}
return sum;
}
""".Verify();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//HintName: Test.Class.SumAsync.g.cs
int Sum(global::System.Collections.Generic.IEnumerable<(int a, int b)> enumerable)
{
int sum = 0;

foreach (var (a, b) in enumerable)
{
sum += a + b;
}

return sum;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//HintName: Test.Class.SumAsync.g.cs
int Sum(global::System.Collections.Generic.IEnumerable<int?> enumerable)
{
int sum = 0;

foreach (int? i in enumerable)
{
if (i.HasValue)
{
sum += i.Value;
}
}

return sum;
}

0 comments on commit 1b0b438

Please sign in to comment.