From a204ebf1e7c6c8894f45a63c9384874467c2e8d2 Mon Sep 17 00:00:00 2001 From: tianfenghan Date: Tue, 31 Mar 2026 13:06:03 +0800 Subject: [PATCH] =?UTF-8?q?feat(aot):=20=E6=94=B9=E8=BF=9Bswitch=E8=AF=AD?= =?UTF-8?q?=E5=8F=A5=E7=BC=96=E8=AF=91=E9=80=BB=E8=BE=91=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加了default分支的特殊处理逻辑 - 实现了defaultOnly标识用于优化条件判断 - 修正了switch case条件列表的构建方式 - 添加了对多个测试用例的支持验证 - 优化了分支条件的代码生成策略 - 确保了break语句后的正确流程控制 --- src/Php/CompilerBase.php | 14 +++++----- .../aot/{switch-001.phpt => switch/001.phpt} | 0 .../aot/{switch-002.phpt => switch/002.phpt} | 0 tests/aot/switch/003.phpt | 18 +++++++++++++ tests/aot/switch/004.phpt | 27 +++++++++++++++++++ 5 files changed, 53 insertions(+), 6 deletions(-) rename tests/aot/{switch-001.phpt => switch/001.phpt} (100%) rename tests/aot/{switch-002.phpt => switch/002.phpt} (100%) create mode 100644 tests/aot/switch/003.phpt create mode 100644 tests/aot/switch/004.phpt diff --git a/src/Php/CompilerBase.php b/src/Php/CompilerBase.php index 3bd7252d..52c88080 100644 --- a/src/Php/CompilerBase.php +++ b/src/Php/CompilerBase.php @@ -3398,11 +3398,11 @@ class CompilerBase extends \PhpAot\Core\Translator $code = 'do {' . PHP_EOL; $this->indentLevel++; $condList = []; + $defaultCase = false; + $defaultOnly = true; foreach ($v->cases as $case) { if (empty($case->cond)) { - if ($condList) { - $this->fatalError($case, 'switch case must be first'); - } + $defaultCase = true; } else { $condList[] = $tmp_var . '==' . $this->parseIdentifier($case->cond); } @@ -3423,11 +3423,13 @@ class CompilerBase extends \PhpAot\Core\Translator $this->fatalError($case, 'switch case must end with return/break/exit/throw, ' . $lastExpr->getType() . ' given'); } - if ($condList) { + if ($defaultCase) { + $else = $defaultOnly ? '' : 'else'; + $code .= $this->getIndent() . $else . ' {' . PHP_EOL; + } else { $code .= $this->getIndent() . 'if (' . implode(' || ', $condList) . ') {' . PHP_EOL; + $defaultOnly = false; $condList = []; - } else { - $code .= $this->getIndent() . 'else {' . PHP_EOL; } $code .= $this->parseStmts($stmts); diff --git a/tests/aot/switch-001.phpt b/tests/aot/switch/001.phpt similarity index 100% rename from tests/aot/switch-001.phpt rename to tests/aot/switch/001.phpt diff --git a/tests/aot/switch-002.phpt b/tests/aot/switch/002.phpt similarity index 100% rename from tests/aot/switch-002.phpt rename to tests/aot/switch/002.phpt diff --git a/tests/aot/switch/003.phpt b/tests/aot/switch/003.phpt new file mode 100644 index 00000000..ccdff2fb --- /dev/null +++ b/tests/aot/switch/003.phpt @@ -0,0 +1,18 @@ +--TEST-- +switch +--FILE-- + +--EXPECT-- +default diff --git a/tests/aot/switch/004.phpt b/tests/aot/switch/004.phpt new file mode 100644 index 00000000..34d3a2d9 --- /dev/null +++ b/tests/aot/switch/004.phpt @@ -0,0 +1,27 @@ +--TEST-- +switch +--FILE-- + +--EXPECT-- +case 1 +default