Skip to content
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
33 changes: 26 additions & 7 deletions CodeConverter/CSharp/CommonConversions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,25 @@ private CSSyntax.VariableDeclarationSyntax CreateVariableDeclaration(bool prefer
var requireExplicitType = requireExplicitTypeForAll ||
vbInitializerType != null && !SymbolEqualityComparer.IncludeNullability.Equals(declaredSymbolType, vbInitializerType);
bool useVar = equalsValueClauseSyntax != null && !preferExplicitType && !requireExplicitType;
var typeSyntax = initSymbol == null || !initSymbol.IsAnonymousFunction()
? GetTypeSyntax(declaredSymbolType, useVar)
: GetFuncTypeSyntax(declaredSymbolType, initSymbol);
var typeSyntax = initSymbol?.IsAnonymousFunction() == true && !IsNamedDelegateOrExpressionOfOne(declaredSymbolType)
? GetFuncTypeSyntax(declaredSymbolType, initSymbol)
: GetTypeSyntax(declaredSymbolType, useVar);
return SyntaxFactory.VariableDeclaration(typeSyntax, SyntaxFactory.SingletonSeparatedList(v));
}

/// <summary>
/// A lambda's own signature can differ from the declared delegate type, e.g. VB's relaxed delegate conversion allows <c>Dim a As Action(Of Integer) = Sub() ...</c>.
/// Only VB's anonymous delegate types (which can't be named in C#) need replacing with an equivalent Action/Func.
/// </summary>
private bool IsNamedDelegateOrExpressionOfOne(ITypeSymbol declaredSymbolType)
{
return UnwrapLinqDelegateExpression(declaredSymbolType).IsDelegateReferencableByName();
}

/// <returns>The delegate type T for Expression(Of T), otherwise the type itself</returns>
public ITypeSymbol UnwrapLinqDelegateExpression(ITypeSymbol type) =>
IsLinqDelegateExpression(type) ? ((INamedTypeSymbol)type).TypeArguments.Single() : type;

public TypeSyntax GetFuncTypeSyntax(ITypeSymbol declaredSymbolType, IMethodSymbol method)
{
var funcTypeSyntax = GetDelegateSyntax();
Expand Down Expand Up @@ -760,13 +773,19 @@ public ISymbol GetCsOriginalSymbolOrNull(ISymbol symbol)

public static ExpressionSyntax ThrowawayParameters(ExpressionSyntax invocable, int paramCount)
{
var names = Enumerable.Range(1, paramCount).Select(i =>
new string(Enumerable.Repeat('_', i).ToArray())
).ToArray();
var parameters = CreateParameterList(names.Select(n => SyntaxFactory.Parameter(SyntaxFactory.Identifier(n))));
var parameters = CreateThrowawayParameterList(paramCount);
return SyntaxFactory.ParenthesizedLambdaExpression(parameters, SyntaxFactory.InvocationExpression(invocable));
}

/// <summary>
/// Parameters named _, __, ___, etc. for when VB allows the parameters of a delegate to be omitted, but C# requires them to be declared
/// </summary>
public static CSSyntax.ParameterListSyntax CreateThrowawayParameterList(int paramCount)
{
var names = Enumerable.Range(1, paramCount).Select(i => new string('_', i));
return CreateParameterList(names.Select(n => SyntaxFactory.Parameter(SyntaxFactory.Identifier(n))));
}

public static CSSyntax.ParameterListSyntax CreateParameterList(IEnumerable<SyntaxNode> ps)
{
return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(ps.Cast<CSSyntax.ParameterSyntax>()));
Expand Down
14 changes: 14 additions & 0 deletions CodeConverter/CSharp/LambdaConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ public async Task<CSharpSyntaxNode> ConvertAsync(VBSyntax.LambdaExpressionSyntax
}

var body = (CSharpSyntaxNode)block ?? expressionBody;
param = WithParametersOmittedByRelaxation(vbNode, param);
var isAnonAsync = _semanticModel.GetOperation(vbNode) is IAnonymousFunctionOperation a && a.Symbol.IsAsync;

var asyncKeyword = SyntaxFactory.Token(SyntaxKind.AsyncKeyword);
Expand All @@ -119,6 +120,19 @@ public async Task<CSharpSyntaxNode> ConvertAsync(VBSyntax.LambdaExpressionSyntax
}


/// <summary>
/// VB's relaxed delegate conversion allows a lambda with no parameters to be converted to a delegate type that has parameters
/// (e.g. <c>Sub() ...</c> to <c>Action(Of T)</c>), whereas C# requires a lambda to declare every parameter of its delegate type.
/// </summary>
/// <remarks>https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/delegates/relaxed-delegate-conversion</remarks>
private ParameterListSyntax WithParametersOmittedByRelaxation(VBSyntax.LambdaExpressionSyntax vbNode, ParameterListSyntax param)
{
if (param.Parameters.Any()) return param;
var delegateType = CommonConversions.UnwrapLinqDelegateExpression(_semanticModel.GetTypeInfo(vbNode).ConvertedType);
var targetParameterCount = delegateType?.GetDelegateInvokeMethod()?.Parameters.Length ?? 0;
return targetParameterCount > 0 ? CommonConversions.CreateThrowawayParameterList(targetParameterCount).WithTriviaFrom(param) : param;
}

private async Task<CSharpSyntaxNode> ConvertToFunctionDeclarationOrNullAsync(VBSyntax.LambdaExpressionSyntax vbNode,
ParameterListSyntax param, BlockSyntax block,
ArrowExpressionClauseSyntax arrow)
Expand Down
42 changes: 42 additions & 0 deletions Tests/CSharp/ExpressionTests/ExpressionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,48 @@ private void TestMethod()
}");
}

[Fact]
public async Task Issue783_LambdaWithOmittedParametersAsync()
{
await TestConversionVisualBasicToCSharpAsync(@"Imports System

Class TestClass
Private Sub ShowPopup(x As Integer, Optional onClose As Action(Of TestClass) = Nothing)
End Sub

Private Sub TestMethod()
ShowPopup(8, Sub()
'Comment
Console.WriteLine(1)
End Sub)
Dim singleLine As Action(Of Integer) = Sub() Console.WriteLine(2)
Dim twoParams As Action(Of Integer, String) = Sub() Console.WriteLine(3)
Dim func As Func(Of Integer, Integer) = Function() 4
Dim handler As EventHandler = Sub() Console.WriteLine(5)
End Sub
End Class", @"using System;

internal partial class TestClass
{
private void ShowPopup(int x, Action<TestClass> onClose = null)
{
}

private void TestMethod()
{
ShowPopup(8, _ =>
{
// Comment
Console.WriteLine(1);
});
Action<int> singleLine = _ => Console.WriteLine(2);
Action<int, string> twoParams = (_, __) => Console.WriteLine(3);
Func<int, int> func = _ => 4;
EventHandler handler = (_, __) => Console.WriteLine(5);
}
}");
}

[Fact]
public async Task AnonymousLambdaArrayTypeConversionAsync()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Imports System
Imports System.Linq.Expressions
Imports Xunit

Public Class RelaxedDelegateConversionTests
Private _log As String = ""

Private Sub Invoke(Of T)(value As T, Optional callback As Action(Of T) = Nothing)
callback(value)
End Sub

<Fact>
Public Sub SubWithOmittedParameterIsCalled()
Invoke(1, Sub()
_log &= "called"
End Sub)
Assert.Equal("called", _log)
End Sub

<Fact>
Public Sub OmittedParametersOfNamedDelegates()
Dim twoParams As Action(Of Integer, String) = Sub() _log &= "two"
twoParams(1, "a")
Dim handler As EventHandler = Sub() _log &= ",handler"
handler(Me, EventArgs.Empty)
Dim func As Func(Of Integer, Integer) = Function() 4
Assert.Equal("two,handler", _log)
Assert.Equal(4, func(3))
End Sub

<Fact>
Public Sub OmittedParameterOfExpressionTree()
Dim expr As Expression(Of Func(Of Integer, Integer)) = Function() 5
Assert.Equal(5, expr.Compile()(3))
End Sub
End Class
Loading