refactor(compiler): 优化关键字方法分派逻辑

- 简化了关键字方法和扩展方法的检测流程
- 统一了接收器类型的获取方式
- 提取了重复的空值检查逻辑
- 改进了代码结构和可读性
- 为关键字扩展方法添加了测试用例
pull/1/head
韩天峰 3 months ago
parent 7a164aa8ee
commit a4ac86524c
  1. 21
      src/Php/CompilerBase.php
  2. 26
      tests/aot/keyword_extension/001.phpt

@ -5444,34 +5444,23 @@ class CompilerBase extends \PhpAot\Core\Translator
$magicMethod = false;
$method = $this->identifierToStr($expr->name, literal: true);
// to* conversion methods are language keywords — always dispatched directly
// keyword methods (to* builtins + __ extensions) — dispatched before type-specific logic
if ($this->isNamedMethod($expr->name)) {
$methodName = $expr->name->toString();
if (isset(self::KEYWORD_METHOD_MAP[$methodName])) {
if ($this->isVarExpr($expr->var)) {
$receiverType = $this->getVarType($object);
} else {
$receiverType = $this->detectTypeOfExpr($expr->var);
}
$receiverType = $this->isVarExpr($expr->var) ? $this->getVarType($object) : $this->detectTypeOfExpr($expr->var);
if ($receiverType === self::TYPE_VOID) {
$this->fatalError($expr->var, 'Cannot call method on void');
}
// to* builtins
if (isset(self::KEYWORD_METHOD_MAP[$methodName])) {
if ($methodName === 'toObject') {
return $this->genToObjectCall($expr, $object);
}
return $this->genToConvertCall($object, $methodName, $receiverType);
}
// keyword extension methods (__ functions) — dispatched before type-specific logic
// __ keyword extensions
$kwExt = $this->findKeywordExtensionMethod($methodName);
if ($kwExt) {
if ($this->isVarExpr($expr->var)) {
$receiverType = $this->getVarType($object);
} else {
$receiverType = $this->detectTypeOfExpr($expr->var);
}
if ($receiverType === self::TYPE_VOID) {
$this->fatalError($expr->var, 'Cannot call method on void');
}
return $this->parseUniversalMethodCall($expr, $object, $methodName, $kwExt, $this->isVarExpr($expr->var));
}
}

@ -0,0 +1,26 @@
--TEST--
keyword extension method: varDump()
--FILE--
<?php
declare(strict_types=1);
use native_types;
function __var_dump(mixed $var): void {
var_dump($var);
}
function main(): void {
$str = "hello world";
$str->varDump();
$int_val = 42;
$int_val->varDump();
$float_val = 3.14;
$float_val->varDump();
}
?>
--EXPECT--
string(11) "hello world"
int(42)
float(3.14)
Loading…
Cancel
Save