From 437c7557d8726afa8fc047f7ff1a4a80b29b858f Mon Sep 17 00:00:00 2001 From: rameel Date: Fri, 20 Nov 2026 00:27:41 +0500 Subject: [PATCH] parser: throw ArgumentException when Evaluate cannot convert the result After parsing, Evaluate converted the result to object or TResult with Expression.Convert. When there was no such conversion, as for a call of a void method or for Evaluate("1"), Expression.Convert threw InvalidOperationException, although Evaluate reports an invalid expression with ArgumentException. Throw ArgumentException with a message like the C# error CS0030, such as "Cannot convert type 'System.Void' to 'System.Object'.", and mention this case in the XML comments of the Evaluate overloads. --- .../ExpressionParser.cs | 50 +++++++++++++++---- .../ExpressionParserTest.cs | 44 ++++++++++++++++ 2 files changed, 83 insertions(+), 11 deletions(-) diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.cs index f3d4e3f..d43ecf0 100644 --- a/src/Ramstack.ExpressionParser/ExpressionParser.cs +++ b/src/Ramstack.ExpressionParser/ExpressionParser.cs @@ -85,7 +85,8 @@ public static ParseResult Parse(ReadOnlySpan source, Expressio /// The evaluated result. /// /// - /// If the expression is invalid, an that describes the error is thrown. + /// If the expression is invalid or the type of its result cannot be converted to , + /// an that describes the error is thrown. /// public static object? Evaluate(ReadOnlySpan source) => Evaluate(source); @@ -100,7 +101,8 @@ public static ParseResult Parse(ReadOnlySpan source, Expressio /// /// /// The expression can access the members of the runtime type of . - /// If the expression is invalid, an that describes the error is thrown. + /// If the expression is invalid or the type of its result cannot be converted to , + /// an that describes the error is thrown. /// public static object? Evaluate(ReadOnlySpan source, object context) { @@ -119,7 +121,7 @@ public static ParseResult Parse(ReadOnlySpan 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 @@ -136,7 +138,8 @@ public static ParseResult Parse(ReadOnlySpan source, Expressio /// The evaluated result of type . /// /// - /// If the expression is invalid, an that describes the error is thrown. + /// If the expression is invalid or the type of its result cannot be converted to , + /// an that describes the error is thrown. /// public static TResult? Evaluate(ReadOnlySpan source) { @@ -147,9 +150,7 @@ public static ParseResult Parse(ReadOnlySpan 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>(e) @@ -169,7 +170,8 @@ public static ParseResult Parse(ReadOnlySpan source, Expressio /// /// The expression can access the members of , not of the runtime type /// of . Members declared only in a derived or implementing type are not available. - /// If the expression is invalid, an that describes the error is thrown. + /// If the expression is invalid or the type of its result cannot be converted to , + /// an that describes the error is thrown. /// public static TResult? Evaluate(ReadOnlySpan source, TContext context) where TContext : notnull { @@ -182,12 +184,38 @@ public static ParseResult Parse(ReadOnlySpan 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>(e, c) .Compile()(context); } + + /// + /// Converts the result of an expression to the specified type. + /// + /// The expression whose result to convert. + /// The type to convert the result to. + /// + /// The itself if its result needs no conversion; + /// otherwise, an expression that converts the result to . + /// + /// + /// The result is converted explicitly. If there is no such conversion, as for an expression + /// of type , an is thrown. + /// + 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}'."); + } + } } diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index 98b1fba..ce8b7b4 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -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 evaluate, string expected) + { + var exception = Assert.Throws(() => evaluate()); + + Assert.That(exception!.Message, Is.EqualTo(expected)); + } + + private static IEnumerable 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, void", + () => ExpressionParser.Evaluate(VoidCall), + "Cannot convert type 'System.Void' to 'System.Int32'."); + + yield return Case("Evaluate, no conversion", + () => ExpressionParser.Evaluate("1"), + "Cannot convert type 'System.Int32' to 'System.String'."); + + yield return Case("Evaluate, void", + () => ExpressionParser.Evaluate(VoidCall, context), + "Cannot convert type 'System.Void' to 'System.Object'."); + + yield return Case("Evaluate, no conversion", + () => ExpressionParser.Evaluate("Value", context), + "Cannot convert type 'System.Int32' to 'System.String'."); + + static TestCaseData Case(string name, Func evaluate, string expected) => + new TestCaseData(evaluate, expected).SetArgDisplayNames(name); + } + } + [TestCase("-1u", -1L)] [TestCase("-4294967295u", -4294967295L)] [TestCase("-3000000000", -3000000000L)]