Skip to content

Commit b7dd913

Browse files
committed
Make BackedEnum generic
`BackedEnum` now carries the backing type: `@template-covariant T of int|string`. `BackedEnum<string>::$value` is `string` instead of `int|string`, and `value-of<T>` for `@template T of BackedEnum<string>` resolves to `string`. `from()` and `tryFrom()` take a method-level `@template TValue of T` instead of `@param T`. `T` stays out of contravariant position, which the variance check forbids for a covariant type parameter, while `BackedEnum<int>::from('a')` is still reported. Three things keep this backwards compatible: * `T` defaults to `int|string`, so a bare `BackedEnum` in PHPDoc keeps its old meaning and is not reported as missing type arguments on level 6 and above. * `T` is covariant, so every backed enum stays assignable to a bare `BackedEnum`. * PHP implements `BackedEnum` implicitly, so there is no `@implements` tag that could carry the type argument. `ClassReflection::getImmediateInterfaces()` fills it in from the enum backing type instead. Two supporting changes were needed for that last point: * `ClassReflection::getInterfaces()` and `ObjectType::getAncestorWithClassName()` now prefer the interface as resolved on the class itself over the same interface reached through one of its ancestors. Without this, an enum that implements an interface which extends `BackedEnum` resolved to the ancestor type arguments of that interface. * A generic ancestor with no `@implements` or `@extends` tag now uses the declared template defaults instead of error types, when every template type has a default. This is what makes `interface Foo extends BackedEnum` resolve to `BackedEnum<int|string>` rather than `BackedEnum<*ERROR*>`. Co-Authored-By: Claude Code Claude-Session: https://claude.ai/code/session_01QCdFyyKvMdEaU4bywFUist
1 parent bbd64b4 commit b7dd913

8 files changed

Lines changed: 299 additions & 2 deletions

File tree

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ parameters:
154154
- ../stubs/iterable.stub
155155
- ../stubs/ArrayObject.stub
156156
- ../stubs/WeakReference.stub
157+
- ../stubs/BackedEnum.stub
157158
- ../stubs/ext-ds.stub
158159
- ../stubs/ImagickPixel.stub
159160
- ../stubs/PDOStatement.stub

‎src/Reflection/ClassReflection.php‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace PHPStan\Reflection;
44

55
use Attribute;
6+
use BackedEnum;
67
use PhpParser\Node\Arg;
78
use PhpParser\Node\Expr\StaticCall;
89
use PhpParser\Node\Identifier;
@@ -1121,6 +1122,12 @@ public function getInterfaces(): array
11211122
}
11221123
}
11231124

1125+
// An interface resolved on this class itself is more specific than the same
1126+
// interface reached through one of its ancestors.
1127+
foreach ($immediateInterfaces as $name => $immediateInterface) {
1128+
$interfaces[$name] = $immediateInterface;
1129+
}
1130+
11241131
$this->cachedInterfaces = $interfaces;
11251132

11261133
return $interfaces;
@@ -1207,17 +1214,52 @@ public function getImmediateInterfaces(): array
12071214

12081215
if ($immediateInterface->isGeneric()) {
12091216
$immediateInterfaces[$immediateInterface->getName()] = $immediateInterface->withTypes(
1210-
array_values($immediateInterface->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()),
1217+
$this->getUnspecifiedAncestorTypes($immediateInterface),
12111218
);
12121219
continue;
12131220
}
12141221

12151222
$immediateInterfaces[$immediateInterface->getName()] = $immediateInterface;
12161223
}
12171224

1225+
// PHP implicitly implements BackedEnum on backed enums, so there is no
1226+
// @implements tag that could carry the backing type.
1227+
$backedEnumType = $this->getBackedEnumType();
1228+
if ($backedEnumType !== null && $this->reflectionProvider->hasClass(BackedEnum::class)) {
1229+
$immediateInterfaces[BackedEnum::class] = $this->reflectionProvider->getClass(BackedEnum::class)
1230+
->withTypes([$backedEnumType]);
1231+
}
1232+
12181233
return $immediateInterfaces;
12191234
}
12201235

1236+
/**
1237+
* Type arguments for a generic ancestor that is not described by an @implements
1238+
* or @extends tag. Declared template defaults are used when the ancestor has
1239+
* one for every template type, otherwise the type arguments stay erroneous.
1240+
*
1241+
* @return list<Type>
1242+
*/
1243+
private function getUnspecifiedAncestorTypes(ClassReflection $ancestor): array
1244+
{
1245+
$defaults = [];
1246+
foreach ($ancestor->getTemplateTags() as $templateTag) {
1247+
$default = $templateTag->getDefault();
1248+
if ($default === null) {
1249+
$defaults = null;
1250+
break;
1251+
}
1252+
1253+
$defaults[] = $default;
1254+
}
1255+
1256+
if ($defaults !== null) {
1257+
return $defaults;
1258+
}
1259+
1260+
return array_values($ancestor->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes());
1261+
}
1262+
12211263
/**
12221264
* @return array<string, ClassReflection>
12231265
*/

‎src/Type/ObjectType.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1871,6 +1871,16 @@ public function getAncestorWithClassName(string $className): ?self
18711871
return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $this;
18721872
}
18731873

1874+
// An interface resolved on this class itself is more specific than the same
1875+
// interface reached through one of its ancestors.
1876+
foreach ($this->getInterfaces() as $interface) {
1877+
if ($interface->getClassName() !== $className) {
1878+
continue;
1879+
}
1880+
1881+
return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $interface;
1882+
}
1883+
18741884
foreach ($this->getInterfaces() as $interface) {
18751885
$ancestor = $interface->getAncestorWithClassName($className);
18761886
if ($ancestor !== null) {

‎src/Type/ValueOfType.php‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace PHPStan\Type;
44

5+
use BackedEnum;
56
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
67
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
78
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
@@ -56,8 +57,29 @@ protected function getResult(): Type
5657
if (
5758
$enumCases === []
5859
&& $this->type instanceof TemplateType
59-
&& (new ObjectType('BackedEnum'))->isSuperTypeOf($this->type->getBound())->yes()
60+
&& (new ObjectType(BackedEnum::class))->isSuperTypeOf($this->type->getBound())->yes()
6061
) {
62+
$backingTypes = [];
63+
foreach ($this->type->getBound()->getObjectClassReflections() as $classReflection) {
64+
$ancestor = $classReflection->getAncestorWithClassName(BackedEnum::class);
65+
if ($ancestor === null) {
66+
$backingTypes = [];
67+
break;
68+
}
69+
70+
$backingType = $ancestor->getActiveTemplateTypeMap()->getType('T');
71+
if ($backingType === null || $backingType instanceof ErrorType) {
72+
$backingTypes = [];
73+
break;
74+
}
75+
76+
$backingTypes[] = $backingType;
77+
}
78+
79+
if ($backingTypes !== []) {
80+
return TypeCombinator::union(...$backingTypes);
81+
}
82+
6183
return new UnionType([new IntegerType(), new StringType()]);
6284
}
6385

‎stubs/BackedEnum.stub‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
/**
4+
* @template-covariant T of int|string = int|string
5+
*/
6+
interface BackedEnum extends UnitEnum
7+
{
8+
9+
/** @var T */
10+
public readonly int|string $value;
11+
12+
/**
13+
* @template TValue of T
14+
* @param TValue $value
15+
* @return static
16+
*/
17+
public static function from(int|string $value): static;
18+
19+
/**
20+
* @template TValue of T
21+
* @param TValue $value
22+
* @return static|null
23+
*/
24+
public static function tryFrom(int|string $value): ?static;
25+
26+
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
<?php // lint >= 8.1
2+
3+
declare(strict_types = 1);
4+
5+
namespace GenericBackedEnum;
6+
7+
use BackedEnum;
8+
use UnitEnum;
9+
use function PHPStan\Testing\assertType;
10+
11+
enum StringEnum: string
12+
{
13+
14+
case A = 'a';
15+
case B = 'b';
16+
17+
}
18+
19+
enum IntEnum: int
20+
{
21+
22+
case One = 1;
23+
24+
}
25+
26+
enum PureEnum
27+
{
28+
29+
case X;
30+
31+
}
32+
33+
interface HasLabel extends BackedEnum
34+
{
35+
36+
}
37+
38+
/**
39+
* @extends BackedEnum<string>
40+
*/
41+
interface StringBackedInterface extends BackedEnum
42+
{
43+
44+
}
45+
46+
enum ViaInterface: string implements HasLabel
47+
{
48+
49+
case A = 'a';
50+
51+
}
52+
53+
enum ViaStringInterface: string implements StringBackedInterface
54+
{
55+
56+
case A = 'a';
57+
58+
}
59+
60+
function bare(BackedEnum $e): void
61+
{
62+
assertType('int|string', $e->value);
63+
assertType('non-decimal-int-string&non-falsy-string', $e->name);
64+
}
65+
66+
/**
67+
* @param BackedEnum<string> $e
68+
* @param BackedEnum<int> $i
69+
*/
70+
function withTypes(BackedEnum $e, BackedEnum $i): void
71+
{
72+
assertType('string', $e->value);
73+
assertType('int', $i->value);
74+
assertType('BackedEnum<string>', $e->from('a'));
75+
assertType('BackedEnum<string>|null', $e->tryFrom('a'));
76+
}
77+
78+
function unresolvedInterface(HasLabel $e): void
79+
{
80+
assertType('int|string', $e->value);
81+
}
82+
83+
function resolvedInterface(StringBackedInterface $e): void
84+
{
85+
assertType('string', $e->value);
86+
}
87+
88+
/**
89+
* @param BackedEnum<string> $e
90+
*/
91+
function acceptsStringBacked(BackedEnum $e): void
92+
{
93+
}
94+
95+
function passing(StringEnum $a, ViaInterface $b, ViaStringInterface $c): void
96+
{
97+
acceptsStringBacked($a);
98+
acceptsStringBacked($b);
99+
acceptsStringBacked($c);
100+
}
101+
102+
/**
103+
* @template T of BackedEnum
104+
* @param T $e
105+
* @return value-of<T>
106+
*/
107+
function valueOfAny(BackedEnum $e)
108+
{
109+
return $e->value;
110+
}
111+
112+
/**
113+
* @template T of BackedEnum<string>
114+
* @param class-string<T> $className
115+
* @return T
116+
*/
117+
function fromString(string $className, string $value): BackedEnum
118+
{
119+
return $className::from($value);
120+
}
121+
122+
function templates(): void
123+
{
124+
assertType("'a'", valueOfAny(StringEnum::A));
125+
assertType('GenericBackedEnum\StringEnum', fromString(StringEnum::class, 'a'));
126+
}
127+
128+
function unitEnumIsNotGeneric(UnitEnum $e, PureEnum $p): void
129+
{
130+
assertType('non-decimal-int-string&non-falsy-string', $e->name);
131+
assertType("'X'", $p->name);
132+
}

‎tests/PHPStan/Rules/Methods/CallStaticMethodsRuleTest.php‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,4 +1066,24 @@ public function testBug15002(): void
10661066
$this->analyse([__DIR__ . '/data/bug-15002.php'], []);
10671067
}
10681068

1069+
#[RequiresPhp('>= 8.1')]
1070+
public function testGenericBackedEnum(): void
1071+
{
1072+
$this->checkThisOnly = false;
1073+
$this->analyse([__DIR__ . '/data/generic-backed-enum.php'], [
1074+
[
1075+
'Parameter #1 $value of static method BackedEnum<int>::from() expects TValue of int, string given.',
1076+
23,
1077+
],
1078+
[
1079+
'Parameter #1 $value of static method BackedEnum<string>::tryFrom() expects TValue of string, int given.',
1080+
24,
1081+
],
1082+
[
1083+
'Parameter #1 $value of static method BackedEnum<string>::from() expects TValue of string, int given.',
1084+
36,
1085+
],
1086+
]);
1087+
}
1088+
10691089
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php // lint >= 8.1
2+
3+
declare(strict_types = 1);
4+
5+
namespace GenericBackedEnumStaticCall;
6+
7+
use BackedEnum;
8+
9+
enum StringEnum: string
10+
{
11+
12+
case A = 'a';
13+
14+
}
15+
16+
/**
17+
* @param BackedEnum<int> $intBacked
18+
* @param BackedEnum<string> $stringBacked
19+
*/
20+
function backedEnumInterface(BackedEnum $intBacked, BackedEnum $stringBacked, BackedEnum $bare, int $i, string $s): void
21+
{
22+
$intBacked::from($i);
23+
$intBacked::from($s);
24+
$stringBacked::tryFrom($i);
25+
$stringBacked::tryFrom($s);
26+
$bare::from($i);
27+
$bare::from($s);
28+
}
29+
30+
/**
31+
* @template T of BackedEnum<string>
32+
* @param class-string<T> $className
33+
*/
34+
function stringBackedClassString(string $className, int $i, string $s): void
35+
{
36+
$className::from($i);
37+
$className::from($s);
38+
}
39+
40+
function concreteEnum(int $i, string $s): void
41+
{
42+
StringEnum::from($s);
43+
StringEnum::tryFrom($s);
44+
}

0 commit comments

Comments
 (0)