Skip to content

Commit 6c839c6

Browse files
committed
Resolve templates of the declaring class in imported type aliases to their bounds
`@phpstan-import-type TList from Coll` with `@phpstan-type TList list<T>` on a generic Coll used to leak `T of object (class Coll)` into the importing class, where it means nothing. It is now `list<object>`. Coll itself keeps its own T. An imported alias that mentions such a template is reported under bleeding edge (typeAlias.importedTemplateType). Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 61ff452 commit 6c839c6

8 files changed

Lines changed: 157 additions & 1 deletion

File tree

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ parameters:
3838
replaceCountMismatch: true
3939
checkMoreParameterCastableToStringFunctions: true
4040
checkTemplateTypeBounds: true
41+
reportTemplateInImportedTypeAlias: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ parameters:
7070
replaceCountMismatch: false
7171
checkMoreParameterCastableToStringFunctions: false
7272
checkTemplateTypeBounds: false
73+
reportTemplateInImportedTypeAlias: false
7374
fileExtensions:
7475
- php
7576
checkAdvancedIsset: false

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ parametersSchema:
6767
replaceCountMismatch: bool()
6868
checkMoreParameterCastableToStringFunctions: bool()
6969
checkTemplateTypeBounds: bool()
70+
reportTemplateInImportedTypeAlias: bool()
7071
])
7172
fileExtensions: listOf(string())
7273
checkAdvancedIsset: bool()

‎src/Rules/Classes/LocalTypeAliasesCheck.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ public function __construct(
5353
private bool $checkClassCaseSensitivity,
5454
#[AutowiredParameter(ref: '%tips.discoveringSymbols%')]
5555
private bool $discoveringSymbolsTip,
56+
#[AutowiredParameter(ref: '%featureToggles.reportTemplateInImportedTypeAlias%')]
57+
private bool $reportTemplateInImportedTypeAlias = false,
5658
)
5759
{
5860
}
@@ -148,6 +150,34 @@ public function checkInTraitDefinitionContext(ClassReflection $reflection): arra
148150
}
149151

150152
$importedAliases[] = $aliasName;
153+
154+
if (!$this->reportTemplateInImportedTypeAlias) {
155+
continue;
156+
}
157+
158+
$templateTypes = [];
159+
TypeTraverser::map($typeAliases[$importedAlias]->resolve($this->typeNodeResolver), static function (Type $type, callable $traverse) use ($importedFromReflection, &$templateTypes): Type {
160+
if (
161+
$type instanceof TemplateType
162+
&& $type->getScope()->getFunctionName() === null
163+
&& $type->getScope()->getClassName() === $importedFromReflection->getName()
164+
) {
165+
$templateTypes[$type->getName()] = $type;
166+
}
167+
168+
return $traverse($type);
169+
});
170+
171+
foreach ($templateTypes as $templateType) {
172+
$errors[] = RuleErrorBuilder::message(sprintf(
173+
'Imported type alias %s refers to template type %s of %s, which resolves to its bound %s in %s.',
174+
$aliasName,
175+
$templateType->getName(),
176+
$importedFromReflection->getDisplayName(),
177+
$templateType->getBound()->describe(VerbosityLevel::typeOnly()),
178+
$className,
179+
))->identifier('typeAlias.importedTemplateType')->build();
180+
}
151181
}
152182

153183
foreach ($phpDoc->getTypeAliasTags() as $typeAliasTag) {

‎src/Type/UsefulTypeAliasResolver.php‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use PHPStan\PhpDoc\TypeStringResolver;
1111
use PHPStan\Reflection\ReflectionProvider;
1212
use PHPStan\ShouldNotHappenException;
13+
use PHPStan\Type\Generic\TemplateType;
1314
use function array_key_exists;
1415
use function sprintf;
1516

@@ -119,7 +120,10 @@ private function resolveLocalTypeAlias(string $aliasName, NameScope $nameScope):
119120

120121
try {
121122
$unresolvedAlias = $localTypeAliases[$aliasName];
122-
$resolvedAliasType = $unresolvedAlias->resolve($this->typeNodeResolver);
123+
$resolvedAliasType = self::resolveForeignTemplatesToBounds(
124+
$unresolvedAlias->resolve($this->typeNodeResolver),
125+
$className,
126+
);
123127
} catch (CircularTypeAliasDefinitionException) {
124128
$resolvedAliasType = new CircularTypeAliasErrorType();
125129
}
@@ -132,6 +136,26 @@ private function resolveLocalTypeAlias(string $aliasName, NameScope $nameScope):
132136
return $resolvedAliasType;
133137
}
134138

139+
/**
140+
* An alias imported from another class may mention that class's templates,
141+
* which mean nothing in $className, so they are replaced by their bounds.
142+
*/
143+
private static function resolveForeignTemplatesToBounds(Type $type, string $className): Type
144+
{
145+
return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($className): Type {
146+
if (!$type instanceof TemplateType) {
147+
return $traverse($type);
148+
}
149+
150+
$scope = $type->getScope();
151+
if ($scope->getFunctionName() !== null || $scope->getClassName() === null || $scope->getClassName() === $className) {
152+
return $traverse($type);
153+
}
154+
155+
return $traverse($type->getBound());
156+
});
157+
}
158+
135159
private function resolveGlobalTypeAlias(string $aliasName, NameScope $nameScope): ?Type
136160
{
137161
if (!array_key_exists($aliasName, $this->globalTypeAliases)) {
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
namespace ImportedTypeAliasTemplateNsrt;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template T of object
9+
* @phpstan-type TList list<T>
10+
* @phpstan-type TNested array{items: TList}
11+
*/
12+
class Coll
13+
{
14+
15+
/** @param TList $l */
16+
public function own($l): void
17+
{
18+
assertType('list<T of object (class ImportedTypeAliasTemplateNsrt\Coll, argument)>', $l);
19+
}
20+
21+
}
22+
23+
/**
24+
* @phpstan-import-type TList from Coll
25+
* @phpstan-import-type TNested from Coll
26+
*/
27+
class Importer
28+
{
29+
30+
/**
31+
* @param TList $l
32+
* @param TNested $n
33+
*/
34+
public function a($l, $n): void
35+
{
36+
assertType('list<object>', $l);
37+
assertType('array{items: list<object>}', $n);
38+
}
39+
40+
}
41+
42+
/**
43+
* @template T of int
44+
* @phpstan-import-type TList from Coll
45+
*/
46+
class SameNameTemplate
47+
{
48+
49+
/** @param TList $l */
50+
public function a($l): void
51+
{
52+
assertType('list<object>', $l);
53+
}
54+
55+
}

‎tests/PHPStan/Rules/Classes/LocalTypeAliasesRuleTest.php‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
class LocalTypeAliasesRuleTest extends RuleTestCase
2222
{
2323

24+
private bool $reportTemplateInImportedTypeAlias = false;
25+
2426
protected function getRule(): Rule
2527
{
2628
$reflectionProvider = self::createReflectionProvider();
@@ -43,6 +45,7 @@ protected function getRule(): Rule
4345
true,
4446
true,
4547
true,
48+
$this->reportTemplateInImportedTypeAlias,
4649
),
4750
);
4851
}
@@ -162,4 +165,24 @@ public function testEnums(): void
162165
]);
163166
}
164167

168+
public function testImportedTemplateType(): void
169+
{
170+
$this->reportTemplateInImportedTypeAlias = true;
171+
$this->analyse([__DIR__ . '/data/imported-type-alias-template.php'], [
172+
[
173+
'Imported type alias TList refers to template type T of ImportedTypeAliasTemplate\\Coll, which resolves to its bound object in ImportedTypeAliasTemplate\\Importer.',
174+
19,
175+
],
176+
[
177+
'Imported type alias Renamed refers to template type T of ImportedTypeAliasTemplate\\Coll, which resolves to its bound object in ImportedTypeAliasTemplate\\Importer.',
178+
19,
179+
],
180+
]);
181+
}
182+
183+
public function testImportedTemplateTypeWithoutToggle(): void
184+
{
185+
$this->analyse([__DIR__ . '/data/imported-type-alias-template.php'], []);
186+
}
187+
165188
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace ImportedTypeAliasTemplate;
4+
5+
/**
6+
* @template T of object
7+
* @phpstan-type TList list<T>
8+
* @phpstan-type TPlain array<string, int>
9+
*/
10+
class Coll
11+
{
12+
}
13+
14+
/**
15+
* @phpstan-import-type TList from Coll
16+
* @phpstan-import-type TPlain from Coll
17+
* @phpstan-import-type TList from Coll as Renamed
18+
*/
19+
class Importer
20+
{
21+
}

0 commit comments

Comments
 (0)