Skip to content

Commit 31f6bc8

Browse files
committed
Do the work on a type shared by nested types once
Compiled Twig templates store the whole context in itself at every for-loop (`$context['_parent'] = $context`, and again in loop.parent), so the same types are members of every nesting level. Walking them once per path leading to them is exponential in the depth. Immutable types now remember what such walks ask them: - generalize() of ConstantArrayType, UnionType, IntersectionType, ArrayType and HasOffsetValueType, per precision - the normalized value at an index of ConstantArrayType - UnionType::getOffsetValueType() per offset, like IntersectionType does - IntersectionType::isSuperTypeOf() of plain mixed ConstantArrayType::isSuperTypeOf() and equals() also answer for the same object without comparing the members. The inferred types do not change. The turbo-ext mirrors get the same fast paths and memos where the native code does not already have them. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c574-f264-7659-8779-5e71ca99b89b
1 parent 12e1dc5 commit 31f6bc8

20 files changed

Lines changed: 2390 additions & 1987 deletions

‎src/Type/Accessory/HasOffsetValueType.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use PHPStan\Type\ConstantScalarType;
2020
use PHPStan\Type\Enum\EnumCaseObjectType;
2121
use PHPStan\Type\ErrorType;
22+
use PHPStan\Type\GeneralizePrecision;
2223
use PHPStan\Type\IntegerRangeType;
2324
use PHPStan\Type\IntegerType;
2425
use PHPStan\Type\IntersectionType;
@@ -43,6 +44,7 @@
4344
use PHPStan\Type\TypeCombinator;
4445
use PHPStan\Type\UnionType;
4546
use PHPStan\Type\VerbosityLevel;
47+
use function spl_object_id;
4648
use function sprintf;
4749
use function strtolower;
4850
use function strtoupper;
@@ -68,6 +70,17 @@ public function __construct(private ConstantStringType|ConstantIntegerType $offs
6870
{
6971
}
7072

73+
/** @var array<int, Type> */
74+
private array $generalizedTypes = [];
75+
76+
public function generalize(GeneralizePrecision $precision): Type
77+
{
78+
// Immutable, so it generalizes the same way every time - remembered
79+
// because a member shared by several nested types is otherwise
80+
// generalized once per path leading to it (see ConstantArrayType::generalize()).
81+
return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
82+
}
83+
7184
public function getOffsetType(): ConstantStringType|ConstantIntegerType
7285
{
7386
return $this->offsetType;

‎src/Type/ArrayType.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
use function array_merge;
4545
use function count;
4646
use function in_array;
47+
use function spl_object_id;
4748
use function sprintf;
4849
use function strtolower;
4950
use function strtoupper;
@@ -88,6 +89,17 @@ public function __construct(Type $keyType, private Type $itemType)
8889
$this->keyType = $keyType;
8990
}
9091

92+
/** @var array<int, Type> */
93+
private array $generalizedTypes = [];
94+
95+
public function generalize(GeneralizePrecision $precision): Type
96+
{
97+
// Immutable, so it generalizes the same way every time - remembered
98+
// because a member shared by several nested types is otherwise
99+
// generalized once per path leading to it (see ConstantArrayType::generalize()).
100+
return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
101+
}
102+
91103
public function getKeyType(): Type
92104
{
93105
return $this->keyType;

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,12 @@ public function __construct(
212212
$this->unsealed = $unsealed;
213213
}
214214

215+
/** @var array<int, Type> */
216+
private array $normalizedValueTypes = [];
217+
218+
/** @var array<int, Type> */
219+
private array $generalizedTypes = [];
220+
215221
public function isSealed(): TrinaryLogic
216222
{
217223
return $this->isUnsealed()->negate();
@@ -782,6 +788,13 @@ private function checkOurKeys(Type $type, bool $strictTypes): AcceptsResult
782788

783789
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
784790
{
791+
// Shapes nested in each other share their members (`$a['parent'] = $a`),
792+
// so comparing two of them meets the same member on both sides along
793+
// every path leading to it.
794+
if ($type === $this) {
795+
return IsSuperTypeOfResult::createYes();
796+
}
797+
785798
if ($type instanceof self) {
786799
$thisUnsealedness = $this->isUnsealed();
787800
$typeUnsealedness = $type->isUnsealed();
@@ -980,6 +993,10 @@ public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
980993

981994
public function equals(Type $type): bool
982995
{
996+
if ($type === $this) {
997+
return true;
998+
}
999+
9831000
if (!$type instanceof self) {
9841001
return false;
9851002
}
@@ -1326,7 +1343,10 @@ public function getOffsetValueType(Type $offsetType): Type
13261343
// maybe-all fallbacks apply and the unsealed extras cannot contribute.
13271344
$index = $this->findVerifiedKeyIndex($offsetType);
13281345
if ($index !== null) {
1329-
$type = TypeCombinator::union($this->valueTypes[$index]);
1346+
// The shape is immutable, so the normalized value at an index is
1347+
// computed once. Comparing nested shapes asks for the same offsets
1348+
// over and over, and normalizing a union of shapes is not cheap.
1349+
$type = $this->normalizedValueTypes[$index] ??= TypeCombinator::union($this->valueTypes[$index]);
13301350
if ($type instanceof ErrorType) {
13311351
return new MixedType();
13321352
}
@@ -2471,6 +2491,15 @@ public function generalize(GeneralizePrecision $precision): Type
24712491
return $this;
24722492
}
24732493

2494+
// The shape is immutable, so it generalizes the same way every time.
2495+
// Shapes nested in each other share their members (`$a['parent'] = $a`),
2496+
// and without remembering the result every path to a shared member
2497+
// generalizes it again - exponential in the nesting depth.
2498+
return $this->generalizedTypes[spl_object_id($precision)] ??= $this->doGeneralize($precision);
2499+
}
2500+
2501+
private function doGeneralize(GeneralizePrecision $precision): Type
2502+
{
24742503
if ($precision->isTemplateArgument()) {
24752504
return $this->traverse(static fn (Type $type) => $type->generalize($precision));
24762505
}

‎src/Type/IntersectionType.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
use function is_int;
6969
use function is_string;
7070
use function ksort;
71+
use function spl_object_id;
7172
use function sprintf;
7273
use function str_starts_with;
7374
use function strcasecmp;
@@ -145,6 +146,20 @@ public function __construct(private array $types)
145146
}
146147
}
147148

149+
/** @var array<int, Type> */
150+
private array $generalizedTypes = [];
151+
152+
/** @var array<int, IsSuperTypeOfResult> */
153+
private array $superTypeOfMixedResults = [];
154+
155+
public function generalize(GeneralizePrecision $precision): Type
156+
{
157+
// Immutable, so it generalizes the same way every time - remembered
158+
// because a member shared by several nested types is otherwise
159+
// generalized once per path leading to it (see ConstantArrayType::generalize()).
160+
return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
161+
}
162+
148163
/**
149164
* @return list<Type>
150165
*/
@@ -311,6 +326,15 @@ public function isSuperTypeOf(Type $otherType): IsSuperTypeOfResult
311326
return IsSuperTypeOfResult::createYes();
312327
}
313328

329+
if ($otherType::class === MixedType::class && $otherType->getSubtractedType() === null) {
330+
// Immutable, so it compares to plain mixed the same way every time -
331+
// remembered because comparing to mixed walks every nested member,
332+
// and a member shared by several nested types (e.g. a snapshot of
333+
// an array stored in it at every nesting level) is otherwise
334+
// walked once per path leading to it.
335+
return $this->superTypeOfMixedResults[(int) $otherType->isExplicitMixed()] ??= IsSuperTypeOfResult::createYes()->and(...array_map(static fn (Type $innerType) => $innerType->isSuperTypeOf($otherType), $this->types));
336+
}
337+
314338
return IsSuperTypeOfResult::createYes()->and(...array_map(static fn (Type $innerType) => $innerType->isSuperTypeOf($otherType), $this->types));
315339
}
316340

‎src/Type/UnionType.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
use function array_values;
5252
use function count;
5353
use function implode;
54+
use function spl_object_id;
5455
use function sprintf;
5556
use function str_contains;
5657

@@ -130,6 +131,20 @@ public function __construct(private array $types, private bool $normalized = fal
130131
}
131132
}
132133

134+
/** @var array<int, Type> */
135+
private array $generalizedTypes = [];
136+
137+
/** @var array<string, Type> */
138+
private array $cachedGetOffsetValueType = [];
139+
140+
public function generalize(GeneralizePrecision $precision): Type
141+
{
142+
// Immutable, so it generalizes the same way every time - remembered
143+
// because a member shared by several nested types is otherwise
144+
// generalized once per path leading to it (see ConstantArrayType::generalize()).
145+
return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
146+
}
147+
133148
/**
134149
* @return list<Type>
135150
*/
@@ -994,6 +1009,15 @@ public function hasOffsetValueType(Type $offsetType): TrinaryLogic
9941009
}
9951010

9961011
public function getOffsetValueType(Type $offsetType): Type
1012+
{
1013+
// Immutable, so it answers the same way every time - remembered
1014+
// because comparing nested shapes looks the same offset up on the
1015+
// same union once per path leading to it, and a new union each time
1016+
// would also defeat the memos of the types inside the result.
1017+
return $this->cachedGetOffsetValueType[$offsetType->describe(VerbosityLevel::cache())] ??= $this->doGetOffsetValueType($offsetType);
1018+
}
1019+
1020+
private function doGetOffsetValueType(Type $offsetType): Type
9971021
{
9981022
$types = [];
9991023
foreach ($this->types as $innerType) {
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace BenchNestedContextSnapshots;
4+
5+
use Countable;
6+
7+
/**
8+
* Shaped like a compiled Twig template with nested for-loops: every loop
9+
* stores the whole context in $context['_parent'] and in loop.parent, so
10+
* the same members are shared by every nesting level, and walking them
11+
* once per path leading to them is exponential in the depth.
12+
*
13+
* @param array{known: int, dynamic: mixed, metadata: array{null, null, null, null, null}} $context
14+
* @return iterable<mixed>
15+
*/
16+
function doDisplay(array $context): iterable
17+
{
18+
yield $context['known'];
19+
$context['_parent'] = $context;
20+
$context['_seq'] = range(1, 3);
21+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
22+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
23+
$length = count($context['_seq']);
24+
$context['loop']['revindex0'] = $length - 1;
25+
$context['loop']['revindex'] = $length;
26+
$context['loop']['length'] = $length;
27+
$context['loop']['last'] = 1 === $length;
28+
}
29+
foreach ($context['_seq'] as $context['_key'] => $context['l1']) {
30+
yield $context['loop']['index'];
31+
yield $context['known'];
32+
$context['_parent'] = $context;
33+
$context['_seq'] = range(1, 3);
34+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
35+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
36+
$length = count($context['_seq']);
37+
$context['loop']['revindex0'] = $length - 1;
38+
$context['loop']['revindex'] = $length;
39+
$context['loop']['length'] = $length;
40+
$context['loop']['last'] = 1 === $length;
41+
}
42+
foreach ($context['_seq'] as $context['_key'] => $context['l2']) {
43+
yield $context['loop']['index'];
44+
yield $context['known'];
45+
$context['_parent'] = $context;
46+
$context['_seq'] = range(1, 3);
47+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
48+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
49+
$length = count($context['_seq']);
50+
$context['loop']['revindex0'] = $length - 1;
51+
$context['loop']['revindex'] = $length;
52+
$context['loop']['length'] = $length;
53+
$context['loop']['last'] = 1 === $length;
54+
}
55+
foreach ($context['_seq'] as $context['_key'] => $context['l3']) {
56+
yield $context['loop']['index'];
57+
yield $context['known'];
58+
$context['_parent'] = $context;
59+
$context['_seq'] = range(1, 3);
60+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
61+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
62+
$length = count($context['_seq']);
63+
$context['loop']['revindex0'] = $length - 1;
64+
$context['loop']['revindex'] = $length;
65+
$context['loop']['length'] = $length;
66+
$context['loop']['last'] = 1 === $length;
67+
}
68+
foreach ($context['_seq'] as $context['_key'] => $context['l4']) {
69+
yield $context['loop']['index'];
70+
yield $context['known'];
71+
$context['_parent'] = $context;
72+
$context['_seq'] = range(1, 3);
73+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
74+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
75+
$length = count($context['_seq']);
76+
$context['loop']['revindex0'] = $length - 1;
77+
$context['loop']['revindex'] = $length;
78+
$context['loop']['length'] = $length;
79+
$context['loop']['last'] = 1 === $length;
80+
}
81+
foreach ($context['_seq'] as $context['_key'] => $context['l5']) {
82+
yield $context['loop']['index'];
83+
yield $context['known'];
84+
$context['_parent'] = $context;
85+
$context['_seq'] = range(1, 3);
86+
$context['loop'] = ['parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true];
87+
if (is_array($context['_seq']) || is_object($context['_seq']) && $context['_seq'] instanceof Countable) {
88+
$length = count($context['_seq']);
89+
$context['loop']['revindex0'] = $length - 1;
90+
$context['loop']['revindex'] = $length;
91+
$context['loop']['length'] = $length;
92+
$context['loop']['last'] = 1 === $length;
93+
}
94+
foreach ($context['_seq'] as $context['_key'] => $context['l6']) {
95+
yield $context['loop']['index'];
96+
++$context['loop']['index0'];
97+
++$context['loop']['index'];
98+
$context['loop']['first'] = false;
99+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
100+
--$context['loop']['revindex0'];
101+
--$context['loop']['revindex'];
102+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
103+
}
104+
}
105+
$_parent = $context['_parent'];
106+
unset($context['_seq'], $context['_key'], $context['l6'], $context['_parent'], $context['loop']);
107+
$context = array_intersect_key($context, $_parent) + $_parent;
108+
++$context['loop']['index0'];
109+
++$context['loop']['index'];
110+
$context['loop']['first'] = false;
111+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
112+
--$context['loop']['revindex0'];
113+
--$context['loop']['revindex'];
114+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
115+
}
116+
}
117+
$_parent = $context['_parent'];
118+
unset($context['_seq'], $context['_key'], $context['l5'], $context['_parent'], $context['loop']);
119+
$context = array_intersect_key($context, $_parent) + $_parent;
120+
++$context['loop']['index0'];
121+
++$context['loop']['index'];
122+
$context['loop']['first'] = false;
123+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
124+
--$context['loop']['revindex0'];
125+
--$context['loop']['revindex'];
126+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
127+
}
128+
}
129+
$_parent = $context['_parent'];
130+
unset($context['_seq'], $context['_key'], $context['l4'], $context['_parent'], $context['loop']);
131+
$context = array_intersect_key($context, $_parent) + $_parent;
132+
++$context['loop']['index0'];
133+
++$context['loop']['index'];
134+
$context['loop']['first'] = false;
135+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
136+
--$context['loop']['revindex0'];
137+
--$context['loop']['revindex'];
138+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
139+
}
140+
}
141+
$_parent = $context['_parent'];
142+
unset($context['_seq'], $context['_key'], $context['l3'], $context['_parent'], $context['loop']);
143+
$context = array_intersect_key($context, $_parent) + $_parent;
144+
++$context['loop']['index0'];
145+
++$context['loop']['index'];
146+
$context['loop']['first'] = false;
147+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
148+
--$context['loop']['revindex0'];
149+
--$context['loop']['revindex'];
150+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
151+
}
152+
}
153+
$_parent = $context['_parent'];
154+
unset($context['_seq'], $context['_key'], $context['l2'], $context['_parent'], $context['loop']);
155+
$context = array_intersect_key($context, $_parent) + $_parent;
156+
++$context['loop']['index0'];
157+
++$context['loop']['index'];
158+
$context['loop']['first'] = false;
159+
if (isset($context['loop']['revindex0'], $context['loop']['revindex'])) {
160+
--$context['loop']['revindex0'];
161+
--$context['loop']['revindex'];
162+
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
163+
}
164+
}
165+
$_parent = $context['_parent'];
166+
unset($context['_seq'], $context['_key'], $context['l1'], $context['_parent'], $context['loop']);
167+
$context = array_intersect_key($context, $_parent) + $_parent;
168+
yield $context['known'];
169+
}

0 commit comments

Comments
 (0)