feat(compiler): 添加变量重新赋值类型检查功能

- 实现了对变量重新赋值时的类型验证逻辑
- 当变量从一种类型重新赋值为另一种类型时抛出致命错误
- 添加了测试基类用于编译器测试
- 新增变量重新赋值的单元测试用例
- 在代码差异中检测到变量类型变化时触发错误处理
pull/1/head
韩天峰 5 months ago
parent 1a7bfe1de5
commit a1c922dac2
  1. 21
      phpunit/bootstrap.php
  2. 6
      phpunit/code/re-assign.php
  3. 9
      phpunit/src/AssignTest.php
  4. 8
      src/Php/CompilerBase.php

@ -1,4 +1,25 @@
<?php
use PHPUnit\Framework\TestCase;
use PhpAot\Php\CompilerTest;
use PhpAot\Php\Exception\TestError;
require __DIR__ . '/../bin/bootstrap.php';
class BaseTest extends TestCase
{
protected function exec(string $expected, string $file): void
{
try {
$compiler = CompilerTest::create(ROOT_PATH);
$testFile = __DIR__ . '/code/' . $file;
$compiler->addFiles([$testFile]);
$compiler->prepare($testFile);
$compiler->convert($testFile);
} catch (TestError $exception) {
$this->assertStringContainsString($expected, $exception->getMessage());
return;
}
$this->fail();
}
}

@ -0,0 +1,6 @@
<?php
function main()
{
$obj = new stdClass();
$obj = "hello world";
}

@ -0,0 +1,9 @@
<?php
class AssignTest extends \BaseTest
{
public function testReAssign()
{
$this->exec('Cannot re-assign variable', 're-assign.php');
}
}

@ -1368,10 +1368,18 @@ class CompilerBase extends \PhpAot\Core\Translator
return $var . ' = ' . $this->convertExprFromType($type, $expr);
}
}
} elseif ($this->isVarExpr($right)) {
$rightVar = $this->parseIdentifier($right);
if ($this->hasVar($rightVar) and $this->isTypedObject($rightVar)) {
$type = self::TYPE_OBJECT;
$this->addObject($var, $this->getObjectType($rightVar));
}
}
if (!$this->hasVar($var)) {
$this->addLocalVar($var, $type);
} else if ($this->getVarType($var) != $type) {
$this->fatalError($left, "Cannot re-assign variable `\${$var}` from " . $this->getVarType($var) . " to " . $type);
}
} elseif ($this->isPropertyFetch($left) and !$left->getAttribute('nativeProperty')) {
return $this->parseAssignPropertyFetch($left, $right);

Loading…
Cancel
Save