fix(compiler): evaluate trailing empty switch cases (#90)

master
yavon007 1 month ago committed by GitHub
parent 6aae5f76d2
commit 42846579b7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 15
      src/Parser/SwitchTrait.php
  2. 49
      tests/compiler/switch/trailing-empty-case.phpt

@ -124,6 +124,13 @@ trait SwitchTrait
$caseConds = []; $caseConds = [];
$hasDefault = false; $hasDefault = false;
} }
if (!empty($caseConds) || $hasDefault) {
$target = count($caseGroups);
if ($hasDefault) {
$defaultTarget = $target;
}
$caseGroups[] = [$caseConds, $hasDefault, []];
}
foreach ($caseGroups as $groupIndex => [$conds]) { foreach ($caseGroups as $groupIndex => [$conds]) {
if (!empty($conds)) { if (!empty($conds)) {
@ -172,14 +179,6 @@ trait SwitchTrait
$this->indentLevel--; $this->indentLevel--;
$code .= $this->getIndent() . '}' . PHP_EOL; $code .= $this->getIndent() . '}' . PHP_EOL;
} }
if (!empty($caseConds) || $hasDefault) {
// PHP allows a trailing label without statements; it has no code to execute.
if ($hasDefault && $defaultTarget === null) {
$code .= $this->getIndent() . 'if (!' . $switchMatched . ') {' . PHP_EOL;
$code .= $this->getIndent() . $switchTarget . ' = -1;' . PHP_EOL;
$code .= $this->getIndent() . '}' . PHP_EOL;
}
}
$this->indentLevel--; $this->indentLevel--;
$code .= $this->getIndent() . '} while (0);'; $code .= $this->getIndent() . '} while (0);';

@ -0,0 +1,49 @@
--TEST--
Switch evaluates and matches a trailing empty case
--FILE--
<?php
function mark(string $value): string
{
echo "evaluated:$value\n";
return $value;
}
function main(): void
{
switch ('subject') {
default:
echo "default\n";
break;
case mark('other'):
}
switch ('subject') {
default:
echo "default\n";
break;
case mark('subject'):
}
switch ('subject') {
default:
echo "unexpected-default\n";
break;
case mark('first-miss'):
case mark('subject'):
}
switch ('subject') {
case mark('default-miss'):
echo "unexpected-case\n";
break;
default:
}
}
?>
--EXPECT--
evaluated:other
default
evaluated:subject
evaluated:first-miss
evaluated:subject
evaluated:default-miss
Loading…
Cancel
Save