kphp icon indicating copy to clipboard operation
kphp copied to clipboard

Exhaustive `constexpr` for `switch`

Open vkaverin opened this issue 1 year ago • 0 comments

constexpr for switch was supported in #727 and #770.

The problem

Consider following snippet

f(new Foo());

/**
 * @kphp-generic T
 * @param T $o
 */
function f($o) {
  switch (classof($foo)) {
    case Bar::class:
      // doing some work
      break;
    
    // No case for Foo::class.
    // No `default` too.
    // We have completely forgotten about Foo :(
  }
}

Now, trying to compile this code and... everything compiles just fine. For Foo we'll get following codegen:

  static_cast<void>(v$matched_with_one_case$ub9cfc05ca56516ed_0);
  do {
    v$condition_on_switch$ub9cfc05ca56516ed_0 = v$const_string$us2098c7d17029d8a0;
    v$matched_with_one_case$ub9cfc05ca56516ed_0 = false;
    {
    }
  } while(false);
  ;

That's it, this is basically "Do nothing for Foo::class". No errors, no warnings.

Solution

Require to cover all T in switch OR default branch, fail compilation otherwise (just like in Rust).

vkaverin avatar Mar 16 '23 11:03 vkaverin