fix(compiler): 修复类型化参数默认值 helper 的运行时常量转换 #35

Merged
韩天峰 merged 3 commits from preprocessor-wrap-runtime-const-scalar-default into master 1 month ago
  1. 25
      src/Generator/DefaultArgumentGenerator.php
  2. 30
      tests/compiler/const/class-const-default-value-typed.phpt

@ -88,7 +88,8 @@ trait DefaultArgumentGenerator
$code .= 'return ' . $plan->expr . ';' . PHP_EOL;
}
} else {
$code .= 'return ' . $argInfo->default . ';' . PHP_EOL;
$default = $this->convertRuntimeConstantDefault($type, $argInfo->default);
$code .= 'return ' . $default . ';' . PHP_EOL;
}
$code .= '}' . PHP_EOL . PHP_EOL;
@ -98,6 +99,28 @@ trait DefaultArgumentGenerator
return $code;
}
/**
* Runtime constant lookup returns Variant, but a typed default helper must
* return its native C++ type explicitly. Convert the complete expression so
* constants nested in expressions are covered as well.
*/
private function convertRuntimeConstantDefault(string $type, string $default): string
{
if (!str_contains($default, 'php::constant(')) {
return $default;
}
return match ($type) {
Type::INT => 'php::toInt(' . $default . ')',
Type::FLOAT => 'php::toFloat(' . $default . ')',
Type::BOOL => 'php::toBool(' . $default . ')',
Type::STR => 'php::toString(' . $default . ')',
Type::ARRAY => 'php::toArray(' . $default . ')',
Type::OBJECT => 'php::toObject(' . $default . ')',
default => $default,
};
}
private function shouldGenerateDefaultArgumentHelper(ArgInfo $argInfo): bool
{
if ($argInfo->variadic) {

@ -0,0 +1,30 @@
--TEST--
Typed parameter default value from an unresolvable (external) class constant
--FILE--
<?php
class TypedDefault
{
public function run(
int $value = \ArrayObject::ARRAY_AS_PROPS,
float $floatValue = \ArrayObject::ARRAY_AS_PROPS,
string $format = \DateTime::ATOM,
int $composite = 1 | \ArrayObject::ARRAY_AS_PROPS,
mixed $variant = \ArrayObject::STD_PROP_LIST,
)
{
var_dump($value, $floatValue, $format, $composite, $variant);
}
}
function main()
{
(new TypedDefault)->run();
}
?>
--EXPECT--
int(2)
float(2)
string(13) "Y-m-d\TH:i:sP"
int(3)
int(1)
Loading…
Cancel
Save