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
93 changes: 93 additions & 0 deletions src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,99 @@ private object ResolveSymbol(Expr.Reference expr)
return null;
}

/// <summary>
/// Converts the branches of a conditional expression to their common type.
/// </summary>
/// <remarks>
/// As in C#, the common type is the type of one of the branches, so it is <see cref="object"/> 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 <see langword="null" />.
/// </remarks>
/// <param name="expr">The conditional expression.</param>
/// <param name="ifTrue">The expression of the true branch.</param>
/// <param name="ifFalse">The expression of the false branch.</param>
/// <returns>
/// The common type of the branches.
/// </returns>
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();
}

/// <summary>
/// Applies an implicit conversion of a branch of a conditional expression to the type of the other branch.
/// </summary>
/// <param name="expression">The expression of the branch.</param>
/// <param name="conversionType">The type of the other branch.</param>
/// <returns>
/// The converted expression, or <see langword="null" /> if no implicit conversion exists.
/// </returns>
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<Expression> CreateInjectingArguments(MethodInfo method, IReadOnlyList<Expression> args)
{
var parameters = method.GetParameters();
Expand Down
3 changes: 2 additions & 1 deletion src/Ramstack.ExpressionParser/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
13 changes: 13 additions & 0 deletions src/Ramstack.ExpressionParser/Internal/Error.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ public static void NonApplicableBinaryOperator(Identifier op, Type left, Type ri
throw new ParseErrorException(message);
}

/// <summary>
/// Throws a <see cref="ParseErrorException"/> indicating the conditional operator cannot be applied to its branches
/// because they have no common type.
/// </summary>
/// <param name="ifTrue">The <see cref="Type"/> of the true branch, or <see langword="null" /> for the null literal.</param>
/// <param name="ifFalse">The <see cref="Type"/> of the false branch, or <see langword="null" /> for the null literal.</param>
[DoesNotReturn]
public static void NonApplicableConditionalOperator(Type? ifTrue, Type? ifFalse)
{
var message = $"Operator '?:' cannot be applied to operands of type '{ifTrue?.ToString() ?? "<null>"}' and '{ifFalse?.ToString() ?? "<null>"}'.";
throw new ParseErrorException(message);
}

/// <summary>
/// Throws a <see cref="ParseErrorException"/> indicating an implicit type conversion is not possible.
/// </summary>
Expand Down
24 changes: 14 additions & 10 deletions src/Ramstack.ExpressionParser/Internal/TypeUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -114,7 +114,11 @@ public static bool IsInteger(Type type)
/// </returns>
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))
Expand Down
33 changes: 33 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<null>'.

true ? null : null
Operator '?:' cannot be applied to operands of type '<null>' and '<null>'.

(true ? "abc" : null :> object).Length
Cannot resolve symbol 'Length'.
34 changes: 32 additions & 2 deletions tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
33 changes: 33 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/TypeUtilsTest.cs
Original file line number Diff line number Diff line change
@@ -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);
}
Loading