fix(parser): 修复变量类型推断问题

- 当右侧表达式为无类型但左侧变量已有已知原生类型时,
  使用左侧类型进行转换以确保类型安全
- 在赋值操作中添加类型检查逻辑,避免类型丢失问题
- 更新 fibo 和 fibo_r 函数参数类型声明为 int
- 添加 issetor 性能测试用例以验证类型推断优化效果
pull/1/head
韩天峰 3 months ago
parent 5e549a4c15
commit c5f38a3d05
  1. 4
      examples/bench.php
  2. 15
      perf/issetor.php
  3. 11
      src/Php/Parser/AssignOpTrait.php

@ -179,11 +179,11 @@ function ary3($n) {
/****/
function fibo_r($n){
function fibo_r(int $n){
return(($n < 2) ? 1 : fibo_r($n - 2) + fibo_r($n - 1));
}
function fibo($n) {
function fibo(int $n) {
$r = fibo_r($n);
print "$r\n";
}

@ -0,0 +1,15 @@
<?php
function issetor(int $n)
{
$val = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
for ($i = 0; $i < $n; ++$i) {
$x = $val ?: null;
}
}
function main()
{
$s = microtime( true);
issetor(1000_0000);
echo microtime( true) - $s . "\n";
}

@ -252,6 +252,17 @@ trait AssignOpTrait
return $this->parseAssignArrayDim($left, $right);
}
// When the RHS is untyped (TYPE_VAR) but the LHS variable already has a known
// native type, use the LHS type for the conversion so that e.g.
// php::Int i; ... i = n; (n is php::Var)
// becomes i = php::toInt(n);
if ($finalVarType === self::TYPE_VAR && $this->hasVar($var)) {
$varType = $this->getVarType($var);
if ($varType !== self::TYPE_VAR) {
$finalVarType = $varType;
}
}
$rightExpr = $this->parseAssignRightExpr($right);
$leftExprType = $this->detectTypeOfExpr($left);
$rightExprType = $this->detectTypeOfExpr($right);

Loading…
Cancel
Save