diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index b5135bb26..9f5fe1dcf 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -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)); } + /// + /// A lambda's own signature can differ from the declared delegate type, e.g. VB's relaxed delegate conversion allows Dim a As Action(Of Integer) = Sub() .... + /// Only VB's anonymous delegate types (which can't be named in C#) need replacing with an equivalent Action/Func. + /// + private bool IsNamedDelegateOrExpressionOfOne(ITypeSymbol declaredSymbolType) + { + return UnwrapLinqDelegateExpression(declaredSymbolType).IsDelegateReferencableByName(); + } + + /// The delegate type T for Expression(Of T), otherwise the type itself + public ITypeSymbol UnwrapLinqDelegateExpression(ITypeSymbol type) => + IsLinqDelegateExpression(type) ? ((INamedTypeSymbol)type).TypeArguments.Single() : type; + public TypeSyntax GetFuncTypeSyntax(ITypeSymbol declaredSymbolType, IMethodSymbol method) { var funcTypeSyntax = GetDelegateSyntax(); @@ -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)); } + /// + /// Parameters named _, __, ___, etc. for when VB allows the parameters of a delegate to be omitted, but C# requires them to be declared + /// + 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 ps) { return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(ps.Cast())); diff --git a/CodeConverter/CSharp/LambdaConverter.cs b/CodeConverter/CSharp/LambdaConverter.cs index c0f0838b3..bf75a7a3d 100644 --- a/CodeConverter/CSharp/LambdaConverter.cs +++ b/CodeConverter/CSharp/LambdaConverter.cs @@ -103,6 +103,7 @@ public async Task 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); @@ -119,6 +120,19 @@ public async Task ConvertAsync(VBSyntax.LambdaExpressionSyntax } + /// + /// VB's relaxed delegate conversion allows a lambda with no parameters to be converted to a delegate type that has parameters + /// (e.g. Sub() ... to Action(Of T)), whereas C# requires a lambda to declare every parameter of its delegate type. + /// + /// https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/delegates/relaxed-delegate-conversion + 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 ConvertToFunctionDeclarationOrNullAsync(VBSyntax.LambdaExpressionSyntax vbNode, ParameterListSyntax param, BlockSyntax block, ArrowExpressionClauseSyntax arrow) diff --git a/Tests/CSharp/ExpressionTests/ExpressionTests.cs b/Tests/CSharp/ExpressionTests/ExpressionTests.cs index 859f63418..607250e0f 100644 --- a/Tests/CSharp/ExpressionTests/ExpressionTests.cs +++ b/Tests/CSharp/ExpressionTests/ExpressionTests.cs @@ -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 onClose = null) + { + } + + private void TestMethod() + { + ShowPopup(8, _ => + { + // Comment + Console.WriteLine(1); + }); + Action singleLine = _ => Console.WriteLine(2); + Action twoParams = (_, __) => Console.WriteLine(3); + Func func = _ => 4; + EventHandler handler = (_, __) => Console.WriteLine(5); + } +}"); + } + [Fact] public async Task AnonymousLambdaArrayTypeConversionAsync() { diff --git a/Tests/TestData/SelfVerifyingTests/VBToCS/RelaxedDelegateConversionTests.vb b/Tests/TestData/SelfVerifyingTests/VBToCS/RelaxedDelegateConversionTests.vb new file mode 100644 index 000000000..788118ae7 --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/VBToCS/RelaxedDelegateConversionTests.vb @@ -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 + + + Public Sub SubWithOmittedParameterIsCalled() + Invoke(1, Sub() + _log &= "called" + End Sub) + Assert.Equal("called", _log) + End Sub + + + 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 + + + Public Sub OmittedParameterOfExpressionTree() + Dim expr As Expression(Of Func(Of Integer, Integer)) = Function() 5 + Assert.Equal(5, expr.Compile()(3)) + End Sub +End Class