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
50 changes: 39 additions & 11 deletions src/Ramstack.ExpressionParser/ExpressionParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
/// The evaluated result.
/// </returns>
/// <remarks>
/// If the expression is invalid, an <see cref="ArgumentException" /> that describes the error is thrown.
/// If the expression is invalid or the type of its result cannot be converted to <see cref="object" />,
/// an <see cref="ArgumentException" /> that describes the error is thrown.
/// </remarks>
public static object? Evaluate(ReadOnlySpan<char> source) =>
Evaluate<object>(source);
Expand All @@ -100,7 +101,8 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
/// </returns>
/// <remarks>
/// The expression can access the members of the runtime type of <paramref name="context" />.
/// If the expression is invalid, an <see cref="ArgumentException" /> that describes the error is thrown.
/// If the expression is invalid or the type of its result cannot be converted to <see cref="object" />,
/// an <see cref="ArgumentException" /> that describes the error is thrown.
/// </remarks>
public static object? Evaluate(ReadOnlySpan<char> source, object context)
{
Expand All @@ -119,7 +121,7 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
expressions:
[
Expression.Assign(c, Expression.Convert(p, context.GetType())),
r.Value.Type.IsClass ? r.Value : Expression.Convert(r.Value, typeof(object))
ConvertResult(r.Value, typeof(object))
]);

return Expression
Expand All @@ -136,7 +138,8 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
/// The evaluated result of type <typeparamref name="TResult" />.
/// </returns>
/// <remarks>
/// If the expression is invalid, an <see cref="ArgumentException" /> that describes the error is thrown.
/// If the expression is invalid or the type of its result cannot be converted to <typeparamref name="TResult" />,
/// an <see cref="ArgumentException" /> that describes the error is thrown.
/// </remarks>
public static TResult? Evaluate<TResult>(ReadOnlySpan<char> source)
{
Expand All @@ -147,9 +150,7 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
if (r.Value is null)
return default;

var e = r.Value;
if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type)))
e = Expression.Convert(e, typeof(TResult));
var e = ConvertResult(r.Value, typeof(TResult));

return Expression
.Lambda<Func<TResult?>>(e)
Expand All @@ -169,7 +170,8 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
/// <remarks>
/// The expression can access the members of <typeparamref name="TContext" />, not of the runtime type
/// of <paramref name="context" />. Members declared only in a derived or implementing type are not available.
/// If the expression is invalid, an <see cref="ArgumentException" /> that describes the error is thrown.
/// If the expression is invalid or the type of its result cannot be converted to <typeparamref name="TResult" />,
/// an <see cref="ArgumentException" /> that describes the error is thrown.
/// </remarks>
public static TResult? Evaluate<TContext, TResult>(ReadOnlySpan<char> source, TContext context) where TContext : notnull
{
Expand All @@ -182,12 +184,38 @@ public static ParseResult<Expression> Parse(ReadOnlySpan<char> source, Expressio
if (r.Value is null)
return default;

var e = r.Value;
if (e.Type != typeof(TResult) && (!e.Type.IsClass || !typeof(TResult).IsAssignableFrom(e.Type)))
e = Expression.Convert(e, typeof(TResult));
var e = ConvertResult(r.Value, typeof(TResult));

return Expression
.Lambda<Func<TContext, TResult?>>(e, c)
.Compile()(context);
}

/// <summary>
/// Converts the result of an expression to the specified type.
/// </summary>
/// <param name="expression">The expression whose result to convert.</param>
/// <param name="type">The type to convert the result to.</param>
/// <returns>
/// The <paramref name="expression" /> itself if its result needs no conversion;
/// otherwise, an expression that converts the result to <paramref name="type" />.
/// </returns>
/// <remarks>
/// The result is converted explicitly. If there is no such conversion, as for an expression
/// of type <see langword="void" />, an <see cref="ArgumentException" /> is thrown.
/// </remarks>
private static Expression ConvertResult(Expression expression, Type type)
{
if (expression.Type == type || expression.Type.IsClass && type.IsAssignableFrom(expression.Type))
return expression;

try
{
return Expression.Convert(expression, type);
}
catch (InvalidOperationException)
{
throw new ArgumentException($"Cannot convert type '{expression.Type}' to '{type}'.");
}
}
}
44 changes: 44 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,50 @@ public void Evaluate_MemberOfRuntimeContextTypeOnly_Throws()
Assert.That(exception!.Message, Is.EqualTo("Cannot resolve symbol 'Extra'."));
}

[TestCaseSource(nameof(InconvertibleResultSource))]
public void Evaluate_ResultNotConvertibleToResultType_ThrowsArgumentException(Func<object?> evaluate, string expected)
{
var exception = Assert.Throws<ArgumentException>(() => evaluate());

Assert.That(exception!.Message, Is.EqualTo(expected));
}

private static IEnumerable<TestCaseData> InconvertibleResultSource
{
get
{
const string VoidCall = "TimeZoneInfo.ClearCachedData()";
var context = new ValueContext();

yield return Case("Evaluate, void",
() => ExpressionParser.Evaluate(VoidCall),
"Cannot convert type 'System.Void' to 'System.Object'.");

yield return Case("Evaluate with context, void",
() => ExpressionParser.Evaluate(VoidCall, context),
"Cannot convert type 'System.Void' to 'System.Object'.");

yield return Case("Evaluate<TResult>, void",
() => ExpressionParser.Evaluate<int>(VoidCall),
"Cannot convert type 'System.Void' to 'System.Int32'.");

yield return Case("Evaluate<TResult>, no conversion",
() => ExpressionParser.Evaluate<string>("1"),
"Cannot convert type 'System.Int32' to 'System.String'.");

yield return Case("Evaluate<TContext, TResult>, void",
() => ExpressionParser.Evaluate<IValueContext, object>(VoidCall, context),
"Cannot convert type 'System.Void' to 'System.Object'.");

yield return Case("Evaluate<TContext, TResult>, no conversion",
() => ExpressionParser.Evaluate<IValueContext, string>("Value", context),
"Cannot convert type 'System.Int32' to 'System.String'.");

static TestCaseData Case(string name, Func<object?> evaluate, string expected) =>
new TestCaseData(evaluate, expected).SetArgDisplayNames(name);
}
}

[TestCase("-1u", -1L)]
[TestCase("-4294967295u", -4294967295L)]
[TestCase("-3000000000", -3000000000L)]
Expand Down