test(compiler): 添加空合并赋值操作符测试用例并优化编译逻辑

- 添加 assign_coalesce_002.phpt 测试文件验证空合并赋值功能
- 在 AstNodeType 中新增 isConstFetch 和 isAssignOp 辅助方法
- 优化 CompilerBase 中的空合并赋值编译逻辑,使用三元运算符替代 if 语句
- 修复局部变量检测和类型推断相关问题
pull/1/head
韩天峰 6 months ago
parent 7292635b3d
commit 34f157871d
  1. 10
      src/Php/AstNodeType.php
  2. 4
      src/Php/CompilerBase.php
  3. 39
      tests/aot/assign_coalesce_002.phpt

@ -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;
}
}

@ -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

@ -0,0 +1,39 @@
--TEST--
assign coalesce 002
--FILE--
<?php
function case1() {
$context = new ArrayObject();
$context['session'] = 'world';
return $context['session'] ??= 'hello';
}
function case2() {
$context = new ArrayObject();
return $context['session'] ??= 'hello';
}
function case3() {
$context = [];
$context['session'] = 'world';
return $context['session'] ??= 'hello';
}
function case4() {
$context = [];
return $context['session'] ??= 'hello';
}
function main() {
error_reporting(E_ERROR);
var_dump(case1());
var_dump(case2());
var_dump(case3());
var_dump(case4());
}
?>
--EXPECT--
string(5) "world"
string(5) "hello"
string(5) "world"
string(5) "hello"
Loading…
Cancel
Save