Skip to content

Commit b8a57b5

Browse files
committed
Infer types that contain themselves for values a loop nests in itself
A loop that nests the value of a variable in itself on every pass, like `$node = ['next' => $node]`, now gives the variable a recursive type instead of a shape that ends in mixed below the generalization depth limit. When the next pass holds the previous value below an array, the previous value is replaced there with a reference, and the recursive type is kept if it holds both passes. Behind the recursiveLoopTypes bleeding edge toggle. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 9ed20e0 commit b8a57b5

22 files changed

Lines changed: 1182 additions & 1 deletion

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,4 @@ parameters:
4141
reportTemplateInImportedTypeAlias: true
4242
checkConditionalParameterTypes: true
4343
checkMixedWitnessTypes: true
44+
recursiveLoopTypes: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ parameters:
7373
reportTemplateInImportedTypeAlias: false
7474
checkConditionalParameterTypes: false
7575
checkMixedWitnessTypes: false
76+
recursiveLoopTypes: false
7677
fileExtensions:
7778
- php
7879
checkAdvancedIsset: false

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ parametersSchema:
7070
reportTemplateInImportedTypeAlias: bool()
7171
checkConditionalParameterTypes: bool()
7272
checkMixedWitnessTypes: bool()
73+
recursiveLoopTypes: bool()
7374
])
7475
fileExtensions: listOf(string())
7576
checkAdvancedIsset: bool()

‎src/Analyser/DirectInternalScopeFactory.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ public function create(
9393
$this->attributeReflectionFactory,
9494
$this->configuredPhpVersionRangeHelper,
9595
$this->container->getParameter('featureToggles')['checkWholePhpVersionRange'],
96+
$this->container->getParameter('featureToggles')['recursiveLoopTypes'],
9697
$this->nodeCallback,
9798
);
9899

‎src/Analyser/LazyInternalScopeFactory.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ public function create(
9393
$this->container->getByType(AttributeReflectionFactory::class),
9494
$this->container->getByType(ConfiguredPhpVersionRangeHelper::class),
9595
$this->container->getParameter('featureToggles')['checkWholePhpVersionRange'],
96+
$this->container->getParameter('featureToggles')['recursiveLoopTypes'],
9697
$this->nodeCallback,
9798
);
9899

‎src/Analyser/MutatingScope.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
use PHPStan\Type\NeverType;
9999
use PHPStan\Type\NullType;
100100
use PHPStan\Type\ObjectType;
101+
use PHPStan\Type\RecursiveType;
101102
use PHPStan\Type\StaticType;
102103
use PHPStan\Type\StaticTypeFactory;
103104
use PHPStan\Type\StringType;
@@ -6004,6 +6005,30 @@ private function generalizeType(Type $a, Type $b, int $depth, ?Type $entryType =
60046005
return $a;
60056006
}
60066007

6008+
if ($this->services->recursiveLoopTypes) {
6009+
// a type that contains itself already holds what the next pass nests in it
6010+
if ($a instanceof RecursiveType && $a->isSuperTypeOf($b)->yes()) {
6011+
return $a;
6012+
}
6013+
6014+
// a value the loop nests in itself on every pass, like `$node = ['next' => $node]`,
6015+
// contains itself, instead of ending in mixed below the depth limit
6016+
$recursiveType = RecursiveType::fromRepetition($a, $b);
6017+
if ($recursiveType !== null) {
6018+
return $recursiveType;
6019+
}
6020+
6021+
// nested loops each nest it in their own shape, which would end in mixed below the depth limit
6022+
$aDepth = self::getArrayDepth($a) + $depth;
6023+
$bDepth = self::getArrayDepth($b) + $depth;
6024+
if ($aDepth > self::GENERALIZED_ARRAY_DEPTH_LIMIT || $bDepth > self::GENERALIZED_ARRAY_DEPTH_LIMIT) {
6025+
$recursiveType = RecursiveType::fromNestedShapes($a, $b);
6026+
if ($recursiveType !== null) {
6027+
return $recursiveType;
6028+
}
6029+
}
6030+
}
6031+
60076032
// Track whether either input carries a BenevolentUnion so the result
60086033
// can be re-wrapped at the end. `flattenTypes` below drops the
60096034
// BenevolentUnion wrapper, which would silently downgrade e.g.
@@ -6030,6 +6055,11 @@ private function generalizeType(Type $a, Type $b, int $depth, ?Type $entryType =
60306055
'b' => $this->flattenUnionForGeneralization($b),
60316056
] as $key => $types) {
60326057
foreach ($types as $type) {
6058+
// widened part by part, a type that contains itself would be unfolded without end
6059+
if ($this->services->recursiveLoopTypes && $type instanceof RecursiveType) {
6060+
$otherTypes[] = $type;
6061+
continue;
6062+
}
60336063
if ($type instanceof ConstantIntegerType) {
60346064
$constantIntegers[$key][] = $type;
60356065
continue;

‎src/Analyser/ScopeServices.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ public function __construct(
4444
public readonly AttributeReflectionFactory $attributeReflectionFactory,
4545
public readonly ConfiguredPhpVersionRangeHelper $configuredPhpVersionRangeHelper,
4646
public readonly bool $checkWholePhpVersionRange,
47+
public readonly bool $recursiveLoopTypes,
4748
public readonly mixed $nodeCallback,
4849
)
4950
{

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,6 +1157,13 @@ public function isCallable(): TrinaryLogic
11571157
if ($keyTypesCount > 2 || ($keyTypesCount !== 2 && !$this->isUnsealed()->yes())) {
11581158
return TrinaryLogic::createNo();
11591159
}
1160+
foreach ($this->keyTypes as $keyType) {
1161+
// a key other than 0 and 1, like a shape of a linked list that contains itself,
1162+
// whose description sorts a union that asks whether the shape is callable again
1163+
if ($keyType->getValue() !== 0 && $keyType->getValue() !== 1) {
1164+
return TrinaryLogic::createNo();
1165+
}
1166+
}
11601167

11611168
$result = RecursionGuard::run($this, function (): TrinaryLogic {
11621169
$hasNonExistentMethod = false;

‎src/Type/NestedShapeFolder.php‎

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Type;
4+
5+
use PHPStan\Type\Constant\ConstantArrayType;
6+
use PHPStan\Type\Constant\ConstantIntegerType;
7+
use PHPStan\Type\Constant\ConstantStringType;
8+
use function count;
9+
use function implode;
10+
use function in_array;
11+
use function sort;
12+
use function spl_object_id;
13+
14+
/**
15+
* The shapes nested loops nest in each other, by their keys, for
16+
* RecursiveType::fromNestedShapes(): a shape with the keys of one at the top
17+
* of the value folds into the value, keeping the values where the nesting ends.
18+
*
19+
* @internal
20+
*/
21+
final class NestedShapeFolder
22+
{
23+
24+
/** @var array<string, true> the keys the shapes nest each other under */
25+
private array $nestingKeys = [];
26+
27+
/**
28+
* @param array<string, true> $keySets
29+
*/
30+
public function __construct(private array $keySets)
31+
{
32+
}
33+
34+
public static function getKeySet(Type $type): ?string
35+
{
36+
$type = self::getShape($type);
37+
if ($type === null) {
38+
return null;
39+
}
40+
41+
$keys = [];
42+
foreach ($type->getKeyTypes() as $keyType) {
43+
$keys[] = self::getKey($keyType);
44+
}
45+
sort($keys);
46+
47+
return implode("\0", $keys);
48+
}
49+
50+
/** Whether the type is one of the shapes, or a recursive type of them an inner loop made. */
51+
public function folds(Type $type): bool
52+
{
53+
if ($type instanceof RecursiveType) {
54+
$body = $type->getBody();
55+
$found = false;
56+
foreach ($body instanceof UnionType ? $body->getTypes() : [$body] as $member) {
57+
$keySet = self::getKeySet($member);
58+
if ($keySet === null) {
59+
continue;
60+
}
61+
if (!isset($this->keySets[$keySet])) {
62+
return false;
63+
}
64+
$found = true;
65+
}
66+
67+
return $found;
68+
}
69+
70+
$keySet = self::getKeySet($type);
71+
72+
return $keySet !== null && isset($this->keySets[$keySet]);
73+
}
74+
75+
public function collectNestingKeys(Type $type): void
76+
{
77+
$this->walk($type, function (string $key, Type $value): void {
78+
// a reference is a shape the value nests in itself
79+
if (!$value instanceof RecursiveTypeReference && !$this->folds($value)) {
80+
return;
81+
}
82+
83+
$this->nestingKeys[$key] = true;
84+
});
85+
}
86+
87+
/**
88+
* The values under the nesting keys that are not shapes, at every depth.
89+
*
90+
* @return list<Type>
91+
*/
92+
public function getEnds(Type $type): array
93+
{
94+
$ends = [];
95+
if ($type instanceof RecursiveType) {
96+
$body = $type->getBody();
97+
foreach ($body instanceof UnionType ? $body->getTypes() : [$body] as $member) {
98+
if ($member instanceof RecursiveTypeReference || $this->folds($member) || in_array($member, $ends, true)) {
99+
continue;
100+
}
101+
$ends[] = $member;
102+
}
103+
}
104+
$this->walk($type, function (string $key, Type $value) use (&$ends): void {
105+
if (
106+
!isset($this->nestingKeys[$key])
107+
|| $value instanceof RecursiveTypeReference
108+
|| $this->folds($value)
109+
|| in_array($value, $ends, true)
110+
) {
111+
return;
112+
}
113+
114+
$ends[] = $value;
115+
});
116+
117+
return $ends;
118+
}
119+
120+
/**
121+
* The shapes in the values of the shapes in the type, at every depth, with
122+
* a recursive type an inner loop made unfolded, so that its references stay bound.
123+
*
124+
* @return list<Type>
125+
*/
126+
public function getNestedShapes(Type $type): array
127+
{
128+
$shapes = [];
129+
$visited = [];
130+
$this->collectShapes($type, false, $shapes, $visited);
131+
132+
return $shapes;
133+
}
134+
135+
/**
136+
* @param list<Type> $shapes
137+
* @param array<int, true> $visited the recursive types already unfolded
138+
*/
139+
private function collectShapes(Type $type, bool $nested, array &$shapes, array &$visited): void
140+
{
141+
if ($type instanceof RecursiveType) {
142+
if (isset($visited[spl_object_id($type)])) {
143+
return;
144+
}
145+
$visited[spl_object_id($type)] = true;
146+
$type = $type->unfold();
147+
}
148+
if ($type instanceof UnionType) {
149+
foreach ($type->getTypes() as $member) {
150+
$this->collectShapes($member, $nested, $shapes, $visited);
151+
}
152+
return;
153+
}
154+
$shape = self::getShape($type);
155+
if ($shape === null || !$this->folds($type)) {
156+
return;
157+
}
158+
if ($nested && !in_array($type, $shapes, true)) {
159+
$shapes[] = $type;
160+
}
161+
foreach ($shape->getValueTypes() as $valueType) {
162+
$this->collectShapes($valueType, true, $shapes, $visited);
163+
}
164+
}
165+
166+
/**
167+
* Calls $visit with each key and member of a value of the shapes in the type,
168+
* the shapes in their values too, and the members of a recursive type there.
169+
*
170+
* @param callable(string, Type): void $visit
171+
*/
172+
private function walk(Type $type, callable $visit): void
173+
{
174+
$visited = [];
175+
$this->walkShapes($type, $visit, $visited);
176+
}
177+
178+
/**
179+
* @param callable(string, Type): void $visit
180+
* @param array<int, true> $visited the recursive types already walked
181+
*/
182+
private function walkShapes(Type $type, callable $visit, array &$visited): void
183+
{
184+
if ($type instanceof RecursiveType) {
185+
if (isset($visited[spl_object_id($type)])) {
186+
return;
187+
}
188+
$visited[spl_object_id($type)] = true;
189+
$type = $type->getBody();
190+
}
191+
foreach ($type instanceof UnionType ? $type->getTypes() : [$type] as $member) {
192+
$shape = self::getShape($member);
193+
if ($shape === null || !$this->folds($member)) {
194+
continue;
195+
}
196+
foreach ($shape->getKeyTypes() as $i => $keyType) {
197+
$this->walkValue(self::getKey($keyType), $shape->getValueTypes()[$i], $visit, $visited);
198+
}
199+
}
200+
}
201+
202+
/**
203+
* @param callable(string, Type): void $visit
204+
* @param array<int, true> $visited the recursive types already walked
205+
*/
206+
private function walkValue(string $key, Type $value, callable $visit, array &$visited): void
207+
{
208+
foreach ($value instanceof UnionType ? $value->getTypes() : [$value] as $member) {
209+
$visit($key, $member);
210+
if ($member instanceof RecursiveType) {
211+
if (isset($visited[spl_object_id($member)])) {
212+
continue;
213+
}
214+
$visited[spl_object_id($member)] = true;
215+
// what the recursive type holds besides its shapes is there too, like null
216+
$this->walkValue($key, $member->getBody(), $visit, $visited);
217+
continue;
218+
}
219+
$this->walkShapes($member, $visit, $visited);
220+
}
221+
}
222+
223+
/** The shape the type is, but not a recursive type or its reference, which only unfold to one. */
224+
private static function getShape(Type $type): ?ConstantArrayType
225+
{
226+
if ($type instanceof RecursiveType || $type instanceof RecursiveTypeReference) {
227+
return null;
228+
}
229+
230+
$constantArrays = $type->getConstantArrays();
231+
if (count($constantArrays) !== 1 || !$type->isConstantArray()->yes()) {
232+
return null;
233+
}
234+
235+
return $constantArrays[0];
236+
}
237+
238+
private static function getKey(ConstantIntegerType|ConstantStringType $keyType): string
239+
{
240+
return ($keyType instanceof ConstantIntegerType ? 'i' : 's') . $keyType->getValue();
241+
}
242+
243+
}

0 commit comments

Comments
 (0)