dadhi / FastExpressionCompiler

Fast Compiler for C# Expression Trees and the lightweight LightExpression alternative. Diagnostic and code generation tools for the expressions.
MIT License
1.16k stars 82 forks source link

Expression.Switch without a default case incorrectly calls first case for unmatched values. #428

Open bfarmer67 opened 1 day ago

bfarmer67 commented 1 day ago

I found an issue with switch expressions that I wanted to report.

When Expression.Switch is created without a default case, the first case expression is being incorrectly called as a default.

   var number = Expression.Parameter(typeof(int), "number");
   var writeLineMethod = typeof(Console).GetMethod("WriteLine", new[] { typeof(string) });

   var switchExpr = Expression.Switch(
      number,
      new SwitchCase[]
      {
         Expression.SwitchCase( Expression.Call(null, writeLineMethod, Expression.Constant("Case 1")), Expression.Constant(1)),
         Expression.SwitchCase( Expression.Call(null, writeLineMethod, Expression.Constant("Case 2")), Expression.Constant(2))
      }
    );

    var lambda = Expression.Lambda<Action<int>>(switchExpr, number);
    var action = (Action<int>) lambda.CompileFast();

    action(3); // RETURNS "Case 1" - should do nothing.

If you explicitly pass Expression.Empty() for the default case, the switch behaves correctly. If you pass null for the default case, you also see the error.

Here is a dotnetfiddle that reproduces the issue https://dotnetfiddle.net/7xKCTF

Thank you again for your library.

dadhi commented 1 day ago

@bfarmer67 Thanks for reporting and the example. I will check.