From ea598446b8a86113f02c909f6bf6b3843c921962 Mon Sep 17 00:00:00 2001 From: rameel Date: Tue, 17 Nov 2026 22:27:08 +0500 Subject: [PATCH 1/2] parser: allow implicit conversions to decimal and reject them to enums CanConvertPrimitive used the widening rules of the reflection binder, which do not convert integer types and char to decimal. It also took an enum target for its underlying type, so it reported that any number converts to any enum. Allow the implicit conversions to decimal and reject conversions to an enum. The method resolver uses the table only for primitive parameter types, and decimal and enums are not primitive, so overload resolution does not change. --- .../Internal/TypeUtils.cs | 24 ++++++++------ .../TypeUtilsTest.cs | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 tests/Ramstack.ExpressionParser.Tests/TypeUtilsTest.cs diff --git a/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs b/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs index 93772d1..3a2a10c 100644 --- a/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs +++ b/src/Ramstack.ExpressionParser/Internal/TypeUtils.cs @@ -13,15 +13,15 @@ public static class TypeUtils /* Object */ 0, /* DBNull */ 0, /* Boolean */ Primitives.Boolean, - /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, - /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, - /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, + /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double | Primitives.Decimal, + /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double | Primitives.Decimal, /* Single */ Primitives.Single | Primitives.Double, /* Double */ Primitives.Double, /* Decimal */ Primitives.Decimal, @@ -114,7 +114,11 @@ public static bool IsInteger(Type type) /// public static bool CanConvertPrimitive(Type source, Type target) { - if (source.IsEnum) + // + // Type.GetTypeCode returns the code of the underlying type for an enum, + // so without this check a number would convert to any enum and back. + // + if (source.IsEnum || target.IsEnum) return false; if ((source == typeof(IntPtr) && target == typeof(IntPtr)) diff --git a/tests/Ramstack.ExpressionParser.Tests/TypeUtilsTest.cs b/tests/Ramstack.ExpressionParser.Tests/TypeUtilsTest.cs new file mode 100644 index 0000000..5dca8b9 --- /dev/null +++ b/tests/Ramstack.ExpressionParser.Tests/TypeUtilsTest.cs @@ -0,0 +1,33 @@ +using Ramstack.Parsing.Internal; + +namespace Ramstack.Parsing; + +[TestFixture] +public class TypeUtilsTest +{ + [TestCase(typeof(char))] + [TestCase(typeof(sbyte))] + [TestCase(typeof(byte))] + [TestCase(typeof(short))] + [TestCase(typeof(ushort))] + [TestCase(typeof(int))] + [TestCase(typeof(uint))] + [TestCase(typeof(long))] + [TestCase(typeof(ulong))] + public void CanConvertPrimitive_IntegerToDecimal_ReturnsTrue(Type source) => + Assert.That(TypeUtils.CanConvertPrimitive(source, typeof(decimal)), Is.True); + + [TestCase(typeof(float), typeof(decimal))] + [TestCase(typeof(double), typeof(decimal))] + [TestCase(typeof(decimal), typeof(float))] + [TestCase(typeof(decimal), typeof(double))] + [TestCase(typeof(decimal), typeof(int))] + public void CanConvertPrimitive_ExplicitDecimalConversion_ReturnsFalse(Type source, Type target) => + Assert.That(TypeUtils.CanConvertPrimitive(source, target), Is.False); + + [TestCase(typeof(int), typeof(DayOfWeek))] + [TestCase(typeof(DayOfWeek), typeof(int))] + [TestCase(typeof(DayOfWeek), typeof(DayOfWeek))] + public void CanConvertPrimitive_Enum_ReturnsFalse(Type source, Type target) => + Assert.That(TypeUtils.CanConvertPrimitive(source, target), Is.False); +} From e05086b030ad0ba82e1fb6b7d43717283f16a20a Mon Sep 17 00:00:00 2001 From: rameel Date: Tue, 17 Nov 2026 22:31:24 +0500 Subject: [PATCH 2/2] parser: convert conditional branches to their common type The branches of a conditional expression were passed to Expression.Condition as they were, so branches of different types, as in 'flag ? 1 : 2.0' or 'flag ? name : null', failed with "Argument types do not match". Convert one branch to the type of the other when only one of them converts implicitly, as C# does. The common type is always the type of a branch, so the result is object only when a branch is of that type. The null literal takes the type of the other branch if that type accepts null, and 'flag ? null : null' now fails because neither branch has a type. Branches without a common type fail with an error that names both types. --- .../ExpressionBuilder.Helpers.cs | 93 +++++++++++++++++++ .../ExpressionBuilder.cs | 3 +- .../Internal/Error.cs | 13 +++ .../Data/Errors.txt | 33 +++++++ .../Data/Expressions.txt | 34 ++++++- 5 files changed, 173 insertions(+), 3 deletions(-) diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs index d14d93b..12e2b74 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs @@ -52,6 +52,99 @@ private object ResolveSymbol(Expr.Reference expr) return null; } + /// + /// Converts the branches of a conditional expression to their common type. + /// + /// + /// As in C#, the common type is the type of one of the branches, so it is only + /// when a branch is of that type, for example after an explicit conversion. The null literal takes the type + /// of the other branch if that type accepts . + /// + /// The conditional expression. + /// The expression of the true branch. + /// The expression of the false branch. + /// + /// The common type of the branches. + /// + private static Type ApplyConditionalConversions(Expr.Conditional expr, ref Expression ifTrue, ref Expression ifFalse) + { + var isTrueNull = IsNullLiteral(expr.IfTrue); + var isFalseNull = IsNullLiteral(expr.IfFalse); + + if (isTrueNull || isFalseNull) + { + if (!isFalseNull && CanBeNull(ifFalse.Type)) + { + ifTrue = Expression.Constant(null, ifFalse.Type); + return ifFalse.Type; + } + + if (!isTrueNull && CanBeNull(ifTrue.Type)) + { + ifFalse = Expression.Constant(null, ifTrue.Type); + return ifTrue.Type; + } + + Error.NonApplicableConditionalOperator( + isTrueNull ? null : ifTrue.Type, + isFalseNull ? null : ifFalse.Type); + } + + if (ifTrue.Type == ifFalse.Type) + return ifTrue.Type; + + var trueToFalse = ApplyBranchConversion(ifTrue, ifFalse.Type); + var falseToTrue = ApplyBranchConversion(ifFalse, ifTrue.Type); + + if (trueToFalse is not null && falseToTrue is null) + { + ifTrue = trueToFalse; + return ifFalse.Type; + } + + if (falseToTrue is not null && trueToFalse is null) + { + ifFalse = falseToTrue; + return ifTrue.Type; + } + + Error.NonApplicableConditionalOperator(ifTrue.Type, ifFalse.Type); + return null!; + + static bool IsNullLiteral(Expr expr) + { + while (expr is Expr.Parenthesized parenthesized) + expr = parenthesized.Expression; + + return expr is Expr.Literal { Value: null }; + } + + static bool CanBeNull(Type type) => + !type.IsValueType || type.IsNullable(); + } + + /// + /// Applies an implicit conversion of a branch of a conditional expression to the type of the other branch. + /// + /// The expression of the branch. + /// The type of the other branch. + /// + /// The converted expression, or if no implicit conversion exists. + /// + private static Expression? ApplyBranchConversion(Expression expression, Type conversionType) + { + // + // ApplyImplicitConversion does not box values, so handle the boxing conversion here, + // for example of a number to a branch explicitly converted to object. + // + if (expression.Type.IsValueType + && !conversionType.IsValueType + && conversionType.IsAssignableFrom(expression.Type)) + return Expression.Convert(expression, conversionType); + + return ApplyImplicitConversion(expression, conversionType); + } + private static List CreateInjectingArguments(MethodInfo method, IReadOnlyList args) { var parameters = method.GetParameters(); diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs index 0f17bb6..135b2b9 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs @@ -481,7 +481,8 @@ protected internal override Expression VisitConditional(Expr.Conditional expr) if (condition is null) Error.MissingImplicitConversion(test.Type, typeof(bool)); - return Expression.Condition(condition, ifTrue, ifFalse); + var type = ApplyConditionalConversions(expr, ref ifTrue, ref ifFalse); + return Expression.Condition(condition, ifTrue, ifFalse, type); } catch (Exception e) when (e is not ParseErrorException) { diff --git a/src/Ramstack.ExpressionParser/Internal/Error.cs b/src/Ramstack.ExpressionParser/Internal/Error.cs index 91ed1b7..0e0f43e 100644 --- a/src/Ramstack.ExpressionParser/Internal/Error.cs +++ b/src/Ramstack.ExpressionParser/Internal/Error.cs @@ -64,6 +64,19 @@ public static void NonApplicableBinaryOperator(Identifier op, Type left, Type ri throw new ParseErrorException(message); } + /// + /// Throws a indicating the conditional operator cannot be applied to its branches + /// because they have no common type. + /// + /// The of the true branch, or for the null literal. + /// The of the false branch, or for the null literal. + [DoesNotReturn] + public static void NonApplicableConditionalOperator(Type? ifTrue, Type? ifFalse) + { + var message = $"Operator '?:' cannot be applied to operands of type '{ifTrue?.ToString() ?? ""}' and '{ifFalse?.ToString() ?? ""}'."; + throw new ParseErrorException(message); + } + /// /// Throws a indicating an implicit type conversion is not possible. /// diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt index c298fc6..6fd9939 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt @@ -151,3 +151,36 @@ Unary operator '!' cannot be applied to operand of type 'System.Byte'. !DayOfWeek.Friday Unary operator '!' cannot be applied to operand of type 'System.DayOfWeek'. + +####################################### +# Conditional operator branches without a common type + +true ? 1.0 : 2m +Operator '?:' cannot be applied to operands of type 'System.Double' and 'System.Decimal'. + +true ? 1 : 1ul +Operator '?:' cannot be applied to operands of type 'System.Int32' and 'System.UInt64'. + +true ? 1 : 1u +Operator '?:' cannot be applied to operands of type 'System.Int32' and 'System.UInt32'. + +true ? 1 : "a" +Operator '?:' cannot be applied to operands of type 'System.Int32' and 'System.String'. + +true ? "a" : Version.Parse("1.0") +Operator '?:' cannot be applied to operands of type 'System.String' and 'System.Version'. + +true ? Guid.Empty : DateTime.MinValue +Operator '?:' cannot be applied to operands of type 'System.Guid' and 'System.DateTime'. + +true ? 1 : DayOfWeek.Friday +Operator '?:' cannot be applied to operands of type 'System.Int32' and 'System.DayOfWeek'. + +true ? 1 : null +Operator '?:' cannot be applied to operands of type 'System.Int32' and ''. + +true ? null : null +Operator '?:' cannot be applied to operands of type '' and ''. + +(true ? "abc" : null :> object).Length +Cannot resolve symbol 'Length'. diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt index 056ab3f..d08bb71 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt @@ -216,8 +216,8 @@ IIF((1 > 0), Int32.MaxValue, Int32.MinValue) true ? "a" : string.Empty IIF(True, "a", String.Empty) -true ? null : null -IIF(True, null, null) +true ? "a" : null +IIF(True, "a", null) 1 > 0 ? 2 > 0 ? int.MaxValue : int.MinValue : 0 IIF((1 > 0), IIF((2 > 0), Int32.MaxValue, Int32.MinValue), 0) @@ -518,3 +518,33 @@ Convert(DayOfWeek.Friday, Int64) DayOfWeek.Friday :> DayOfWeek DayOfWeek.Friday + +####################################### +# Conditional operator branches of different types + +true ? 1 : 2.0 +IIF(True, Convert(1, Double), 2) + +false ? 1 : 2m +IIF(False, Convert(1, Decimal), 2) + +true ? 'a' : 1 +IIF(True, Convert(a, Int32), 1) + +true ? 1 :> byte : 2 :> short +IIF(True, Convert(Convert(1, Byte), Int16), Convert(2, Int16)) + +true ? 1u : 1L +IIF(True, Convert(1, Int64), 1) + +false ? null : "a" +IIF(False, null, "a") + +true ? (null) : "a" +IIF(True, null, "a") + +(true ? "abc" : null).Length +IIF(True, "abc", null).Length + +true ? 1 : 2 :> object +IIF(True, Convert(1, Object), Convert(2, Object))