diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs index cbcf7f9..c8ba6fb 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs @@ -287,23 +287,18 @@ private static Expression ApplyBinaryExpression(Identifier op, Func>" or ">>>" or "<<") { - if (!TypeUtils.IsInteger(lhs.Type) && TypeUtils.IsInteger(rhs.Type)) - Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type); - - if (rhs.Type == typeof(sbyte) - || rhs.Type == typeof(byte) - || rhs.Type == typeof(short) - || rhs.Type == typeof(ushort)) - rhs = Expression.Convert(rhs, typeof(int)); + // + // The predefined shift operators take an int, uint, long, or ulong value and an int count, + // so an operand of a smaller integral type, including char, is converted to int, as in C#. + // + var lhsType = lhs.Type; + var rhsType = rhs.Type; - if (rhs.Type != typeof(int)) - Error.NonApplicableBinaryOperator(op, lhs.Type, rhs.Type); + lhs = ApplyUnaryNumericPromotion(lhs); + rhs = ApplyUnaryNumericPromotion(rhs); - if (lhs.Type == typeof(sbyte) - || lhs.Type == typeof(byte) - || lhs.Type == typeof(short) - || lhs.Type == typeof(ushort)) - lhs = Expression.Convert(lhs, typeof(int)); + if (!TypeUtils.IsInteger(lhs.Type) || rhs.Type != typeof(int)) + Error.NonApplicableBinaryOperator(op, lhsType, rhsType); if (op.Name == ">>>") { @@ -344,6 +339,26 @@ private static Expression ApplyBinaryExpression(Identifier op, Func> 1 +Operator '>>' cannot be applied to operands of type 'System.Double' and 'System.Int32'. + +1m >>> 1 +Operator '>>>' cannot be applied to operands of type 'System.Decimal' and 'System.Int32'. + ####################################### # Conditional operator branches without a common type diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index e657ab3..6000cd7 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -134,6 +134,16 @@ public void EvaluateExpression(string expression, object result) => public void Evaluate_NegatedUInt32_ReturnsNegatedInt64(string expression, long expected) => Assert.That(ExpressionParser.Evaluate(expression), Is.TypeOf().And.EqualTo(expected)); + [TestCase("-'a'", -97)] + [TestCase("+'a'", 97)] + [TestCase("~'a'", -98)] + [TestCase("'a' << 1", 194)] + [TestCase("'a' >> 1", 48)] + [TestCase("'a' >>> 1", 48)] + [TestCase("1 << 'a'", 2)] + public void Evaluate_CharOperand_PromotesToInt32(string expression, int expected) => + Assert.That(ExpressionParser.Evaluate(expression), Is.TypeOf().And.EqualTo(expected)); + [TestCase("Sum(Numbers)", 6)] [TestCase("Count(Words)", 2)] [TestCase("IsWords(Words)", true)]