Skip to content

Commit 146b56d

Browse files
committed
Support type arguments on a template type bound by a class with consistent templates
`@template TColl of Coll` with `@param TColl<int> $c` and `@return TColl<string>` is the class TColl is with other type arguments when Coll has @phpstan-consistent-templates: called with a Vec<int>, the function returns a Vec<string>. The template is inferred from the class of the argument, together with the templates in the type arguments, and the type arguments are carried down to that class the way `static<…>` does. Until TColl is known, `TColl<string>` is a Coll<string> that only another `TColl<…>` is known to be, so returning any Coll<string> is reported. Without the tag, the type stays the bound with the type arguments, which bleeding edge reports (generics.inconsistentTemplates). Ported to turbo-ext. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 25e835c commit 146b56d

14 files changed

Lines changed: 1289 additions & 8 deletions

‎src/DependencyInjection/ValidateIgnoredErrorsExtension.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
use PHPStan\PhpDocParser\Parser\ConstExprParser;
2424
use PHPStan\PhpDocParser\Parser\TypeParser;
2525
use PHPStan\PhpDocParser\ParserConfig;
26+
use PHPStan\Reflection\ConsistentTemplatesHelper;
2627
use PHPStan\Reflection\InitializerExprTypeResolver;
2728
use PHPStan\Reflection\MissingStaticAccessorInstanceException;
2829
use PHPStan\Reflection\PhpVersionStaticAccessor;
@@ -129,6 +130,8 @@ public function resolveTypeAlias(string $aliasName, NameScope $nameScope): ?Type
129130
new InitializerExprTypeResolver($constantResolver, $reflectionProviderProvider, new PhpVersion(PHP_VERSION_ID), new OperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new UnaryOperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new OversizedArrayBuilder(), true, $valueDependencyCollector),
130131
reportUnsafeArrayStringKeyCasting: null,
131132
valueDependencyCollector: $valueDependencyCollector,
133+
consistentTemplatesHelper: new ConsistentTemplatesHelper(),
134+
checkConsistentTemplates: false,
132135
),
133136
),
134137
);

‎src/PhpDoc/TypeNodeResolver.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
4747
use PHPStan\Reflection\Assertions;
4848
use PHPStan\Reflection\Callables\SimpleImpurePoint;
49+
use PHPStan\Reflection\ConsistentTemplatesHelper;
4950
use PHPStan\Reflection\InitializerExprContext;
5051
use PHPStan\Reflection\InitializerExprTypeResolver;
5152
use PHPStan\Reflection\Native\NativeParameterReflection;
@@ -87,6 +88,7 @@
8788
use PHPStan\Type\Generic\GenericStaticType;
8889
use PHPStan\Type\Generic\TemplateSelfReferenceTarget;
8990
use PHPStan\Type\Generic\TemplateType;
91+
use PHPStan\Type\Generic\TemplateTypeApplication;
9092
use PHPStan\Type\Generic\TemplateTypeFactory;
9193
use PHPStan\Type\Generic\TemplateTypeMap;
9294
use PHPStan\Type\Generic\TemplateTypeScope;
@@ -168,6 +170,9 @@ public function __construct(
168170
#[AutowiredParameter]
169171
private ?string $reportUnsafeArrayStringKeyCasting,
170172
private ValueDependencyCollector $valueDependencyCollector,
173+
private ConsistentTemplatesHelper $consistentTemplatesHelper,
174+
#[AutowiredParameter(ref: '%featureToggles.checkConsistentTemplates%')]
175+
private bool $checkConsistentTemplates,
171176
)
172177
{
173178
}
@@ -935,6 +940,12 @@ static function (string $variance): TemplateTypeVariance {
935940
$mainType = $typeNode->type instanceof NameNode
936941
? $this->resolveNameNode($typeNode->type, $nameScope)
937942
: $this->resolveIdentifierTypeNode($typeNode->type, $nameScope);
943+
if ($mainType instanceof TemplateType) {
944+
$application = $this->resolveTemplateTypeApplication($mainType, $genericTypes, $variances);
945+
if ($application !== null) {
946+
return $application;
947+
}
948+
}
938949
$mainTypeObjectClassNames = $mainType->getObjectClassNames();
939950
if (count($mainTypeObjectClassNames) > 1) {
940951
if ($mainType instanceof TemplateType) {
@@ -1326,6 +1337,30 @@ private function resolveTemplateTagsInDeclaration(array $valueNodes, NameScope $
13261337
return $tags;
13271338
}
13281339

1340+
/**
1341+
* `TColl<string>` for `@template TColl of Coll`: the class TColl is with other type
1342+
* arguments, which only a class with @phpstan-consistent-templates guarantees exists.
1343+
* Without it, the type is the bound with the arguments, as it always was.
1344+
*
1345+
* @param array<int, Type> $genericTypes
1346+
* @param array<int, TemplateTypeVariance> $variances
1347+
*/
1348+
private function resolveTemplateTypeApplication(TemplateType $templateType, array $genericTypes, array $variances): ?Type
1349+
{
1350+
$classReflections = $templateType->getBound()->getObjectClassReflections();
1351+
if (count($classReflections) !== 1 || !$classReflections[0]->isGeneric()) {
1352+
return null;
1353+
}
1354+
1355+
$consistent = $this->consistentTemplatesHelper->findConsistentTemplatesClass($classReflections[0]) !== null;
1356+
if (!$consistent && !$this->checkConsistentTemplates) {
1357+
return null;
1358+
}
1359+
1360+
// the bound with the type arguments for a class without the tag, which the PHPDoc checks report
1361+
return new TemplateTypeApplication($templateType, new GenericStaticType($classReflections[0], $genericTypes, null, $variances), $consistent);
1362+
}
1363+
13291364
private function resolveCallableTypeNode(CallableTypeNode $typeNode, NameScope $nameScope): Type
13301365
{
13311366
$templateTags = [];

‎src/Rules/Generics/GenericObjectTypeCheck.php‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPStan\Type\Generic\GenericObjectType;
1010
use PHPStan\Type\Generic\GenericStaticType;
1111
use PHPStan\Type\Generic\TemplateType;
12+
use PHPStan\Type\Generic\TemplateTypeApplication;
1213
use PHPStan\Type\Generic\TemplateTypeHelper;
1314
use PHPStan\Type\Generic\TemplateTypeMap;
1415
use PHPStan\Type\Generic\TemplateTypeVariance;
@@ -43,8 +44,25 @@ public function check(
4344
string $typeProjectionIsRedundantMessage,
4445
): array
4546
{
46-
$genericTypes = $this->getGenericTypes($phpDocType);
47+
$genericTypes = $this->getGenericTypes($phpDocType, $applications);
4748
$messages = [];
49+
foreach ($applications as $application) {
50+
$constructor = $application->getConstructor();
51+
if (!$constructor instanceof TemplateType) {
52+
continue;
53+
}
54+
55+
$classReflection = $application->getApplication()->getClassReflection();
56+
$messages[] = RuleErrorBuilder::message(sprintf(
57+
'PHPDoc type %s applies type arguments to template type %s, but its bound %s %s does not have @phpstan-consistent-templates.',
58+
(string) $application->toPhpDocNode(),
59+
$constructor->getName(),
60+
strtolower($classReflection->getClassTypeDescription()),
61+
$classReflection->getDisplayName(false),
62+
))
63+
->identifier('generics.inconsistentTemplates')
64+
->build();
65+
}
4866
foreach ($genericTypes as $genericType) {
4967
$classReflection = $genericType->getClassReflection();
5068
if ($classReflection === null) {
@@ -187,17 +205,24 @@ public function check(
187205
}
188206

189207
/**
208+
* @param list<TemplateTypeApplication>|null $inconsistentApplications
209+
* @param-out list<TemplateTypeApplication> $inconsistentApplications
190210
* @return list<GenericObjectType|GenericStaticType>
191211
*/
192-
private function getGenericTypes(Type $phpDocType): array
212+
private function getGenericTypes(Type $phpDocType, ?array &$inconsistentApplications): array
193213
{
214+
$inconsistentApplications = [];
215+
194216
// a generic type references its class, unless it hides in a template default or a late-resolvable type
195217
if ($phpDocType->getReferencedClasses() === [] && !$phpDocType->hasTemplateOrLateResolvableType()) {
196218
return [];
197219
}
198220

199221
$genericObjectTypes = [];
200-
TypeTraverser::map($phpDocType, static function (Type $type, callable $traverse) use (&$genericObjectTypes): Type {
222+
TypeTraverser::map($phpDocType, static function (Type $type, callable $traverse) use (&$genericObjectTypes, &$inconsistentApplications): Type {
223+
if ($type instanceof TemplateTypeApplication && !$type->isConsistent()) {
224+
$inconsistentApplications[] = $type;
225+
}
201226
if ($type instanceof GenericObjectType || $type instanceof GenericStaticType) {
202227
$resolvedType = TemplateTypeHelper::resolveToBounds($type);
203228
if (!$resolvedType instanceof GenericObjectType && !$resolvedType instanceof GenericStaticType) {
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Type\Generic;
4+
5+
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
6+
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
7+
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
8+
use PHPStan\Turbo\ShadowedByTurboExtension;
9+
use PHPStan\Type\AcceptsResult;
10+
use PHPStan\Type\CompoundType;
11+
use PHPStan\Type\IsSuperTypeOfResult;
12+
use PHPStan\Type\LateResolvableType;
13+
use PHPStan\Type\Traits\LateResolvableTypeTrait;
14+
use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
15+
use PHPStan\Type\Type;
16+
use PHPStan\Type\TypeCombinator;
17+
use PHPStan\Type\VerbosityLevel;
18+
use function array_map;
19+
use function array_merge;
20+
use function implode;
21+
use function sprintf;
22+
23+
/**
24+
* `TColl<string>` for `@template TColl of Coll` where Coll has `@phpstan-consistent-templates`:
25+
* the class TColl is with other type arguments. Once TColl is known, like `Vec<int>`, the type
26+
* is that class with these arguments, `Vec<string>`. Until then it is a `Coll<string>`, and
27+
* only another `TColl<…>` is known to be the same class.
28+
*
29+
* The application is a `static<…>` of the bound's class, so a class below it gets the type
30+
* arguments the way `static<…>` called on it does.
31+
*/
32+
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateTypeApplication.cpp')]
33+
final class TemplateTypeApplication implements CompoundType, LateResolvableType
34+
{
35+
36+
use LateResolvableTypeTrait;
37+
use NonGeneralizableTypeTrait;
38+
39+
/**
40+
* @param bool $consistent Whether the bound's class has `@phpstan-consistent-templates`;
41+
* without it, the type is the bound with the type arguments.
42+
*/
43+
public function __construct(
44+
private Type $constructor,
45+
private GenericStaticType $application,
46+
private bool $consistent,
47+
)
48+
{
49+
}
50+
51+
public function isConsistent(): bool
52+
{
53+
return $this->consistent;
54+
}
55+
56+
public function getConstructor(): Type
57+
{
58+
return $this->constructor;
59+
}
60+
61+
public function getApplication(): GenericStaticType
62+
{
63+
return $this->application;
64+
}
65+
66+
public function getReferencedClasses(): array
67+
{
68+
return array_merge($this->constructor->getReferencedClasses(), $this->application->getReferencedClasses());
69+
}
70+
71+
public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
72+
{
73+
return array_merge(
74+
$this->constructor->getReferencedTemplateTypes($positionVariance),
75+
$this->application->getReferencedTemplateTypes($positionVariance),
76+
);
77+
}
78+
79+
public function equals(Type $type): bool
80+
{
81+
return $type instanceof self
82+
&& $this->constructor->equals($type->constructor)
83+
&& $this->application->equals($type->application);
84+
}
85+
86+
public function describe(VerbosityLevel $level): string
87+
{
88+
if ($this->isResolvable() || !$this->constructor instanceof TemplateType) {
89+
return $this->resolve()->describe($level);
90+
}
91+
92+
$constructor = $this->constructor;
93+
$arguments = implode(', ', array_map(static fn (Type $type): string => $type->describe($level), $this->application->getTypes()));
94+
95+
// written as in the PHPDoc, but the cache keys tell apart the templates of the same name
96+
return $level->handle(
97+
static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments),
98+
static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments),
99+
static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments),
100+
static fn (): string => sprintf('%s<%s>', $constructor->describe(VerbosityLevel::cache()), $arguments),
101+
);
102+
}
103+
104+
public function isResolvable(): bool
105+
{
106+
return !$this->consistent || !$this->constructor instanceof TemplateType;
107+
}
108+
109+
protected function getResult(): Type
110+
{
111+
if (!$this->consistent) {
112+
return $this->application->getStaticObjectType();
113+
}
114+
115+
$applicationClassReflection = $this->application->getClassReflection();
116+
$results = [];
117+
foreach ($this->constructor->getObjectClassReflections() as $classReflection) {
118+
if ($classReflection->getName() !== $applicationClassReflection->getName() && !$classReflection->isSubclassOfClass($applicationClassReflection)) {
119+
continue;
120+
}
121+
122+
$results[] = $this->application->changeBaseClass($classReflection)->getStaticObjectType();
123+
}
124+
125+
if ($results === []) {
126+
return $this->application->getStaticObjectType();
127+
}
128+
129+
return TypeCombinator::union(...$results);
130+
}
131+
132+
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
133+
{
134+
if ($this->isSameUnresolvedClass($type)) {
135+
return $this->application->getStaticObjectType()->isSuperTypeOf($type->application->getStaticObjectType());
136+
}
137+
138+
return $this->isSuperTypeOfDefault($type);
139+
}
140+
141+
public function accepts(Type $type, bool $strictTypes): AcceptsResult
142+
{
143+
if ($this->isSameUnresolvedClass($type)) {
144+
return $this->application->getStaticObjectType()->accepts($type->application->getStaticObjectType(), $strictTypes);
145+
}
146+
147+
$accepts = $this->resolve()->accepts($type, $strictTypes);
148+
if (!$this->isResolvable()) {
149+
// like a template, an unknown class is the same as another one only maybe
150+
return $accepts->and(AcceptsResult::createMaybe());
151+
}
152+
153+
return $accepts;
154+
}
155+
156+
public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
157+
{
158+
// the received object is the class the constructor stands for,
159+
// and its type arguments are what the application has
160+
return $this->constructor->inferTemplateTypes($receivedType)
161+
->union($this->application->getStaticObjectType()->inferTemplateTypes($receivedType));
162+
}
163+
164+
/** @phpstan-assert-if-true self $type */
165+
private function isSameUnresolvedClass(Type $type): bool
166+
{
167+
return $type instanceof self
168+
&& !$this->isResolvable()
169+
&& $this->constructor->equals($type->constructor);
170+
}
171+
172+
/**
173+
* @param callable(Type): Type $cb
174+
*/
175+
public function traverse(callable $cb): Type
176+
{
177+
$constructor = $cb($this->constructor);
178+
$application = $this->application->traverse($cb);
179+
180+
if ($this->constructor === $constructor && $this->application === $application) {
181+
return $this;
182+
}
183+
184+
return $this->create($constructor, $application);
185+
}
186+
187+
public function traverseSimultaneously(Type $right, callable $cb): Type
188+
{
189+
if (!$right instanceof self) {
190+
return $this;
191+
}
192+
193+
$constructor = $cb($this->constructor, $right->constructor);
194+
$application = $this->application->traverseSimultaneously($right->application, $cb);
195+
196+
if ($this->constructor === $constructor && $this->application === $application) {
197+
return $this;
198+
}
199+
200+
return $this->create($constructor, $application);
201+
}
202+
203+
/** A traversal may turn the application into anything, which then stands on its own. */
204+
private function create(Type $constructor, Type $application): Type
205+
{
206+
if (!$application instanceof GenericStaticType) {
207+
return $application;
208+
}
209+
210+
return new self($constructor, $application, $this->consistent);
211+
}
212+
213+
public function toPhpDocNode(): TypeNode
214+
{
215+
$constructor = $this->constructor->toPhpDocNode();
216+
if (!$constructor instanceof IdentifierTypeNode) {
217+
return $this->resolve()->toPhpDocNode();
218+
}
219+
220+
return new GenericTypeNode(
221+
$constructor,
222+
array_map(static fn (Type $type): TypeNode => $type->toPhpDocNode(), $this->application->getTypes()),
223+
);
224+
}
225+
226+
}

‎src/Type/Traverser/LateResolvableTraverser.php‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use PHPStan\Type\ArrayType;
77
use PHPStan\Type\CallableType;
88
use PHPStan\Type\ClosureType;
9+
use PHPStan\Type\Generic\TemplateTypeApplication;
910
use PHPStan\Type\LateResolvableType;
1011
use PHPStan\Type\Type;
1112
use PHPStan\Type\TypeTraverserCallable;
@@ -28,7 +29,14 @@ public function __construct(
2829
*/
2930
public function traverse(Type $type, callable $traverse): Type
3031
{
31-
while ($type instanceof LateResolvableType && (($this->resolveUnresolvableTypes && $this->ignoreResolveUnresolvableTypesLevel === 0) || $type->isResolvable())) {
32+
// TColl<…> of a TColl not known yet is not some Coll<…>, it is the class TColl will be
33+
while (
34+
$type instanceof LateResolvableType
35+
&& (
36+
($this->resolveUnresolvableTypes && $this->ignoreResolveUnresolvableTypesLevel === 0 && !$type instanceof TemplateTypeApplication)
37+
|| $type->isResolvable()
38+
)
39+
) {
3240
$type = $type->resolve();
3341
}
3442

0 commit comments

Comments
 (0)