Merge pull request 'fix(compiler): 修复类常量继承重写及类型推断' (#27) from fix-class-const into master

Reviewed-on: #27
pull/34/head
韩天峰 1 month ago
commit 092fb77c38
  1. 13
      phpunit/code/inheritance_error_const_final.php
  2. 13
      phpunit/code/inheritance_error_const_missing_type.php
  3. 10
      phpunit/src/InheritanceErrorTest.php
  4. 2
      src/Entity/ConstantDef.php
  5. 9
      src/Parser/ClassConstantFetchTrait.php
  6. 71
      src/Preprocessor.php
  7. 10
      src/Resolver/ClassConstantValueTrait.php
  8. 33
      src/Translator.php
  9. 41
      src/gen_stub.php
  10. 51
      tests/compiler/const/class-const-override-variants.phpt
  11. 30
      tests/compiler/const/class-const-override.phpt
  12. 43
      tests/compiler/const/class-const-parent-cross-ns.phpt

@ -0,0 +1,13 @@
<?php
class FinalConstantParent
{
final public const VALUE = 1;
}
class FinalConstantChild extends FinalConstantParent
{
public const VALUE = 2;
}
function main() {}

@ -0,0 +1,13 @@
<?php
class TypedConstantParent
{
public const int VALUE = 1;
}
class UntypedConstantChild extends TypedConstantParent
{
public const VALUE = 1;
}
function main() {}

@ -168,6 +168,16 @@ class InheritanceErrorTest extends TestCase
$this->exec('must be compatible', 'inheritance_error_const_type.php');
}
public function testTypedConstantCannotBeOverriddenWithoutDeclaredType()
{
$this->exec('must be compatible', 'inheritance_error_const_missing_type.php');
}
public function testFinalConstantCannotBeOverridden()
{
$this->exec('Cannot override final constant', 'inheritance_error_const_final.php');
}
public function testConstantVisibilityMismatch()
{
$this->exec('must be compatible', 'inheritance_error_const_visibility.php');

@ -19,6 +19,8 @@ class ConstantDef
public string $arrayExpr = '';
public string $class = '';
public ?NodeAbstract $valueExpr = null;
/** Explicit declared type (e.g. `const int FOO`); null for inferred/untyped constants. */
public ?string $declaredType = null;
public function __construct(string $name, int $flags, string $type, string $value)
{

@ -31,6 +31,14 @@ trait ClassConstantFetchTrait
$self = true;
$class = $this->class;
}
} elseif ($class === 'parent') {
if (!$this->classDef || !$this->classDef->extends) {
$this->fatalError($expr, 'Cannot use "parent" outside a class or class does not extend any class');
}
// extends is already fully resolved. Keep the leading slash so the
// current namespace is not applied again below.
$class = '\\' . $this->classDef->extends;
$self = true;
}
$const = $this->escapeString($this->parseIdentifier($expr->name));
@ -98,4 +106,3 @@ trait ClassConstantFetchTrait
}
}

@ -757,24 +757,89 @@ class Preprocessor extends CompilerBase
'Scalar_String' => Type::STR,
default => Type::VAR,
};
// `::class` is a compile-time magic constant that always yields a string,
// so a constant declared as `X = self::class` (or `Foo::class`) must be
// typed as a string rather than a generic variant.
if ($type === Type::VAR
&& $const->value instanceof Node\Expr\ClassConstFetch
&& strtolower((string) $const->value->name) === 'class') {
$type = Type::STR;
}
// A constant whose value references another class constant
// (e.g. `X = ParentClass::Y` or `X = self::Y`) must take the referenced
// constant's type. This keeps override compatibility checks and the C++
// declaration correct, mirroring PHP where overriding an untyped constant
// with a value of any (compatible) type is allowed.
if ($type === Type::VAR
&& $const->value instanceof Node\Expr\ClassConstFetch
&& $const->value->class instanceof Node\Name) {
$refType = $this->resolveReferencedConstantType($const->value, $this->getFullClassName());
if ($refType !== null) {
$type = $refType;
}
}
}
$constName = $this->parseIdentifier($const->name);
if ($this->classDef->hasConstant($constName)) {
$this->fatalError($v, "Duplicate constant `{$constName}`");
}
$constInfo = $this->parseClassLikeConstant($const, $flags, $type, $class);
$constInfo = $this->parseClassLikeConstant($const, $flags, $type, $class, $declaredType);
$constInfo->class = $class;
$this->classDef->constants[$constInfo->name] = $constInfo;
}
}
private function parseClassLikeConstant(Node\Const_ $const, int $flags, string $type, string $class = ''): ConstantDef
/**
* Resolve the compile-time type of a class constant whose value is a
* `ClassConstFetch` referencing another constant (e.g. `X = ParentClass::Y`
* or `X = self::Y`). Returns the referenced constant's type, or null when
* the reference cannot be resolved yet (for instance when the referenced
* class has not been prepared). `::class` always resolves to a string.
*/
private function resolveReferencedConstantType(Node\Expr\ClassConstFetch $fetch, string $currentClass): ?string
{
$constName = $fetch->name->toString();
if (strcasecmp($constName, 'class') === 0) {
return Type::STR;
}
if (!($fetch->class instanceof Node\Name)) {
return null;
}
$className = $fetch->class->toString();
if (strcasecmp($className, 'self') === 0 || strcasecmp($className, 'static') === 0) {
$targetClass = $currentClass;
} elseif (strcasecmp($className, 'parent') === 0) {
$targetClass = $this->getParentClass($currentClass);
} else {
$targetClass = $this->getNamespacedClassName($className);
}
if ($targetClass === '' || !$this->hasClass($targetClass)) {
return null;
}
$def = $this->getClass($targetClass);
if (!$def->hasConstant($constName)) {
return null;
}
$refConst = $def->getConstant($constName);
// Follow the chain in case the referenced constant is itself an
// expression that resolves to another constant.
if ($refConst->type !== Type::VAR) {
return $refConst->type;
}
if ($refConst->valueExpr instanceof Node\Expr\ClassConstFetch) {
return $this->resolveReferencedConstantType($refConst->valueExpr, $targetClass);
}
return null;
}
private function parseClassLikeConstant(Node\Const_ $const, int $flags, string $type, string $class = '', ?string $declaredType = null): ConstantDef
{
$constName = $this->parseIdentifier($const->name);
$constValue = $this->parseIdentifier($const->value);
$constInfo = new ConstantDef($constName, $flags, $type, $constValue);
$constInfo->valueExpr = $const->value;
$constInfo->declaredType = $declaredType;
if ($this->context->beforeStmtLines) {
$arrayExpr = '';
@ -979,7 +1044,7 @@ class Preprocessor extends CompilerBase
default => Type::VAR,
};
}
$constInfo = $this->parseClassLikeConstant($const, $this->parseModifiers($stmt->flags), $type, $class);
$constInfo = $this->parseClassLikeConstant($const, $this->parseModifiers($stmt->flags), $type, $class, $stmt->type ? $type : null);
$this->interfaceDef->constants[$constName] = $constInfo;
}
continue;

@ -116,6 +116,16 @@ trait ClassConstantValueTrait
if ($expr instanceof Node\Expr\ClassConstFetch && $expr->class instanceof Node\Name) {
$constName = $expr->name->toString();
$className = $expr->class->toString();
if (strcasecmp($constName, 'class') === 0) {
// `::class` is a compile-time magic constant that resolves to the
// fully qualified class name of the referenced class.
if (strcasecmp($className, 'self') === 0 || strcasecmp($className, 'static') === 0) {
$className = $class;
} elseif (strcasecmp($className, 'parent') === 0) {
$className = $this->getParentClass($class);
}
return ltrim($this->getNamespacedClassName($className, $this->getNamespaceOfClass($class)), '\\');
}
if (strcasecmp($className, 'self') === 0) {
$className = $class;
} elseif (strcasecmp($className, 'parent') === 0) {

@ -3478,10 +3478,37 @@ CODE;
if ($parentConst->flags & Modifiers::PRIVATE) {
continue;
}
if ($childConst->type !== $parentConst->type || $childConst->class !== $parentConst->class) {
if ($parentConst->flags & Modifiers::FINAL) {
$this->fatalError($classStmt,
"Declaration of `{$className}::{$name}` must be compatible " .
"with `{$parentClass}::{$name}`");
"Cannot override final constant `{$parentClass}::{$name}`");
}
// PHP only enforces type compatibility when the parent constant
// carries an explicit declared type. Overriding an untyped constant
// with a value of any type is permitted, so the type check is skipped
// in that case. Visibility is always enforced below.
if ($parentConst->declaredType !== null) {
if ($childConst->declaredType === null) {
$this->fatalError($classStmt,
"Declaration of `{$className}::{$name}` must be compatible " .
"with `{$parentClass}::{$name}`");
}
// An untyped child constant whose value is an expression (e.g.
// `X = ParentClass::Y`) is inferred as a variant. Resolve its real
// type from the referenced constant so the compatibility check uses
// the actual value type.
$childType = $childConst->type;
if ($childType === Type::VAR
&& $childConst->valueExpr instanceof Node\Expr\ClassConstFetch) {
$resolved = $this->resolveReferencedConstantType($childConst->valueExpr, $this->getFullClassName());
if ($resolved !== null) {
$childType = $resolved;
}
}
if ($childType !== $parentConst->type || $childConst->class !== $parentConst->class) {
$this->fatalError($classStmt,
"Declaration of `{$className}::{$name}` must be compatible " .
"with `{$parentClass}::{$name}`");
}
}
if ($this->getVisibilityRank($childConst->flags) < $this->getVisibilityRank($parentConst->flags)) {
$this->fatalError($classStmt,

@ -2354,18 +2354,29 @@ class EvaluatedValue
}
if ($expr instanceof Expr\ClassConstFetch) {
$constName = $expr->name->__toString();
if (strcasecmp($constName, 'class') === 0) {
// `::class` is a compile-time magic constant that resolves to the
// fully qualified class name of the referenced class.
$className = getClassConstFetchClassName($expr);
if (strcasecmp($className, 'self') === 0 || strcasecmp($className, 'static') === 0) {
return ClassInfo::$currentClass;
}
if (strcasecmp($className, 'parent') === 0) {
return getTranslator()->getParentClass(ClassInfo::$currentClass);
}
return ltrim($className, '\\');
}
$class = getClassConstFetchClassName($expr);
if ($class === 'self') {
$constName = ClassInfo::$currentClass . "::" . $expr->name->__toString();
$constName = ClassInfo::$currentClass . "::" . $constName;
if (isset($allConstInfos[$constName])) {
return formatConstValue($allConstInfos[$constName]->getValue($allConstInfos)->value);
} else {
return formatConstValue(getTranslator()->getClassConstValue($expr, ClassInfo::$currentClass, $expr->name->toString()));
return formatConstValue(getTranslator()->getClassConstValue($expr, ClassInfo::$currentClass, $constName));
}
} elseif ($expr->name->__toString() === 'class') {
return $class;
} else {
return formatConstValue(getTranslator()->getClassConstValue($expr, $class, $expr->name->__toString(), ClassInfo::$currentClass));
return formatConstValue(getTranslator()->getClassConstValue($expr, $class, $constName, ClassInfo::$currentClass));
}
} else {
$constName = $expr->name->__toString();
@ -2490,16 +2501,14 @@ class EvaluatedValue
// PHP single-quote to C double-quote string
if ($this->type->isString()) {
if (
$this->expr instanceof PhpParser\Node\Expr\ClassConstFetch
) {
if ($this->expr->class instanceof PhpParser\Node\Name\FullyQualified and
$this->expr->name instanceof PhpParser\Node\Identifier and
if ($this->expr instanceof PhpParser\Node\Expr\ClassConstFetch) {
if ($this->expr->name instanceof PhpParser\Node\Identifier and
$this->expr->name->__toString() === 'class') {
$expr = '"' . addcslashes($this->expr->class->name, '\\') . '"';
} else {
return $this->value;
// `::class` is a compile-time magic constant that resolves to the
// fully qualified class name (already stored in $this->value).
return '"' . addcslashes($this->value, '\\') . '"';
}
return $this->value;
} elseif ($this->expr instanceof Expr\ConstFetch) {
return getTranslator()->getConstValue($this->expr->name->toString());
} elseif (!($this->expr instanceof String_)) {
@ -2899,6 +2908,12 @@ class ConstInfo extends VariableLike
$code .= "\tzend_string *const_{$constName}_name = zend_string_init_interned(\"$constName\", sizeof(\"$constName\") - 1, true);\n";
$nameCode = "const_{$constName}_name";
// A child class may override a constant inherited from its parent. The
// runtime copies the parent's constants into the child, so re-declaring
// the constant would fail with "Cannot redefine class constant".
// Drop any inherited entry first so the child's value replaces it.
$code .= "\tzend_hash_del(&class_entry->constants_table, $nameCode);\n";
if ($this->exposedDocComment) {
$commentCode = "const_{$constName}_comment";
$escapedCommentInit = $this->exposedDocComment->getInitCode();

@ -0,0 +1,51 @@
--TEST--
class const override variants (self::class, parent::class, references, multi-level)
--FILE--
<?php
declare(strict_types=1);
class Base
{
public const NAME = 'Base';
public const GREETING = 'hello';
public const VALUE = 42;
}
class Other
{
public const TAG = 'other';
}
class Mid extends Base
{
public const NAME = Base::GREETING; // 'hello'
public const SELF_NAME = self::class; // 'Mid'
public const PARENT_NAME = parent::class; // 'Base'
public const CROSS = Other::TAG; // 'other'
}
class Leaf extends Mid
{
public const VALUE = Mid::NAME; // 'hello' (overrides Base::VALUE int with a string)
public const LEAF_NAME = self::class; // 'Leaf'
public const GREET = Base::GREETING; // 'hello'
}
function main()
{
var_dump(Mid::NAME, Mid::SELF_NAME, Mid::PARENT_NAME, Mid::CROSS);
var_dump(Leaf::VALUE, Leaf::LEAF_NAME, Leaf::GREET);
var_dump(Base::VALUE, Leaf::VALUE);
}
?>
--EXPECT--
string(5) "hello"
string(3) "Mid"
string(4) "Base"
string(5) "other"
string(5) "hello"
string(4) "Leaf"
string(5) "hello"
int(42)
string(5) "hello"

@ -0,0 +1,30 @@
--TEST--
class const override referencing another constant
--FILE--
<?php
declare(strict_types=1);
abstract class ParentClass
{
public const A = 'A';
public const B = 'B';
}
class TestClass extends ParentClass
{
public const A = ParentClass::B;
public const B = 'bbb';
}
function main()
{
var_dump(ParentClass::A, ParentClass::B);
var_dump(TestClass::A, TestClass::B);
}
?>
--EXPECT--
string(1) "A"
string(1) "B"
string(1) "B"
string(3) "bbb"

@ -0,0 +1,43 @@
--TEST--
parent class constants resolve across namespaces
--FILE--
<?php
namespace Library {
class Base
{
public const TOKEN = 'base';
}
}
namespace Application {
class Sibling
{
}
class Child extends \Library\Base
{
public const PARENT_NAME = parent::class;
public const SIBLING_NAME = Sibling::class;
public static function dumpParent(): void
{
var_dump(parent::class, parent::TOKEN);
}
}
}
namespace {
function main(): void
{
var_dump(\Application\Child::PARENT_NAME);
var_dump(\Application\Child::SIBLING_NAME);
\Application\Child::dumpParent();
}
}
?>
--EXPECT--
string(12) "Library\Base"
string(19) "Application\Sibling"
string(12) "Library\Base"
string(4) "base"
Loading…
Cancel
Save