diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs index 0406b96..501e033 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs @@ -207,6 +207,78 @@ private static bool IsNullLiteral(Expr expr) return expr is Expr.Literal { Value: null }; } + /// + /// Determines whether the specified expression is the integer literal 0, possibly in parentheses. + /// + /// The expression to test. + /// + /// if the expression is the integer literal 0; otherwise, . + /// + private static bool IsZeroLiteral(Expr expr) + { + while (expr is Expr.Parenthesized parenthesized) + expr = parenthesized.Expression; + + return expr is Expr.Literal { Value: 0 or 0u or 0L or 0UL }; + } + + /// + /// Converts the integer literal 0 opposite an operand of an enum type to that enum type + /// if the operator is defined for two operands of the enum type. + /// + /// The binary expression. + /// The expression of the left operand. + /// The expression of the right operand. + private static void ApplyEnumZeroConversion(Expr.Binary expr, ref Expression lhs, ref Expression rhs) + { + // + // 10.2.4 Implicit enumeration conversions + // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#1024-implicit-enumeration-conversions + // + // An implicit enumeration conversion permits a constant expression with any integer type and the value zero + // to be converted to any enum type and to any nullable value type whose underlying type is an enum type. + // + // Of such constant expressions, only the integer literal 0 is recognized. + // + switch (expr.Operator.Name) + { + case "-": + case "&": + case "|": + case "^": + case "==": + case "!=": + case "<": + case ">": + case "<=": + case ">=": + break; + + default: + return; + } + + var lhsType = lhs.Type.GetNonNullableType(); + var rhsType = rhs.Type.GetNonNullableType(); + + if (lhsType.IsEnum && IsZeroLiteral(expr.Right)) + { + // + // Both E - E and E - U accept 'x - 0'. As in the C# compiler, E - U is selected and returns E + // if the literal is of the underlying type U; otherwise, E - E is selected and returns U, as in 'x - 0L'. + // + if (expr.Operator.Name != "-" || rhsType != lhsType.GetEnumUnderlyingType()) + rhs = Expression.Convert(rhs, lhsType); + } + else if (rhsType.IsEnum && IsZeroLiteral(expr.Left)) + { + // + // As in the C# compiler, E - E is selected for '0 - x' over U - E, so the result is of the underlying type. + // + lhs = Expression.Convert(lhs, rhsType); + } + } + /// /// Applies an implicit conversion of a branch of a conditional expression to the type of the other branch. /// @@ -365,13 +437,57 @@ private static Expression ApplyBinaryExpression(Identifier op, Func, <=, >= + // + // Each operator is evaluated on the values converted to U, as in (E)((U)x + (U)y). + // The C# compiler also accepts U - E and returns E, so it is supported as well. + // var enumUnderlyingType = enumType.GetEnumUnderlyingType(); + var otherType = lhsNonNullableType.IsEnum ? rhsNonNullableType : lhsNonNullableType; + + var isEnumPair = lhsNonNullableType == rhsNonNullableType; + var isUnderlyingPair = otherType == enumUnderlyingType + || TypeUtils.CanConvertPrimitive(otherType, enumUnderlyingType); + + switch (op.Name) + { + case "+" when isUnderlyingPair: + case "-" when isUnderlyingPair: + case "&" or "|" or "^" when isEnumPair: + enumResultType = enumType; + break; - if (lhsNonNullableType != rhsNonNullableType) - if (lhsNonNullableType.IsEnum ? enumUnderlyingType != rhsNonNullableType : enumUnderlyingType != lhsNonNullableType) + case "-" when isEnumPair: + enumResultType = enumUnderlyingType; + break; + + case "==" or "!=" or "<" or ">" or "<=" or ">=" when isEnumPair: + break; + + default: Error.NonApplicableBinaryOperator(op, lhsType, rhsType); + break; + } if (lhsNonNullableType.IsEnum) lhs = ConvertOperand(lhs, enumUnderlyingType, lifted); @@ -379,8 +495,7 @@ private static Expression ApplyBinaryExpression(Identifier op, Func>" or ">>>" or "<<") + else if (op.Name is ">>" or ">>>" or "<<") { // // The predefined shift operators take an int, uint, long, or ulong value and an int count, @@ -428,24 +543,9 @@ private static Expression ApplyBinaryExpression(Identifier op, Func": - case "<": - case ">=": - case "<=": - return result; - - default: - return ConvertOperand(result, enumType, lifted); - } - } - - return result; + return enumResultType is not null + ? ConvertOperand(result, enumResultType, lifted) + : result; } /// diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs index 6cc2771..d2abc83 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs @@ -55,12 +55,15 @@ protected internal override Expression VisitBinary(Expr.Binary expr) // // 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'. + // it takes that type, as in 'x == null' or 'x ?? null'. For an enum type E, only E + U and U + E + // are defined, so in 'x + null' it takes the nullable form of the underlying type U instead. // if (lhsType.IsNullable() && IsNullLiteral(expr.Right)) - rhs = Expression.Constant(null, lhsType); + rhs = Expression.Constant(null, GetNullLiteralType(expr.Operator, lhsType)); else if (rhsType.IsNullable() && IsNullLiteral(expr.Left)) - lhs = Expression.Constant(null, rhsType); + lhs = Expression.Constant(null, GetNullLiteralType(expr.Operator, rhsType)); + + ApplyEnumZeroConversion(expr, ref lhs, ref rhs); var factory = ResolveBinaryOperatorFactory(expr.Operator.Name); @@ -168,6 +171,11 @@ void Flatten(Expression e) } return null!; + + static Type GetNullLiteralType(Identifier op, Type operandType) => + op.Name == "+" && operandType.GetNonNullableType() is { IsEnum: true } enumType + ? enumType.GetEnumUnderlyingType().MakeNullableType() + : operandType; } /// diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt index f340493..df597bd 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt @@ -179,6 +179,63 @@ Operator '>>' cannot be applied to operands of type 'System.Double' and 'System. 1m >>> 1 Operator '>>>' cannot be applied to operands of type 'System.Decimal' and 'System.Int32'. +####################################### +# Binary operators not defined for enum operands + +DayOfWeek.Friday * 2 +Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday / 2 +Operator '/' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday % 2 +Operator '%' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday * 0 +Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday * DayOfWeek.Monday +Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.DayOfWeek'. + +DayOfWeek.Friday << 1 +Operator '<<' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +1 << DayOfWeek.Friday +Operator '<<' cannot be applied to operands of type 'System.Int32' and 'System.DayOfWeek'. + +DayOfWeek.Friday >> 1 +Operator '>>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday >>> 1 +Operator '>>>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday + DayOfWeek.Monday +Operator '+' cannot be applied to operands of type 'System.DayOfWeek' and 'System.DayOfWeek'. + +DayOfWeek.Friday + 1L +Operator '+' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int64'. + +DayOfWeek.Friday & 1 +Operator '&' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday | 1 +Operator '|' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +1 ^ DayOfWeek.Friday +Operator '^' cannot be applied to operands of type 'System.Int32' and 'System.DayOfWeek'. + +DayOfWeek.Friday == 5 +Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday > 1 +Operator '>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'. + +DayOfWeek.Friday == 0.0 +Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Double'. + +DayOfWeek.Friday == StringSplitOptions.None +Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.StringSplitOptions'. + ####################################### # Conditional operator branches without a common type diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt index ea6a6e8..af18b65 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt @@ -519,6 +519,18 @@ Convert(DayOfWeek.Friday, Int64) DayOfWeek.Friday :> DayOfWeek DayOfWeek.Friday +####################################### +# Enum binary operators + +DayOfWeek.Friday - DayOfWeek.Monday +(Convert(DayOfWeek.Friday, Int32) - Convert(DayOfWeek.Monday, Int32)) + +DayOfWeek.Friday - 1 +Convert((Convert(DayOfWeek.Friday, Int32) - 1), DayOfWeek) + +DayOfWeek.Friday | 0 +Convert((Convert(DayOfWeek.Friday, Int32) | Convert(Convert(0, DayOfWeek), Int32)), DayOfWeek) + ####################################### # Conditional operator branches of different types diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index ed45d31..5012948 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -440,6 +440,60 @@ public void Parse_NullableOperandsWithoutOperatorInCSharp_ReturnsError(string ex Assert.That(result.ErrorMessage, Is.EqualTo(expected)); } + [TestCase("Day + ByteValue", typeof(DayOfWeek), DayOfWeek.Saturday)] + [TestCase("ShortValue + Day", typeof(DayOfWeek), DayOfWeek.Saturday)] + [TestCase("Day + CharValue", typeof(DayOfWeek), (DayOfWeek)102)] + [TestCase("Day - ByteValue", typeof(DayOfWeek), DayOfWeek.Thursday)] + [TestCase("ByteValue - Day", typeof(DayOfWeek), (DayOfWeek)(-4))] + [TestCase("Day - DayOfWeek.Monday", typeof(int), 4)] + [TestCase("Day - Day", typeof(int), 0)] + [TestCase("Day - 0", typeof(DayOfWeek), DayOfWeek.Friday)] + [TestCase("Day - 0L", typeof(int), 5)] + [TestCase("0 - Day", typeof(int), -5)] + [TestCase("Level + ByteValue", typeof(ByteLevel), ByteLevel.High)] + [TestCase("Level - NextLevel", typeof(byte), (byte)255)] + [TestCase("Level - 0", typeof(byte), (byte)1)] + [TestCase("NullableDay - DayOfWeek.Monday", typeof(int?), 4)] + [TestCase("NullDay - Day", typeof(int?), null)] + [TestCase("0 - NullableDay", typeof(int?), -5)] + [TestCase("NullableDay + NullableByteValue", typeof(DayOfWeek?), DayOfWeek.Saturday)] + [TestCase("NullableDay + null", typeof(DayOfWeek?), null)] + [TestCase("null + NullableDay", typeof(DayOfWeek?), null)] + [TestCase("NullableDay - null", typeof(int?), null)] + public void Evaluate_EnumAdditiveOperator_ReturnsTypeOfCSharp(string expression, Type type, object? expected) => + AssertResult(new EnumContext(), expression, type, expected); + + [TestCase("Day & 0", typeof(DayOfWeek), DayOfWeek.Sunday)] + [TestCase("0u | Day", typeof(DayOfWeek), DayOfWeek.Friday)] + [TestCase("Day ^ (0)", typeof(DayOfWeek), DayOfWeek.Friday)] + [TestCase("Level | 0", typeof(ByteLevel), ByteLevel.Low)] + [TestCase("NullableDay & 0L", typeof(DayOfWeek?), DayOfWeek.Sunday)] + [TestCase("Day == 0", typeof(bool), false)] + [TestCase("0x0 < Day", typeof(bool), true)] + [TestCase("Day != 0ul", typeof(bool), true)] + [TestCase("Level == 0", typeof(bool), false)] + [TestCase("NullableDay > 0", typeof(bool), true)] + [TestCase("NullDay == 0", typeof(bool), false)] + public void Evaluate_EnumAndZeroLiteral_ConvertsZeroToEnum(string expression, Type type, object? expected) => + AssertResult(new EnumContext(), expression, type, expected); + + [TestCase("Level + IntValue", "Operator '+' cannot be applied to operands of type 'Ramstack.Parsing.ExpressionParserTest+ByteLevel' and 'System.Int32'.")] + [TestCase("Day & ByteValue", "Operator '&' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Byte'.")] + [TestCase("Day == IntValue", "Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.")] + [TestCase("Day == Level", "Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'Ramstack.Parsing.ExpressionParserTest+ByteLevel'.")] + [TestCase("NullableDay * 2", "Operator '*' cannot be applied to operands of type 'System.Nullable`1[System.DayOfWeek]' and 'System.Int32'.")] + [TestCase("NullableDay >>> 1", "Operator '>>>' cannot be applied to operands of type 'System.Nullable`1[System.DayOfWeek]' and 'System.Int32'.")] + [TestCase("NullableDay + NullableDay", "Operator '+' cannot be applied to operands of type 'System.Nullable`1[System.DayOfWeek]' and 'System.Nullable`1[System.DayOfWeek]'.")] + [TestCase("NullableDay == 5", "Operator '==' cannot be applied to operands of type 'System.Nullable`1[System.DayOfWeek]' and 'System.Int32'.")] + public void Parse_EnumOperandsWithoutOperatorInCSharp_ReturnsError(string expression, string expected) + { + var parameter = Expression.Parameter(typeof(EnumContext), "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) { @@ -535,9 +589,12 @@ public void StringConcatTest(string source, string expected) Assert.That(result.ToString(), Is.EqualTo(expected)); } - private static void AssertNullableResult(string expression, Type type, object? expected) + private static void AssertNullableResult(string expression, Type type, object? expected) => + AssertResult(new NullableContext(), expression, type, expected); + + private static void AssertResult(TContext context, string expression, Type type, object? expected) { - var parameter = Expression.Parameter(typeof(NullableContext), "c"); + var parameter = Expression.Parameter(typeof(TContext), "c"); var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); Assert.That(result.Success, Is.True, result.ErrorMessage); @@ -547,7 +604,7 @@ private static void AssertNullableResult(string expression, Type type, object? e // 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()); + var value = Expression.Lambda>(body, parameter).Compile()(context); Assert.That(value, Is.EqualTo(expected)); Assert.That(value?.GetType(), Is.EqualTo(expected?.GetType())); @@ -780,6 +837,26 @@ public class NullableContext public DateTime Date { get; } = new DateTime(2020, 1, 1); } + public enum ByteLevel : byte + { + Low = 1, + High = 2 + } + + public class EnumContext + { + public DayOfWeek Day { get; } = DayOfWeek.Friday; + public DayOfWeek? NullableDay { get; } = DayOfWeek.Friday; + public DayOfWeek? NullDay { get; } + public ByteLevel Level { get; } = ByteLevel.Low; + public ByteLevel NextLevel { get; } = ByteLevel.High; + public byte ByteValue { get; } = 1; + public byte? NullableByteValue { get; } = 1; + public short ShortValue { get; } = 1; + public char CharValue { get; } = 'a'; + public int IntValue { get; } = 1; + } + public class ArrayContext { public int[] Numbers { get; } = [1, 2, 3];