Skip to content

Commit 25e835c

Browse files
committed
Add @phpstan-consistent-templates
A class or an interface with @phpstan-consistent-templates, or @psalm-consistent-templates, makes the classes below it declare the same template types, pass them on in the order they declare them and bound them at most as tightly, so that the class of an object with other type arguments is a type. The rule checking them reports generics.inconsistentTemplates under bleeding edge (checkConsistentTemplates). Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 13a9180 commit 25e835c

10 files changed

Lines changed: 458 additions & 0 deletions

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,4 @@ parameters:
4040
checkTemplateTypeBounds: true
4141
reportTemplateInImportedTypeAlias: true
4242
checkConditionalParameterTypes: true
43+
checkConsistentTemplates: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ parameters:
7272
checkTemplateTypeBounds: false
7373
reportTemplateInImportedTypeAlias: false
7474
checkConditionalParameterTypes: false
75+
checkConsistentTemplates: false
7576
fileExtensions:
7677
- php
7778
checkAdvancedIsset: false

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ parametersSchema:
6969
checkTemplateTypeBounds: bool()
7070
reportTemplateInImportedTypeAlias: bool()
7171
checkConditionalParameterTypes: bool()
72+
checkConsistentTemplates: bool()
7273
])
7374
fileExtensions: listOf(string())
7475
checkAdvancedIsset: bool()

‎src/PhpDoc/PhpDocNodeResolver.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,17 @@ public function resolveHasConsistentConstructor(PhpDocNode $phpDocNode): bool
741741
return false;
742742
}
743743

744+
public function resolveHasConsistentTemplates(PhpDocNode $phpDocNode): bool
745+
{
746+
foreach (['@phpstan-consistent-templates', '@psalm-consistent-templates'] as $tagName) {
747+
if (count($phpDocNode->getTagsByName($tagName)) > 0) {
748+
return true;
749+
}
750+
}
751+
752+
return false;
753+
}
754+
744755
public function resolveAcceptsNamedArguments(PhpDocNode $phpDocNode): bool
745756
{
746757
return count($phpDocNode->getTagsByName('@no-named-arguments')) === 0;

‎src/PhpDoc/ResolvedPhpDocBlock.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ final class ResolvedPhpDocBlock
160160

161161
private ?bool $hasConsistentConstructor = null;
162162

163+
private ?bool $hasConsistentTemplates = null;
164+
163165
private ?bool $acceptsNamedArguments = null;
164166

165167
private function __construct()
@@ -254,6 +256,7 @@ public static function createEmpty(): self
254256
$self->isImmutable = false;
255257
$self->isAllowedPrivateMutation = false;
256258
$self->hasConsistentConstructor = false;
259+
$self->hasConsistentTemplates = false;
257260
$self->acceptsNamedArguments = true;
258261

259262
return $self;
@@ -312,6 +315,7 @@ public function merge(ResolvedPhpDocBlock $parent, InheritedPhpDocParameterMappi
312315
$result->isImmutable = $this->isImmutable();
313316
$result->isAllowedPrivateMutation = $this->isAllowedPrivateMutation();
314317
$result->hasConsistentConstructor = $this->hasConsistentConstructor();
318+
$result->hasConsistentTemplates = $this->hasConsistentTemplates();
315319
$result->acceptsNamedArguments = $acceptsNamedArguments;
316320

317321
return $result;
@@ -828,6 +832,13 @@ public function hasConsistentConstructor(): bool
828832
);
829833
}
830834

835+
public function hasConsistentTemplates(): bool
836+
{
837+
return $this->hasConsistentTemplates ??= $this->phpDocNodeResolver->resolveHasConsistentTemplates(
838+
$this->phpDocNode,
839+
);
840+
}
841+
831842
public function acceptsNamedArguments(): bool
832843
{
833844
return $this->acceptsNamedArguments ??= $this->phpDocNodeResolver->resolveAcceptsNamedArguments(
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Reflection;
4+
5+
use PHPStan\DependencyInjection\AutowiredService;
6+
use function array_unshift;
7+
use function array_values;
8+
9+
/**
10+
* `@phpstan-consistent-templates` on a class or an interface makes every class below it
11+
* declare the same template types and pass them on in the same order, so that the
12+
* class of an object together with other type arguments is a type, like `static<U>`.
13+
*/
14+
#[AutowiredService]
15+
final class ConsistentTemplatesHelper
16+
{
17+
18+
/** The class itself or the ancestor with `@phpstan-consistent-templates`, the nearest one first. */
19+
public function findConsistentTemplatesClass(ClassReflection $classReflection): ?ClassReflection
20+
{
21+
$resolvedPhpDoc = $classReflection->getResolvedPhpDoc();
22+
if ($resolvedPhpDoc !== null && $resolvedPhpDoc->hasConsistentTemplates()) {
23+
return $classReflection;
24+
}
25+
26+
$ancestors = array_values($classReflection->getImmediateInterfaces());
27+
$parent = $classReflection->getParentClass();
28+
if ($parent !== null) {
29+
array_unshift($ancestors, $parent);
30+
}
31+
32+
foreach ($ancestors as $ancestor) {
33+
$found = $this->findConsistentTemplatesClass($ancestor);
34+
if ($found !== null) {
35+
return $found;
36+
}
37+
}
38+
39+
return null;
40+
}
41+
42+
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Generics;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\DependencyInjection\AutowiredParameter;
8+
use PHPStan\DependencyInjection\RegisteredRule;
9+
use PHPStan\Node\InClassNode;
10+
use PHPStan\Reflection\ClassReflection;
11+
use PHPStan\Reflection\ConsistentTemplatesHelper;
12+
use PHPStan\Rules\Rule;
13+
use PHPStan\Rules\RuleErrorBuilder;
14+
use PHPStan\Type\Generic\TemplateType;
15+
use PHPStan\Type\Generic\TemplateTypeHelper;
16+
use PHPStan\Type\Generic\TemplateTypeVariance;
17+
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
18+
use PHPStan\Type\VerbosityLevel;
19+
use function array_keys;
20+
use function array_values;
21+
use function count;
22+
use function sprintf;
23+
use function strtolower;
24+
use function ucfirst;
25+
26+
/**
27+
* A class below one with `@phpstan-consistent-templates` declares the same template
28+
* types, passes them on in the same order and bounds them at most as tightly.
29+
*
30+
* @implements Rule<InClassNode>
31+
*/
32+
#[RegisteredRule(level: 2)]
33+
final class ConsistentTemplatesRule implements Rule
34+
{
35+
36+
public function __construct(
37+
private ConsistentTemplatesHelper $consistentTemplatesHelper,
38+
#[AutowiredParameter(ref: '%featureToggles.checkConsistentTemplates%')]
39+
private bool $checkConsistentTemplates,
40+
)
41+
{
42+
}
43+
44+
public function getNodeType(): string
45+
{
46+
return InClassNode::class;
47+
}
48+
49+
public function processNode(Node $node, Scope $scope): array
50+
{
51+
if (!$this->checkConsistentTemplates) {
52+
return [];
53+
}
54+
55+
$classReflection = $node->getClassReflection();
56+
if ($classReflection->isAnonymous()) {
57+
return [];
58+
}
59+
60+
$ancestors = array_values($classReflection->getImmediateInterfaces());
61+
$parent = $classReflection->getParentClass();
62+
if ($parent !== null) {
63+
$ancestors = [$parent, ...$ancestors];
64+
}
65+
66+
$errors = [];
67+
foreach ($ancestors as $ancestor) {
68+
$consistentClass = $this->consistentTemplatesHelper->findConsistentTemplatesClass($ancestor);
69+
if ($consistentClass === null) {
70+
continue;
71+
}
72+
73+
foreach ($this->check($classReflection, $ancestor, $consistentClass) as $message) {
74+
$errors[] = RuleErrorBuilder::message($message)
75+
->identifier('generics.inconsistentTemplates')
76+
->build();
77+
}
78+
}
79+
80+
return $errors;
81+
}
82+
83+
/**
84+
* @return list<string>
85+
*/
86+
private function check(ClassReflection $classReflection, ClassReflection $ancestor, ClassReflection $consistentClass): array
87+
{
88+
$classDescription = sprintf('%s %s', strtolower($classReflection->getClassTypeDescription()), $classReflection->getDisplayName(false));
89+
$ancestorDescription = sprintf('%s %s with @phpstan-consistent-templates', strtolower($ancestor->getClassTypeDescription()), $ancestor->getDisplayName(false));
90+
if ($consistentClass->getName() !== $ancestor->getName()) {
91+
$ancestorDescription .= sprintf(' from %s %s', strtolower($consistentClass->getClassTypeDescription()), $consistentClass->getDisplayName(false));
92+
}
93+
94+
$ownNames = array_keys($classReflection->getTemplateTags());
95+
$ancestorNames = array_keys($ancestor->getTemplateTags());
96+
if (count($ownNames) !== count($ancestorNames)) {
97+
return [sprintf(
98+
'%s declares %d template %s, but %s declares %d.',
99+
ucfirst($classDescription),
100+
count($ownNames),
101+
count($ownNames) === 1 ? 'type' : 'types',
102+
$ancestorDescription,
103+
count($ancestorNames),
104+
)];
105+
}
106+
107+
$passed = $classReflection->getAncestorWithClassName($ancestor->getName());
108+
if ($passed === null) {
109+
return [];
110+
}
111+
112+
$passedTypes = $passed->getActiveTemplateTypeMap();
113+
$ownTypes = $classReflection->getTemplateTypeMap();
114+
$ancestorTypes = $ancestor->getTemplateTypeMap();
115+
$messages = [];
116+
foreach ($ancestorNames as $i => $ancestorName) {
117+
$ownName = $ownNames[$i];
118+
$passedType = $passedTypes->getType($ancestorName);
119+
if (
120+
!$passedType instanceof TemplateType
121+
|| $passedType->getName() !== $ownName
122+
|| $passedType->getScope()->getClassName() !== $classReflection->getName()
123+
|| $passedType->getScope()->getFunctionName() !== null
124+
) {
125+
return [sprintf(
126+
'%s does not pass its template types to %s in the order it declares them.',
127+
ucfirst($classDescription),
128+
$ancestorDescription,
129+
)];
130+
}
131+
132+
$ownType = $ownTypes->getType($ownName);
133+
$ancestorType = $ancestorTypes->getType($ancestorName);
134+
if (!$ownType instanceof TemplateType || !$ancestorType instanceof TemplateType) {
135+
continue;
136+
}
137+
138+
// the ancestor's bound in terms of the own template types
139+
$ancestorBound = TemplateTypeHelper::resolveTemplateTypes(
140+
$ancestorType->getBound(),
141+
$passedTypes,
142+
TemplateTypeVarianceMap::createEmpty(),
143+
TemplateTypeVariance::createInvariant(),
144+
);
145+
if ($ownType->getBound()->isSuperTypeOf($ancestorBound)->yes()) {
146+
continue;
147+
}
148+
149+
$messages[] = sprintf(
150+
'Bound type %s of template type %s of %s is narrower than bound type %s of template type %s of %s.',
151+
$ownType->getBound()->describe(VerbosityLevel::typeOnly()),
152+
$ownName,
153+
$classDescription,
154+
$ancestorBound->describe(VerbosityLevel::typeOnly()),
155+
$ancestorName,
156+
$ancestorDescription,
157+
);
158+
}
159+
160+
return $messages;
161+
}
162+
163+
}

‎src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ final class InvalidPHPStanDocTagRule implements MultipleNodeTypesRule
4848
'@phpstan-property-read',
4949
'@phpstan-property-write',
5050
'@phpstan-consistent-constructor',
51+
'@phpstan-consistent-templates',
5152
'@phpstan-assert',
5253
'@phpstan-assert-if-true',
5354
'@phpstan-assert-if-false',
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Generics;
4+
5+
use PHPStan\Reflection\ConsistentTemplatesHelper;
6+
use PHPStan\Rules\Rule;
7+
use PHPStan\Testing\RuleTestCase;
8+
9+
/**
10+
* @extends RuleTestCase<ConsistentTemplatesRule>
11+
*/
12+
class ConsistentTemplatesRuleTest extends RuleTestCase
13+
{
14+
15+
protected function getRule(): Rule
16+
{
17+
return new ConsistentTemplatesRule(new ConsistentTemplatesHelper(), true);
18+
}
19+
20+
public function testRule(): void
21+
{
22+
$this->analyse([__DIR__ . '/data/consistent-templates.php'], [
23+
[
24+
'Bound type int of template type T of class ConsistentTemplates\IntBoundVec is narrower than bound type mixed of template type T of interface ConsistentTemplates\Coll with @phpstan-consistent-templates.',
25+
27,
26+
],
27+
[
28+
'Class ConsistentTemplates\IntVec declares 0 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.',
29+
35,
30+
],
31+
[
32+
'Class ConsistentTemplates\Dict declares 2 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.',
33+
45,
34+
],
35+
[
36+
'Class ConsistentTemplates\Wrapped does not pass its template types to interface ConsistentTemplates\Coll with @phpstan-consistent-templates in the order it declares them.',
37+
54,
38+
],
39+
[
40+
'Bound type object of template type T of class ConsistentTemplates\ObjVec is narrower than bound type mixed of template type T of class ConsistentTemplates\Vec with @phpstan-consistent-templates from interface ConsistentTemplates\Coll.',
41+
72,
42+
],
43+
[
44+
'Class ConsistentTemplates\Flipped does not pass its template types to interface ConsistentTemplates\Pair with @phpstan-consistent-templates in the order it declares them.',
45+
110,
46+
],
47+
[
48+
'Class ConsistentTemplates\PsalmIntVec declares 0 template types, but interface ConsistentTemplates\PsalmColl with @phpstan-consistent-templates declares 1.',
49+
137,
50+
],
51+
[
52+
'Interface ConsistentTemplates\IntSequence declares 0 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.',
53+
154,
54+
],
55+
[
56+
'Class ConsistentTemplates\NoTag does not pass its template types to interface ConsistentTemplates\Sequence with @phpstan-consistent-templates from interface ConsistentTemplates\Coll in the order it declares them.',
57+
162,
58+
],
59+
]);
60+
}
61+
62+
}

0 commit comments

Comments
 (0)