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

Rm "async" anywhere from IAsyncEnumerable & methods returning it #905

Merged
merged 15 commits into from
Aug 9, 2023
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 @@ -16,6 +16,8 @@ CancellationToken token
private bool m_disableTaskRunWarningFlag;
// Need to modify return statement later on if function returns Task -> Void to prevent CS0127 (A method with a void return type cannot return a value)
private bool m_generatedFunctionReturnsVoid;
// Need to remove async not anywhere (not just suffix) in certain cases
private bool m_removeAsyncAnywhere;

public TransformResult<MethodDeclarationSyntax> Transform( MethodDeclarationSyntax decl ) {
// TODO: remove CancellationToken parameters
Expand Down Expand Up @@ -73,6 +75,13 @@ private static SyntaxTokenList RemoveAsyncModifier( SyntaxTokenList modifiers )
);

private SyntaxToken RemoveAsyncSuffix( SyntaxToken ident, bool optional = false ) {
if( m_removeAsyncAnywhere && ident.ValueText.Contains( "Async" ) ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this check optional?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so, because there are cases where a function may return IAsyncEnumerable and not end in Async and we want the sync generator to transform it without a diagnostic

m_removeAsyncAnywhere = false;
return SyntaxFactory.Identifier(
ident.ValueText.Replace( "Async", "" )
).WithTriviaFrom( ident );
}

if( !ident.ValueText.EndsWith( "Async", StringComparison.Ordinal ) || ident.ValueText == "Async" ) {
if( optional ) {
return ident;
Expand Down Expand Up @@ -123,6 +132,10 @@ private TypeSyntax TransformType( TypeSyntax typeSynt, bool isReturnType = false
);
return typeSynt;
}
} else if( returnTypeInfo.Type.MetadataName == "IAsyncEnumerable`1" && returnTypeInfo.Type.ContainingNamespace.ToString() == "System.Collections.Generic" ) {
return ( (GenericNameSyntax)typeSynt )
.WithIdentifier( SyntaxFactory.Identifier( "IEnumerable" ) )
.WithTriviaFrom( typeSynt );
}

if( isReturnType ) { ReportDiagnostic( Diagnostics.NonTaskReturnType, typeSynt.GetLocation() ); }
Expand Down Expand Up @@ -338,22 +351,33 @@ private StatementSyntax Transform( ExpressionStatementSyntax exprStmt ) {
}

private ExpressionSyntax Transform( InvocationExpressionSyntax invocationExpr) {
ITypeSymbol? returnTypeInfo = Model.GetTypeInfo( invocationExpr ).Type;

bool prevRemoveAsyncAnywhereState = m_removeAsyncAnywhere;
if( returnTypeInfo?.MetadataName == "IAsyncEnumerable`1" && returnTypeInfo.ContainingNamespace.ToString() == "System.Collections.Generic" ) {
m_removeAsyncAnywhere = true;
AnaCoda marked this conversation as resolved.
Show resolved Hide resolved
}

ExpressionSyntax newExpr = invocationExpr;
var memberAccess = invocationExpr.Expression as MemberAccessExpressionSyntax;

if( memberAccess is not null && ShouldRemoveInvocation( memberAccess ) ) {
if( memberAccess?.Expression is not null ) {
newExpr = memberAccess.Expression;
return Transform( newExpr );
try {
if( memberAccess is not null && ShouldRemoveInvocation( memberAccess ) ) {
if( memberAccess?.Expression is not null ) {
newExpr = memberAccess.Expression;
return Transform( newExpr );
}
} else if( memberAccess is not null && ShouldWrapMemberAccessInTaskRun( memberAccess ) ) {
m_disableTaskRunWarningFlag = true;
return SyntaxFactory.ParseExpression( $"Task.Run(() => {invocationExpr}).Result" );
}
} else if( memberAccess is not null && ShouldWrapMemberAccessInTaskRun( memberAccess ) ) {
m_disableTaskRunWarningFlag = true;
return SyntaxFactory.ParseExpression( $"Task.Run(() => {invocationExpr}).Result" );
}

return invocationExpr
.WithExpression( Transform( invocationExpr.Expression ) )
.WithArgumentList( TransformAll( invocationExpr.ArgumentList, Transform ) );
return invocationExpr = invocationExpr
.WithExpression( Transform( invocationExpr.Expression ) )
.WithArgumentList( TransformAll( invocationExpr.ArgumentList, Transform ) ); ;
} finally {
m_removeAsyncAnywhere = prevRemoveAsyncAnywhereState;
}
}

bool ShouldRemoveReturnedMemberAccess( MemberAccessExpressionSyntax memberAccessExpr ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,35 @@ public void CancellationTokenVariableArgument() {
}

[Test]
public void IAsyncEnumerable() {
var actual = TransformWithIAsyncEnumerable( @"[GenerateSync] async Task BarAsync() { IAsyncEnumerable<string> m_enum = MethodReturningIAsyncEnumerable(); }" );

Assert.IsTrue( actual.Success );
Assert.IsEmpty( actual.Diagnostics );
Assert.AreEqual( @"[Blocking] void Bar() { IEnumerable<string> m_enum = MethodReturningIEnumerable(); }", actual.Value.ToFullString() );
}

AnaCoda marked this conversation as resolved.
Show resolved Hide resolved
[Test]
public void IAsyncEnumerable_WithParameterContainingAsyncInName() {
var actual = TransformWithIAsyncEnumerable( @"
[GenerateSync] async Task BarAsync() {
int parameterWithAsyncInName = 0;
IAsyncEnumerable<string> m_enum = MethodReturningIAsyncEnumerable( parameterWithAsyncInName );
}"
);

Assert.IsTrue( actual.Success );
Assert.IsEmpty( actual.Diagnostics );
Assert.AreEqual( @"
[Blocking] void Bar() {
int parameterWithAsyncInName = 0;
IEnumerable<string> m_enum = MethodReturningIEnumerable( parameterWithAsyncInName );
}",
actual.Value.ToFullString()
);
}

[Test]
public void ParenthesizedAnonymousCreationLambda() {
var actual = Transform( @"[GenerateSync] async Task BarAsync() { await BazAsync(() => new { BazAsync = 5, Quux = ""test"" } ); }" );

Expand Down Expand Up @@ -506,11 +535,22 @@ public static TransformResult<MethodDeclarationSyntax> Transform( string methodS
return transformer.Transform( methodDecl );
}

public static TransformResult<MethodDeclarationSyntax> TransformWithIAsyncEnumerable( string methodSource ) {
var (compilation, methodDecl) = ParseMethodWithIAsyncEnumerable( methodSource );

var transformer = new AsyncToSyncMethodTransformer(
compilation.GetSemanticModel( methodDecl.SyntaxTree ),
CancellationToken.None
);

return transformer.Transform( methodDecl );
}

public static (Compilation, MethodDeclarationSyntax) ParseMethod( string methodSource ) {
var wrappedAndParsed = CSharpSyntaxTree.ParseText( @$"
using System.Threading.Tasks;
using D2L.CodeStyle.Annotations;
using System.Threading;
using D2L.CodeStyle.Annotations;

class TestType{{{methodSource}}}" );

Expand All @@ -521,6 +561,28 @@ class TestType{{{methodSource}}}" );
return (compilation, methodDecl);
}


public static (Compilation, MethodDeclarationSyntax) ParseMethodWithIAsyncEnumerable( string methodSource ) {
var wrappedAndParsed = CSharpSyntaxTree.ParseText( @$"
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using D2L.CodeStyle.Annotations;

class TestType{{
{methodSource}async IAsyncEnumerable<string> MethodReturningIAsyncEnumerable( int p = 0 ) {{
await Task.Delay(1000);
yield return ""test"";
}}
}}" );

var methodDecl = wrappedAndParsed.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();

var compilation = CreateSyncGeneratorTestCompilation( wrappedAndParsed );

return (compilation, methodDecl);
}

internal static Compilation CreateSyncGeneratorTestCompilation( params SyntaxTree[] trees )
=> CSharpCompilation.Create(
assemblyName: "test",
Expand All @@ -539,7 +601,8 @@ internal static Compilation CreateSyncGeneratorTestCompilation( params SyntaxTre

typeof( object ),
typeof( Task ),
typeof( GenerateSyncAttribute )
typeof( GenerateSyncAttribute ),
typeof( IAsyncEnumerable<object> )

}.Select( t => t.Assembly.Location )
.Distinct()
Expand Down
Loading