From 34f157871daf34365f7f856401f0dec6c46f0192 Mon Sep 17 00:00:00 2001 From: tianfenghan Date: Sat, 28 Feb 2026 13:05:39 +0800 Subject: [PATCH] =?UTF-8?q?test(compiler):=20=E6=B7=BB=E5=8A=A0=E7=A9=BA?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E8=B5=8B=E5=80=BC=E6=93=8D=E4=BD=9C=E7=AC=A6?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B=E5=B9=B6=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 assign_coalesce_002.phpt 测试文件验证空合并赋值功能 - 在 AstNodeType 中新增 isConstFetch 和 isAssignOp 辅助方法 - 优化 CompilerBase 中的空合并赋值编译逻辑,使用三元运算符替代 if 语句 - 修复局部变量检测和类型推断相关问题 --- src/Php/AstNodeType.php | 10 ++++++++ src/Php/CompilerBase.php | 4 +-- tests/aot/assign_coalesce_002.phpt | 39 ++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 tests/aot/assign_coalesce_002.phpt diff --git a/src/Php/AstNodeType.php b/src/Php/AstNodeType.php index a8801385..c33204b3 100644 --- a/src/Php/AstNodeType.php +++ b/src/Php/AstNodeType.php @@ -78,4 +78,14 @@ trait AstNodeType { return $expr instanceof Expr\Match_; } + + protected function isConstFetch(NodeAbstract $expr): bool + { + return $expr instanceof Expr\ConstFetch; + } + + protected function isAssignOp(NodeAbstract $expr): bool + { + return $expr instanceof Node\Expr\AssignOp or $expr instanceof Node\Expr\Assign; + } } diff --git a/src/Php/CompilerBase.php b/src/Php/CompilerBase.php index 65ff247f..4f2980a0 100644 --- a/src/Php/CompilerBase.php +++ b/src/Php/CompilerBase.php @@ -3864,9 +3864,7 @@ class CompilerBase extends \PhpAot\Core\Translator if ($this->isVarExpr($expr->var) and !$this->hasVar($var)) { $this->addLocalVar($var, $this->detectExprType($expr->expr)); } - return 'if (!' . $isset . ') {' . PHP_EOL . - $this->getIndent() . $var . ' = ' . $right . ';' . PHP_EOL . - '}' . PHP_EOL; + return '(' . $isset . '?' . $var . ':(' . $var . ' = ' . $right . '))'; } protected function isReturnStmtInLastLine(array $stmts): bool diff --git a/tests/aot/assign_coalesce_002.phpt b/tests/aot/assign_coalesce_002.phpt new file mode 100644 index 00000000..2b4af19a --- /dev/null +++ b/tests/aot/assign_coalesce_002.phpt @@ -0,0 +1,39 @@ +--TEST-- +assign coalesce 002 +--FILE-- + +--EXPECT-- +string(5) "world" +string(5) "hello" +string(5) "world" +string(5) "hello"