Skip to content

Commit 9cc3647

Browse files
authored
Merge pull request #31 from rameel/parser/enum-binary-operators
parser: apply the C# rules to binary operators on enums
2 parents 8aad428 + 89bd153 commit 9cc3647

5 files changed

Lines changed: 282 additions & 28 deletions

File tree

‎src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs‎

Lines changed: 122 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,78 @@ private static bool IsNullLiteral(Expr expr)
207207
return expr is Expr.Literal { Value: null };
208208
}
209209

210+
/// <summary>
211+
/// Determines whether the specified expression is the integer literal 0, possibly in parentheses.
212+
/// </summary>
213+
/// <param name="expr">The expression to test.</param>
214+
/// <returns>
215+
/// <see langword="true" /> if the expression is the integer literal 0; otherwise, <see langword="false" />.
216+
/// </returns>
217+
private static bool IsZeroLiteral(Expr expr)
218+
{
219+
while (expr is Expr.Parenthesized parenthesized)
220+
expr = parenthesized.Expression;
221+
222+
return expr is Expr.Literal { Value: 0 or 0u or 0L or 0UL };
223+
}
224+
225+
/// <summary>
226+
/// Converts the integer literal 0 opposite an operand of an enum type to that enum type
227+
/// if the operator is defined for two operands of the enum type.
228+
/// </summary>
229+
/// <param name="expr">The binary expression.</param>
230+
/// <param name="lhs">The expression of the left operand.</param>
231+
/// <param name="rhs">The expression of the right operand.</param>
232+
private static void ApplyEnumZeroConversion(Expr.Binary expr, ref Expression lhs, ref Expression rhs)
233+
{
234+
//
235+
// 10.2.4 Implicit enumeration conversions
236+
// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#1024-implicit-enumeration-conversions
237+
//
238+
// An implicit enumeration conversion permits a constant expression with any integer type and the value zero
239+
// to be converted to any enum type and to any nullable value type whose underlying type is an enum type.
240+
//
241+
// Of such constant expressions, only the integer literal 0 is recognized.
242+
//
243+
switch (expr.Operator.Name)
244+
{
245+
case "-":
246+
case "&":
247+
case "|":
248+
case "^":
249+
case "==":
250+
case "!=":
251+
case "<":
252+
case ">":
253+
case "<=":
254+
case ">=":
255+
break;
256+
257+
default:
258+
return;
259+
}
260+
261+
var lhsType = lhs.Type.GetNonNullableType();
262+
var rhsType = rhs.Type.GetNonNullableType();
263+
264+
if (lhsType.IsEnum && IsZeroLiteral(expr.Right))
265+
{
266+
//
267+
// Both E - E and E - U accept 'x - 0'. As in the C# compiler, E - U is selected and returns E
268+
// if the literal is of the underlying type U; otherwise, E - E is selected and returns U, as in 'x - 0L'.
269+
//
270+
if (expr.Operator.Name != "-" || rhsType != lhsType.GetEnumUnderlyingType())
271+
rhs = Expression.Convert(rhs, lhsType);
272+
}
273+
else if (rhsType.IsEnum && IsZeroLiteral(expr.Left))
274+
{
275+
//
276+
// As in the C# compiler, E - E is selected for '0 - x' over U - E, so the result is of the underlying type.
277+
//
278+
lhs = Expression.Convert(lhs, rhsType);
279+
}
280+
}
281+
210282
/// <summary>
211283
/// Applies an implicit conversion of a branch of a conditional expression to the type of the other branch.
212284
/// </summary>
@@ -365,22 +437,65 @@ private static Expression ApplyBinaryExpression(Identifier op, Func<Expression,
365437
? rhsNonNullableType
366438
: null;
367439

440+
//
441+
// The type to which the result of an enum operator is converted. It remains null for an enum comparison,
442+
// whose result is bool, and if neither operand is of an enum type.
443+
//
444+
Type? enumResultType = null;
445+
368446
if (enumType is not null)
369447
{
448+
//
449+
// 12.10.5 Addition operator, 12.10.6 Subtraction operator, 12.12.6 Enumeration comparison operators,
450+
// and 12.13.3 Enumeration logical operators
451+
// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#12105-addition-operator
452+
//
453+
// Every enum type E with the underlying type U implicitly provides the following operators:
454+
//
455+
// E operator +(E x, U y);
456+
// E operator +(U x, E y);
457+
// U operator -(E x, E y);
458+
// E operator -(E x, U y);
459+
// E operator &(E x, E y); and likewise |, ^
460+
// bool operator ==(E x, E y); and likewise !=, <, >, <=, >=
461+
//
462+
// Each operator is evaluated on the values converted to U, as in (E)((U)x + (U)y).
463+
// The C# compiler also accepts U - E and returns E, so it is supported as well.
464+
//
370465
var enumUnderlyingType = enumType.GetEnumUnderlyingType();
466+
var otherType = lhsNonNullableType.IsEnum ? rhsNonNullableType : lhsNonNullableType;
467+
468+
var isEnumPair = lhsNonNullableType == rhsNonNullableType;
469+
var isUnderlyingPair = otherType == enumUnderlyingType
470+
|| TypeUtils.CanConvertPrimitive(otherType, enumUnderlyingType);
471+
472+
switch (op.Name)
473+
{
474+
case "+" when isUnderlyingPair:
475+
case "-" when isUnderlyingPair:
476+
case "&" or "|" or "^" when isEnumPair:
477+
enumResultType = enumType;
478+
break;
371479

372-
if (lhsNonNullableType != rhsNonNullableType)
373-
if (lhsNonNullableType.IsEnum ? enumUnderlyingType != rhsNonNullableType : enumUnderlyingType != lhsNonNullableType)
480+
case "-" when isEnumPair:
481+
enumResultType = enumUnderlyingType;
482+
break;
483+
484+
case "==" or "!=" or "<" or ">" or "<=" or ">=" when isEnumPair:
485+
break;
486+
487+
default:
374488
Error.NonApplicableBinaryOperator(op, lhsType, rhsType);
489+
break;
490+
}
375491

376492
if (lhsNonNullableType.IsEnum)
377493
lhs = ConvertOperand(lhs, enumUnderlyingType, lifted);
378494

379495
if (rhsNonNullableType.IsEnum)
380496
rhs = ConvertOperand(rhs, enumUnderlyingType, lifted);
381497
}
382-
383-
if (enumType is null && op.Name is ">>" or ">>>" or "<<")
498+
else if (op.Name is ">>" or ">>>" or "<<")
384499
{
385500
//
386501
// 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<Expression,
428543

429544
var result = apply(lhs, rhs);
430545

431-
if (enumType is not null)
432-
{
433-
switch (op.Name)
434-
{
435-
case "==":
436-
case "!=":
437-
case ">":
438-
case "<":
439-
case ">=":
440-
case "<=":
441-
return result;
442-
443-
default:
444-
return ConvertOperand(result, enumType, lifted);
445-
}
446-
}
447-
448-
return result;
546+
return enumResultType is not null
547+
? ConvertOperand(result, enumResultType, lifted)
548+
: result;
449549
}
450550

451551
/// <summary>

‎src/Ramstack.ExpressionParser/ExpressionBuilder.cs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,15 @@ protected internal override Expression VisitBinary(Expr.Binary expr)
5555

5656
//
5757
// The null literal converts to a nullable value type, so opposite an operand of such a type
58-
// it takes that type, as in 'x == null' or 'x ?? null'.
58+
// it takes that type, as in 'x == null' or 'x ?? null'. For an enum type E, only E + U and U + E
59+
// are defined, so in 'x + null' it takes the nullable form of the underlying type U instead.
5960
//
6061
if (lhsType.IsNullable() && IsNullLiteral(expr.Right))
61-
rhs = Expression.Constant(null, lhsType);
62+
rhs = Expression.Constant(null, GetNullLiteralType(expr.Operator, lhsType));
6263
else if (rhsType.IsNullable() && IsNullLiteral(expr.Left))
63-
lhs = Expression.Constant(null, rhsType);
64+
lhs = Expression.Constant(null, GetNullLiteralType(expr.Operator, rhsType));
65+
66+
ApplyEnumZeroConversion(expr, ref lhs, ref rhs);
6467

6568
var factory = ResolveBinaryOperatorFactory(expr.Operator.Name);
6669

@@ -168,6 +171,11 @@ void Flatten(Expression e)
168171
}
169172

170173
return null!;
174+
175+
static Type GetNullLiteralType(Identifier op, Type operandType) =>
176+
op.Name == "+" && operandType.GetNonNullableType() is { IsEnum: true } enumType
177+
? enumType.GetEnumUnderlyingType().MakeNullableType()
178+
: operandType;
171179
}
172180

173181
/// <inheritdoc />

‎tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,63 @@ Operator '>>' cannot be applied to operands of type 'System.Double' and 'System.
179179
1m >>> 1
180180
Operator '>>>' cannot be applied to operands of type 'System.Decimal' and 'System.Int32'.
181181

182+
#######################################
183+
# Binary operators not defined for enum operands
184+
185+
DayOfWeek.Friday * 2
186+
Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
187+
188+
DayOfWeek.Friday / 2
189+
Operator '/' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
190+
191+
DayOfWeek.Friday % 2
192+
Operator '%' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
193+
194+
DayOfWeek.Friday * 0
195+
Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
196+
197+
DayOfWeek.Friday * DayOfWeek.Monday
198+
Operator '*' cannot be applied to operands of type 'System.DayOfWeek' and 'System.DayOfWeek'.
199+
200+
DayOfWeek.Friday << 1
201+
Operator '<<' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
202+
203+
1 << DayOfWeek.Friday
204+
Operator '<<' cannot be applied to operands of type 'System.Int32' and 'System.DayOfWeek'.
205+
206+
DayOfWeek.Friday >> 1
207+
Operator '>>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
208+
209+
DayOfWeek.Friday >>> 1
210+
Operator '>>>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
211+
212+
DayOfWeek.Friday + DayOfWeek.Monday
213+
Operator '+' cannot be applied to operands of type 'System.DayOfWeek' and 'System.DayOfWeek'.
214+
215+
DayOfWeek.Friday + 1L
216+
Operator '+' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int64'.
217+
218+
DayOfWeek.Friday & 1
219+
Operator '&' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
220+
221+
DayOfWeek.Friday | 1
222+
Operator '|' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
223+
224+
1 ^ DayOfWeek.Friday
225+
Operator '^' cannot be applied to operands of type 'System.Int32' and 'System.DayOfWeek'.
226+
227+
DayOfWeek.Friday == 5
228+
Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
229+
230+
DayOfWeek.Friday > 1
231+
Operator '>' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Int32'.
232+
233+
DayOfWeek.Friday == 0.0
234+
Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.Double'.
235+
236+
DayOfWeek.Friday == StringSplitOptions.None
237+
Operator '==' cannot be applied to operands of type 'System.DayOfWeek' and 'System.StringSplitOptions'.
238+
182239
#######################################
183240
# Conditional operator branches without a common type
184241

‎tests/Ramstack.ExpressionParser.Tests/Data/Expressions.txt‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,18 @@ Convert(DayOfWeek.Friday, Int64)
519519
DayOfWeek.Friday :> DayOfWeek
520520
DayOfWeek.Friday
521521

522+
#######################################
523+
# Enum binary operators
524+
525+
DayOfWeek.Friday - DayOfWeek.Monday
526+
(Convert(DayOfWeek.Friday, Int32) - Convert(DayOfWeek.Monday, Int32))
527+
528+
DayOfWeek.Friday - 1
529+
Convert((Convert(DayOfWeek.Friday, Int32) - 1), DayOfWeek)
530+
531+
DayOfWeek.Friday | 0
532+
Convert((Convert(DayOfWeek.Friday, Int32) | Convert(Convert(0, DayOfWeek), Int32)), DayOfWeek)
533+
522534
#######################################
523535
# Conditional operator branches of different types
524536

0 commit comments

Comments
 (0)