From ae717c4b86affc2d831262e7f611b53595083461 Mon Sep 17 00:00:00 2001 From: yavon007 Date: Sat, 5 Sep 2026 12:46:50 +0800 Subject: [PATCH] fix(compiler): evaluate trailing empty switch cases --- src/Parser/SwitchTrait.php | 15 +++--- .../compiler/switch/trailing-empty-case.phpt | 49 +++++++++++++++++++ 2 files changed, 56 insertions(+), 8 deletions(-) create mode 100644 tests/compiler/switch/trailing-empty-case.phpt diff --git a/src/Parser/SwitchTrait.php b/src/Parser/SwitchTrait.php index 82441a67..e3521ef8 100644 --- a/src/Parser/SwitchTrait.php +++ b/src/Parser/SwitchTrait.php @@ -124,6 +124,13 @@ protected function parseSwitch(Node\Stmt\Switch_ $v): string $caseConds = []; $hasDefault = false; } + if (!empty($caseConds) || $hasDefault) { + $target = count($caseGroups); + if ($hasDefault) { + $defaultTarget = $target; + } + $caseGroups[] = [$caseConds, $hasDefault, []]; + } foreach ($caseGroups as $groupIndex => [$conds]) { if (!empty($conds)) { @@ -172,14 +179,6 @@ protected function parseSwitch(Node\Stmt\Switch_ $v): string $this->indentLevel--; $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--; $code .= $this->getIndent() . '} while (0);'; diff --git a/tests/compiler/switch/trailing-empty-case.phpt b/tests/compiler/switch/trailing-empty-case.phpt new file mode 100644 index 00000000..6c8c520e --- /dev/null +++ b/tests/compiler/switch/trailing-empty-case.phpt @@ -0,0 +1,49 @@ +--TEST-- +Switch evaluates and matches a trailing empty case +--FILE-- + +--EXPECT-- +evaluated:other +default +evaluated:subject +evaluated:first-miss +evaluated:subject +evaluated:default-miss