Skip to content

Commit

Permalink
No longer omit the conversion expression when the return type is expl…
Browse files Browse the repository at this point in the history
…icitly object.

Force the return type of a lambda expression to typeof(void) to prevent the emission of a conversion expresssion.
Fixes dynamicexpresso#185
  • Loading branch information
metoule committed Nov 14, 2021
1 parent 7e172a1 commit 803e1ee
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/DynamicExpresso.Core/Interpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,16 @@ public Expression<TDelegate> ParseAsExpression<TDelegate>(string expressionText,

internal LambdaExpression ParseAsExpression(Type delegateType, string expressionText, params string[] parametersNames)
{
var lambda = ParseAs(delegateType, expressionText, parametersNames);
var delegateInfo = ReflectionExtensions.GetDelegateInfo(delegateType, parametersNames);

// return type is object means that we have no information beforehand
// => we force it to typeof(void) so that no conversion expression is emitted by the parser
// and the actual expression type is preserved
var returnType = delegateInfo.ReturnType;
if (returnType == typeof(object))
returnType = typeof(void);

var lambda = ParseAsLambda(expressionText, returnType, delegateInfo.Parameters);
return lambda.LambdaExpression(delegateType);
}

Expand Down
2 changes: 1 addition & 1 deletion src/DynamicExpresso.Core/Parsing/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private Expression ParseExpressionSegment(Type returnType)
int errorPos = _token.pos;
var expression = ParseExpressionSegment();

if (returnType != typeof(void) && returnType != typeof(object))
if (returnType != typeof(void))
{
return GenerateConversion(expression, returnType, errorPos);
}
Expand Down
12 changes: 12 additions & 0 deletions test/DynamicExpresso.UnitTest/GithubIssues.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,5 +344,17 @@ public void GitHub_Issue_169_quatro()
result = interpreter.Eval<string>("x?.ToString()");
Assert.AreEqual("56", result);
}

[Test]
public void GitHub_Issue_185()
{
var interpreter = new Interpreter().SetVariable("a", 123L);

// forcing the return type to object should work
// (ie a conversion expression should be emitted from long to object)
var del = interpreter.ParseAsDelegate<Func<object>>("a*2");
var result = del();
Assert.AreEqual(246, result);
}
}
}

0 comments on commit 803e1ee

Please sign in to comment.