xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

Implement switch expressions #67

Closed thekid closed 5 years ago

thekid commented 5 years ago

Introduces => expr as (kind of) shorthand for : return expr like with short lambdas and compact functions, and makes switch an expression. The type tests borrow from the casting syntax.

Example

public function serialize($arg) {
  return switch ($arg) {
    case true     => 'b:1;';
    case false    => 'b:0;';
    case null     => 'N;';
    case (int)    => 'i:'.$arg.';';
    case (string) => 's:'.strlen($arg).'"'.$arg.'";';
    case (Date)   => '@:'.$arg->getTime().';';
    default       => throw new IllegalArgumentException('Unhandled '.typeof($arg));
  };
}

See https://blog.codefx.org/java/switch-expressions/

thekid commented 5 years ago

Alternative suggestion for type matching, which would go along the is infix operator as suggested in #68:

public function serialize($arg) {
  return switch ($arg) {
    case true      => 'b:1;';
    case false     => 'b:0;';
    case null      => 'N;';
    case is int    => 'i:'.$arg.';';
    case is string => 's:'.strlen($arg).'"'.$arg.'";';
    case is Date   => '@:'.$arg->getTime().';';
    default        => throw new IllegalArgumentException('Unhandled '.typeof($arg));
  };
}

See https://kotlinlang.org/docs/reference/control-flow.html#when-expression

thekid commented 5 years ago

Can be implemented as external plugin once #66 is merged - see https://github.com/xp-lang/php-switch-expression