From 9a0dd2bda050af92498e275e82fdab66c08e7e69 Mon Sep 17 00:00:00 2001 From: rameel Date: Wed, 18 Nov 2026 19:13:22 +0500 Subject: [PATCH] parser: support nullable value types in operators Operators accepted operands of a nullable value type only when both operands had the same type, as in x + y for two int? values. Mixed operands were rejected: for an int? x, x ?? 5, x + 1, x > 1, and Flag ? x : 1 all failed, as did x == DayOfWeek.Friday for a DayOfWeek? x and x > Date for a DateTime? x. The unary '~' did not promote a byte? operand, so ~x for x = 3 returned 252 as byte? instead of -4 as int?. Follow the C# rules for nullable value types: - Add the implicit conversions from S and S? to T? for each identity or numeric conversion from S to T. The conditional operator uses them to find the common type of its branches. - Determine the result type of '??' in the order of the specification: A0, A, then B. For example, x ?? 1 is an int, x ?? 1L is a long, and x ?? y is a long? for a long? y. - Lift the unary and binary operators, including shifts, enum operators, and user-defined operators such as DateTime subtraction: select the operator by the underlying types of the operands and convert the operands to the nullable forms of its operand types. - Give the null literal the type of the nullable operand on the other side, as in x == null or x ?? null. --- .../ExpressionBuilder.Helpers.cs | 226 ++++++++++++++---- .../ExpressionBuilder.cs | 40 ++-- .../Internal/ReflectionExtensions.cs | 21 ++ .../ExpressionParserTest.cs | 174 ++++++++++++++ 4 files changed, 395 insertions(+), 66 deletions(-) diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs index 131f297..0406b96 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs @@ -45,6 +45,20 @@ private object ResolveSymbol(Expr.Reference expr) if (TypeUtils.CanConvertPrimitive(expression.Type, conversionType)) return Expression.Convert(expression, conversionType); + // + // 10.2.6 Implicit nullable conversions + // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#1026-implicit-nullable-conversions + // + // For each predefined implicit identity or numeric conversion from a non-nullable value type S + // to a non-nullable value type T, implicit conversions exist from S? to T? and from S to T?. + // + if (Nullable.GetUnderlyingType(conversionType) is { } underlyingType) + { + var sourceType = expression.Type.GetNonNullableType(); + if (sourceType == underlyingType || TypeUtils.CanConvertPrimitive(sourceType, underlyingType)) + return Expression.Convert(expression, conversionType); + } + var conversion = TypeUtils.FindConversionOperator(expression.Type, conversionType); if (conversion is not null) return Expression.Convert(expression, conversionType, conversion); @@ -111,16 +125,86 @@ private static Type ApplyConditionalConversions(Expr.Conditional expr, ref Expre Error.NonApplicableConditionalOperator(ifTrue.Type, ifFalse.Type); return null!; - static bool IsNullLiteral(Expr expr) + static bool CanBeNull(Type type) => + !type.IsValueType || type.IsNullable(); + } + + /// + /// Creates a null-coalescing expression whose operands are converted to its result type. + /// + /// The representing the operator. + /// The expression of the left operand. + /// The expression of the right operand. + /// + /// The null-coalescing expression. + /// + private static BinaryExpression ApplyNullCoalescing(Identifier op, Expression lhs, Expression rhs) + { + // + // 12.15 The null coalescing operator + // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1215-the-null-coalescing-operator + // + // In order of preference, the type of a ?? b is A₀, A, or B, where A is the type of a, B is the type of b, + // and A₀ is the underlying type of A if A is a nullable value type, or A otherwise: + // + // * If A is a non-nullable value type, a compile-time error occurs. + // * Otherwise, if A is a nullable value type and an implicit conversion exists from b to A₀, + // the result type is A₀. + // * Otherwise, if an implicit conversion exists from b to A, the result type is A. + // * Otherwise, if A is a nullable value type and an implicit conversion exists from A₀ to B, + // the result type is B. + // + var lhsType = lhs.Type; + var rhsType = rhs.Type; + + if (lhsType.IsValueType && !lhsType.IsNullable()) + Error.NonApplicableBinaryOperator(op, lhsType, rhsType); + + var underlyingType = Nullable.GetUnderlyingType(lhsType); + if (underlyingType is not null) { - while (expr is Expr.Parenthesized parenthesized) - expr = parenthesized.Expression; + var value = ApplyImplicitConversion(rhs, underlyingType); + if (value is not null) + return Expression.Coalesce(lhs, value); + } - return expr is Expr.Literal { Value: null }; + var converted = ApplyImplicitConversion(rhs, lhsType); + if (converted is not null) + return Expression.Coalesce(lhs, converted); + + if (underlyingType is not null) + { + // + // A non-null value of a is unwrapped and converted to B. Convert a to the nullable form of B instead, + // which keeps its null value. For a reference type B, the conversion is a boxing conversion. + // + converted = rhsType.IsValueType + ? ApplyImplicitConversion(lhs, rhsType.IsNullable() ? rhsType : rhsType.MakeNullableType()) + : rhsType.IsAssignableFrom(underlyingType) + ? Expression.Convert(lhs, rhsType) + : null; + + if (converted is not null) + return Expression.Coalesce(converted, rhs); } - static bool CanBeNull(Type type) => - !type.IsValueType || type.IsNullable(); + Error.NonApplicableBinaryOperator(op, lhsType, rhsType); + return null!; + } + + /// + /// Determines whether the specified expression is the null literal, possibly in parentheses. + /// + /// The expression to test. + /// + /// if the expression is the null literal; otherwise, . + /// + private static bool IsNullLiteral(Expr expr) + { + while (expr is Expr.Parenthesized parenthesized) + expr = parenthesized.Expression; + + return expr is Expr.Literal { Value: null }; } /// @@ -260,29 +344,40 @@ static Expression Convert(Expression argument, Type conversionType) private static Expression ApplyBinaryExpression(Identifier op, Func apply, Expression lhs, Expression rhs) { - var enumUnderlyingType = lhs.Type.IsEnum - ? lhs.Type.GetEnumUnderlyingType() - : rhs.Type.IsEnum - ? rhs.Type.GetEnumUnderlyingType() - : null; + // + // 12.4.8 Lifted operators + // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1248-lifted-operators + // + // The operators on non-nullable value types have lifted forms, which take and return the nullable forms + // of the types. If either operand is of a nullable value type, the operator is selected by the underlying + // types of the operands, and both operands are converted to the nullable forms of the operator's operand types. + // + var lhsType = lhs.Type; + var rhsType = rhs.Type; - var enumType = lhs.Type.IsEnum - ? lhs.Type - : rhs.Type.IsEnum - ? rhs.Type + var lifted = lhsType.IsNullable() || rhsType.IsNullable(); + var lhsNonNullableType = lhsType.GetNonNullableType(); + var rhsNonNullableType = rhsType.GetNonNullableType(); + + var enumType = lhsNonNullableType.IsEnum + ? lhsNonNullableType + : rhsNonNullableType.IsEnum + ? rhsNonNullableType : null; - if (enumUnderlyingType is not null) + if (enumType is not null) { - if (lhs.Type != rhs.Type) - if (lhs.Type.IsEnum ? enumUnderlyingType != rhs.Type : enumUnderlyingType != lhs.Type) - Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type); + var enumUnderlyingType = enumType.GetEnumUnderlyingType(); + + if (lhsNonNullableType != rhsNonNullableType) + if (lhsNonNullableType.IsEnum ? enumUnderlyingType != rhsNonNullableType : enumUnderlyingType != lhsNonNullableType) + Error.NonApplicableBinaryOperator(op, lhsType, rhsType); - if (lhs.Type.IsEnum) - lhs = Expression.Convert(lhs, enumUnderlyingType); + if (lhsNonNullableType.IsEnum) + lhs = ConvertOperand(lhs, enumUnderlyingType, lifted); - if (rhs.Type.IsEnum) - rhs = Expression.Convert(rhs, enumUnderlyingType); + if (rhsNonNullableType.IsEnum) + rhs = ConvertOperand(rhs, enumUnderlyingType, lifted); } if (enumType is null && op.Name is ">>" or ">>>" or "<<") @@ -291,32 +386,46 @@ private static Expression ApplyBinaryExpression(Identifier op, Func>>") { - if (lhs.Type == typeof(int)) - return Expression.Convert( - apply(Expression.Convert(lhs, typeof(uint)), rhs), - typeof(int)); - - if (lhs.Type == typeof(long)) - return Expression.Convert( - apply(Expression.Convert(lhs, typeof(ulong)), rhs), - typeof(long)); + if (shiftType == typeof(int)) + return ConvertOperand( + apply(ConvertOperand(lhs, typeof(uint), lifted), rhs), + typeof(int), + lifted); + + if (shiftType == typeof(long)) + return ConvertOperand( + apply(ConvertOperand(lhs, typeof(ulong), lifted), rhs), + typeof(long), + lifted); } return apply(lhs, rhs); } ApplyBinaryNumericPromotions(op, ref lhs, ref rhs); + + if (lifted) + { + // + // Expression lifts a user-defined operator, such as DateTime subtraction, only if both operands + // are of nullable types, so convert the remaining operand of a non-nullable value type. + // + if (lhs.Type.IsValueType) + lhs = ConvertOperand(lhs, lhs.Type.GetNonNullableType(), lifted: true); + + if (rhs.Type.IsValueType) + rhs = ConvertOperand(rhs, rhs.Type.GetNonNullableType(), lifted: true); + } + var result = apply(lhs, rhs); if (enumType is not null) @@ -332,13 +441,32 @@ private static Expression ApplyBinaryExpression(Identifier op, Func + /// Converts an operand to the specified type, or to the nullable form of the type for a lifted operator. + /// + /// The expression of the operand. + /// The non-nullable value type to convert to. + /// to convert to the nullable form of . + /// + /// The converted expression, or if it is already of the resulting type. + /// + private static Expression ConvertOperand(Expression operand, Type type, bool lifted) + { + if (lifted) + type = type.MakeNullableType(); + + return operand.Type != type + ? Expression.Convert(operand, type) + : operand; + } + private static Expression ApplyUnaryNumericPromotion(Expression operand) { // @@ -346,15 +474,16 @@ private static Expression ApplyUnaryNumericPromotion(Expression operand) // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#12472-unary-numeric-promotions // // Unary numeric promotion consists of converting operands of type sbyte, byte, short, ushort, or char to type int. + // For a lifted operator, an operand of the nullable form of these types is converted to int?. // - var type = operand.Type; + var type = operand.Type.GetNonNullableType(); if (type == typeof(sbyte) || type == typeof(byte) || type == typeof(short) || type == typeof(ushort) || type == typeof(char)) - return Expression.Convert(operand, typeof(int)); + return ConvertOperand(operand, typeof(int), operand.Type.IsNullable()); return operand; } @@ -380,9 +509,13 @@ private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression l // both operands are converted to type long. // * Otherwise, if either operand is of type uint, the other operand is converted to type uint. // * Otherwise, both operands are converted to type int. + // + // For a lifted operator, the rules apply to the underlying types, and both operands are converted + // to the nullable form of the resulting type. - var lhsType = lhs.Type; - var rhsType = rhs.Type; + var lhsType = lhs.Type.GetNonNullableType(); + var rhsType = rhs.Type.GetNonNullableType(); + var lifted = lhs.Type.IsNullable() || rhs.Type.IsNullable(); if (!TypeUtils.IsNumeric(lhsType) || !TypeUtils.IsNumeric(rhsType)) @@ -418,7 +551,7 @@ private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression l || lhsType == typeof(float) || rhsType == typeof(double) || rhsType == typeof(float)) - Error.NonApplicableBinaryOperator(op, lhsType, rhsType); + Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type); } else if (conversionType == typeof(ulong)) { @@ -434,7 +567,7 @@ private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression l || rhsType == typeof(short) || rhsType == typeof(int) || rhsType == typeof(long)) - Error.NonApplicableBinaryOperator(op, lhsType, rhsType); + Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type); } else if (conversionType == typeof(uint)) { @@ -451,11 +584,8 @@ private static void ApplyBinaryNumericPromotions(Identifier op, ref Expression l conversionType = typeof(long); } - if (lhsType != conversionType) - lhs = Expression.Convert(lhs, conversionType); - - if (rhsType != conversionType) - rhs = Expression.Convert(rhs, conversionType); + lhs = ConvertOperand(lhs, conversionType, lifted); + rhs = ConvertOperand(rhs, conversionType, lifted); return; } diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs index 58df7a5..6cc2771 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs @@ -53,6 +53,15 @@ protected internal override Expression VisitBinary(Expr.Binary expr) var lhsType = lhs.Type; var rhsType = rhs.Type; + // + // The null literal converts to a nullable value type, so opposite an operand of such a type + // it takes that type, as in 'x == null' or 'x ?? null'. + // + if (lhsType.IsNullable() && IsNullLiteral(expr.Right)) + rhs = Expression.Constant(null, lhsType); + else if (rhsType.IsNullable() && IsNullLiteral(expr.Left)) + lhs = Expression.Constant(null, rhsType); + var factory = ResolveBinaryOperatorFactory(expr.Operator.Name); switch (expr.Operator.Name) @@ -71,14 +80,7 @@ protected internal override Expression VisitBinary(Expr.Binary expr) break; case "??": - if (lhsType.IsValueType && !lhsType.IsNullable()) - Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType); - - rhs = ApplyImplicitConversion(rhs, lhsType); - if (rhs is null) - Error.NonApplicableBinaryOperator(expr.Operator, lhsType, rhsType); - - break; + return ApplyNullCoalescing(expr.Operator, lhs, rhs); case "+": if (lhsType != typeof(string) && rhsType != typeof(string)) @@ -379,21 +381,24 @@ protected internal override Expression VisitUnary(Expr.Unary expr) { var operand = Visit(expr.Operand); + // + // For an operand of a nullable value type, the operators below are lifted: + // they apply to the underlying type and return the nullable form of their result type. + // var operandType = operand.Type; - var underlyingType = operandType.IsEnum - ? operandType.GetEnumUnderlyingType() - : operandType; + var nonNullableType = operandType.GetNonNullableType(); + var lifted = operandType.IsNullable(); // // C# does not define the unary '-' and '+' operators for an enum, and '~' applies to its underlying type. // A conversion takes the enum itself, so that converting it to object boxes the enum // rather than its underlying value. // - if (operandType.IsEnum && expr.UnaryType is UnaryType.Negate or UnaryType.UnaryPlus) + if (nonNullableType.IsEnum && expr.UnaryType is UnaryType.Negate or UnaryType.UnaryPlus) Error.NonApplicableUnaryOperator(expr, operandType); - if (operandType.IsEnum && expr.UnaryType != UnaryType.Convert) - operand = Expression.Convert(operand, underlyingType); + if (nonNullableType.IsEnum && expr.UnaryType != UnaryType.Convert) + operand = ConvertOperand(operand, nonNullableType.GetEnumUnderlyingType(), lifted); switch (expr.UnaryType, operand) { @@ -407,8 +412,8 @@ protected internal override Expression VisitUnary(Expr.Unary expr) // C# has no negation operator for uint, so the operand is converted to long // and then negated, which keeps the sign of the result. // - case (UnaryType.Negate, _) when operand.Type == typeof(uint): - operand = Expression.Convert(operand, typeof(long)); + case (UnaryType.Negate, _) when operand.Type.GetNonNullableType() == typeof(uint): + operand = ConvertOperand(operand, typeof(long), lifted); break; case (not UnaryType.Convert, _): @@ -427,7 +432,6 @@ protected internal override Expression VisitUnary(Expr.Unary expr) // Allow only the logical negation, as C# does. For a nullable operand, // Expression.Not lifts the negation of the underlying type. // - var nonNullableType = Nullable.GetUnderlyingType(operandType) ?? operandType; if (nonNullableType == typeof(bool)) return Expression.Not(operand); @@ -449,7 +453,7 @@ protected internal override Expression VisitUnary(Expr.Unary expr) case UnaryType.OnesComplement: operand = Expression.OnesComplement(operand); - return operandType.IsEnum + return nonNullableType.IsEnum ? Expression.Convert(operand, operandType) : operand; diff --git a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs index 71d4eb6..f51805d 100644 --- a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs +++ b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs @@ -17,6 +17,27 @@ internal static class ReflectionExtensions public static bool IsNullable(this Type type) => type.IsGenericType && !type.IsGenericTypeDefinition && type.GetGenericTypeDefinition() == typeof(Nullable<>); + /// + /// Returns the underlying type of the specified type, or the type itself for any other type. + /// + /// The to evaluate. + /// + /// The underlying type if is a type; + /// otherwise, . + /// + public static Type GetNonNullableType(this Type type) => + Nullable.GetUnderlyingType(type) ?? type; + + /// + /// Returns the type for the specified non-nullable value type. + /// + /// The non-nullable value type. + /// + /// The type whose underlying type is . + /// + public static Type MakeNullableType(this Type type) => + typeof(Nullable<>).MakeGenericType(type); + /// /// Determines whether the specified type is declared as static. /// diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index 2f8f087..ed45d31 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -107,6 +107,54 @@ static string Repeat(string value, int count) => } } + private static IEnumerable LiftedBinaryOperatorSource + { + get + { + yield return Case("NullableInt + 1", typeof(int?), 6); + yield return Case("NullInt + 1", typeof(int?), null); + yield return Case("NullableInt + 1L", typeof(long?), 6L); + yield return Case("NullableInt + Big", typeof(long?), 15L); + yield return Case("NullableInt * 2.5", typeof(double?), 12.5); + yield return Case("NullableInt / 2", typeof(int?), 2); + yield return Case("NullableInt % 2", typeof(int?), 1); + yield return Case("NullableInt - NullableLong", typeof(long?), -2L); + yield return Case("NullableByte + NullableByte", typeof(int?), 6); + yield return Case("NullableChar + 1", typeof(int?), 98); + yield return Case("NullableDecimal + 1", typeof(decimal?), 3.5m); + yield return Case("NullableUInt + NullableInt", typeof(long?), 9L); + yield return Case("NullableULong + 1u", typeof(ulong?), 9UL); + yield return Case("NullInt + null", typeof(int?), null); + + yield return Case("NullableInt & 1", typeof(int?), 1); + yield return Case("NullableInt | NullableLong", typeof(long?), 7L); + yield return Case("NullableInt ^ 1", typeof(int?), 4); + yield return Case("NullableTrue & true", typeof(bool?), true); + yield return Case("NullBool & false", typeof(bool?), false); + yield return Case("NullBool | true", typeof(bool?), true); + yield return Case("NullBool ^ true", typeof(bool?), null); + + yield return Case("NullableInt << 1", typeof(int?), 10); + yield return Case("NullableByte << 1", typeof(int?), 6); + yield return Case("1 << NullableInt", typeof(int?), 32); + yield return Case("NullableLong << NullableInt", typeof(long?), 224L); + yield return Case("-NullableInt >>> 28", typeof(int?), 15); + yield return Case("-NullableLong >>> 60", typeof(long?), 15L); + yield return Case("NullInt << 1", typeof(int?), null); + + yield return Case("NullableDay | DayOfWeek.Monday", typeof(DayOfWeek?), DayOfWeek.Friday); + yield return Case("NullableDay & Day", typeof(DayOfWeek?), DayOfWeek.Monday); + yield return Case("NullableDay + 1", typeof(DayOfWeek?), DayOfWeek.Saturday); + yield return Case("NullDay | Day", typeof(DayOfWeek?), null); + + yield return Case("NullableDate - Date", typeof(TimeSpan?), TimeSpan.FromDays(1)); + yield return Case("Date + NullableSpan", typeof(DateTime?), new DateTime(2020, 1, 1, 1, 0, 0)); + + static TestCaseData Case(string expression, Type type, object? expected) => + new(expression, type, expected); + } + } + [OneTimeSetUp] public void Setup() { @@ -308,6 +356,90 @@ public void Parse_TypeWithWriteOnlyIndexer_ReturnsNonIndexingError() $"Cannot apply indexing with [] to an expression of type '{typeof(WriteOnlyIndexer)}'.")); } + [TestCase("NullInt ?? 1", typeof(int), 1)] + [TestCase("NullableInt ?? 1", typeof(int), 5)] + [TestCase("NullInt ?? NullableInt", typeof(int?), 5)] + [TestCase("NullInt ?? 1L", typeof(long), 1L)] + [TestCase("NullInt ?? 1.5", typeof(double), 1.5)] + [TestCase("NullableByte ?? Count", typeof(int), 3)] + [TestCase("NullInt ?? NullableLong", typeof(long?), 7L)] + [TestCase("NullInt ?? (1 :> object)", typeof(object), 1)] + [TestCase("NullInt ?? NullInt ?? 9", typeof(int), 9)] + [TestCase("NullBool ?? Flag", typeof(bool), true)] + [TestCase("NullDay ?? Day", typeof(DayOfWeek), DayOfWeek.Monday)] + [TestCase("NullableDay ?? DayOfWeek.Sunday", typeof(DayOfWeek), DayOfWeek.Friday)] + [TestCase("NullInt ?? null", typeof(int?), null)] + [TestCase("null ?? NullableInt", typeof(int?), 5)] + public void Evaluate_NullCoalescingOnNullable_ReturnsTypeOfCSharp(string expression, Type type, object? expected) => + AssertNullableResult(expression, type, expected); + + [TestCaseSource(nameof(LiftedBinaryOperatorSource))] + public void Evaluate_LiftedBinaryOperator_ReturnsNullableResult(string expression, Type type, object? expected) => + AssertNullableResult(expression, type, expected); + + [TestCase("NullableInt > 1", true)] + [TestCase("NullInt > 1", false)] + [TestCase("NullInt <= 1", false)] + [TestCase("NullableInt >= NullableLong", false)] + [TestCase("NullableInt < 1.5", false)] + [TestCase("NullableInt == 5", true)] + [TestCase("NullInt == 5", false)] + [TestCase("NullInt != 5", true)] + [TestCase("NullableInt == NullableLong", false)] + [TestCase("NullableByte == 3", true)] + [TestCase("NullableDecimal > 1", true)] + [TestCase("NullableTrue == true", true)] + [TestCase("NullBool == false", false)] + [TestCase("NullableDay == DayOfWeek.Friday", true)] + [TestCase("NullDay == DayOfWeek.Friday", false)] + [TestCase("NullableDay > Day", true)] + [TestCase("NullableDate > Date", true)] + [TestCase("NullableDate == Date", false)] + [TestCase("NullInt == null", true)] + [TestCase("null != NullableInt", true)] + [TestCase("NullDay == null", true)] + [TestCase("NullableDay != null", true)] + [TestCase("NullInt > null", false)] + public void Evaluate_LiftedComparison_ReturnsBoolean(string expression, bool expected) => + AssertNullableResult(expression, typeof(bool), expected); + + [TestCase("-NullableInt", typeof(int?), -5)] + [TestCase("-NullInt", typeof(int?), null)] + [TestCase("-NullableByte", typeof(int?), -3)] + [TestCase("~NullableByte", typeof(int?), -4)] + [TestCase("-NullableChar", typeof(int?), -97)] + [TestCase("+NullableChar", typeof(int?), 97)] + [TestCase("-NullableUInt", typeof(long?), -4L)] + [TestCase("~NullableDay", typeof(DayOfWeek?), ~DayOfWeek.Friday)] + [TestCase("~NullDay", typeof(DayOfWeek?), null)] + public void Evaluate_LiftedUnaryOperator_ReturnsNullableResult(string expression, Type type, object? expected) => + AssertNullableResult(expression, type, expected); + + [TestCase("Flag ? NullableInt : 1", typeof(int?), 5)] + [TestCase("Flag ? 1 : NullableInt", typeof(int?), 1)] + [TestCase("Flag ? NullableInt : NullableLong", typeof(long?), 5L)] + [TestCase("Flag ? NullDay : Day", typeof(DayOfWeek?), null)] + public void Evaluate_ConditionalWithNullableBranch_ReturnsNullableType(string expression, Type type, object? expected) => + AssertNullableResult(expression, type, expected); + + [TestCase("NullableDouble + NullableDecimal", "Operator '+' cannot be applied to operands of type 'System.Nullable`1[System.Double]' and 'System.Nullable`1[System.Decimal]'.")] + [TestCase("NullableULong + NullableInt", "Operator '+' cannot be applied to operands of type 'System.Nullable`1[System.UInt64]' and 'System.Nullable`1[System.Int32]'.")] + [TestCase("NullableInt << 1L", "Operator '<<' cannot be applied to operands of type 'System.Nullable`1[System.Int32]' and 'System.Int64'.")] + [TestCase("NullableInt ?? \"x\"", "Operator '??' cannot be applied to operands of type 'System.Nullable`1[System.Int32]' and 'System.String'.")] + [TestCase("-NullableDay", "Unary operator '-' cannot be applied to operand of type 'System.Nullable`1[System.DayOfWeek]'.")] + [TestCase("+NullableDay", "Unary operator '+' cannot be applied to operand of type 'System.Nullable`1[System.DayOfWeek]'.")] + [TestCase("-NullableULong", "Unary operator '-' cannot be applied to operand of type 'System.Nullable`1[System.UInt64]'.")] + [TestCase("NullBool && true", "Cannot implicitly convert type 'System.Nullable`1[System.Boolean]' to 'System.Boolean'.")] + [TestCase("Flag ? NullableInt : 1L", "Operator '?:' cannot be applied to operands of type 'System.Nullable`1[System.Int32]' and 'System.Int64'.")] + public void Parse_NullableOperandsWithoutOperatorInCSharp_ReturnsError(string expression, string expected) + { + var parameter = Expression.Parameter(typeof(NullableContext), "c"); + var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Is.EqualTo(expected)); + } + [TestCaseSource(nameof(ErrorsSource))] public void ParseErrorExpression(string expression, string expected) { @@ -403,6 +535,24 @@ public void StringConcatTest(string source, string expected) Assert.That(result.ToString(), Is.EqualTo(expected)); } + private static void AssertNullableResult(string expression, Type type, object? expected) + { + var parameter = Expression.Parameter(typeof(NullableContext), "c"); + var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); + + Assert.That(result.Success, Is.True, result.ErrorMessage); + Assert.That(result.Value!.Type, Is.EqualTo(type)); + + // + // Boxing loses the nullable type, so the type of the value is checked separately from the type of the expression. + // + var body = Expression.Convert(result.Value, typeof(object)); + var value = Expression.Lambda>(body, parameter).Compile()(new NullableContext()); + + Assert.That(value, Is.EqualTo(expected)); + Assert.That(value?.GetType(), Is.EqualTo(expected?.GetType())); + } + private static T RunOnThread(int maxStackSize, Func func) { var result = default(T); @@ -606,6 +756,30 @@ public static string WithMissing([Optional] object value, [Optional] int number) $"{value.GetType().Name} {number}"; } + public class NullableContext + { + public int? NullableInt { get; } = 5; + public int? NullInt { get; } + public long? NullableLong { get; } = 7; + public byte? NullableByte { get; } = 3; + public char? NullableChar { get; } = 'a'; + public uint? NullableUInt { get; } = 4; + public ulong? NullableULong { get; } = 8; + public double? NullableDouble { get; } = 1.5; + public decimal? NullableDecimal { get; } = 2.5m; + public bool? NullableTrue { get; } = true; + public bool? NullBool { get; } + public DayOfWeek? NullableDay { get; } = DayOfWeek.Friday; + public DayOfWeek? NullDay { get; } + public DateTime? NullableDate { get; } = new DateTime(2020, 1, 2); + public TimeSpan? NullableSpan { get; } = TimeSpan.FromHours(1); + public int Count { get; } = 3; + public long Big { get; } = 10; + public bool Flag { get; } = true; + public DayOfWeek Day { get; } = DayOfWeek.Monday; + public DateTime Date { get; } = new DateTime(2020, 1, 1); + } + public class ArrayContext { public int[] Numbers { get; } = [1, 2, 3];