Repository navigation
Expand file tree
/
Copy pathTemplateArgumentFrame.php
More file actions
381 lines (332 loc) · 12.4 KB
/
Copy pathTemplateArgumentFrame.php
File metadata and controls
381 lines (332 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\Generics;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PHPStan\Analyser\ConditionalExpressionHolder;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Reflection\ParametersAcceptor;
use PHPStan\Reflection\ResolvedFunctionVariant;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
use function array_keys;
use function spl_object_id;
use function sprintf;
/**
* Immutable template inference context carried by a scope. The observation walk
* and the resolved walk use distinct instances, including in saved callbacks.
*/
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateArgumentFrame.cpp')]
final class TemplateArgumentFrame
{
/**
* Set on the synthetic nodes handlers build for an on-demand pricing (the
* parent constructor's `new`, a fabricated offsetGet()/__toString() call):
* a fresh node every walk, so it can never be a site the second pass finds
* again. Markers keyed by such a node are re-keyed by the handler that
* built it or stay unobserved.
*/
public const SYNTHETIC_SITE_ATTRIBUTE = 'templateArgumentSyntheticSite';
/**
* Set on a node a handler builds in place of the real one (the nullsafe
* call's plain twin) to the real node, which is the site.
*/
public const ORIGINAL_SITE_ATTRIBUTE = 'templateArgumentOriginalSite';
/**
* The return type of a call the analyser walks: the variant's return type
* with the inferred template arguments unresolved/resolved under the
* scope's frame, the legacy (generalizing) one otherwise.
*/
public static function returnTypeOfCall(ParametersAcceptor $acceptor, MutatingScope $scope, Expr $site, ?bool $allowUnresolved = null): Type
{
$frame = $scope->getCurrentTemplateArgumentFrame();
if ($frame === null || !$acceptor instanceof ResolvedFunctionVariant) {
return $acceptor->getReturnType();
}
$originalSite = $site->getAttribute(self::ORIGINAL_SITE_ATTRIBUTE);
return $acceptor->getReturnTypeWithUnresolvedTemplateArguments(
$originalSite instanceof Expr ? $originalSite : $site,
$frame,
$allowUnresolved ?? !$scope->nativeTypesPromoted,
);
}
/**
* @param array<string, Type>|null $resolutions null during collection
* @param array<int, true> $siteStatementIndexes
* @param Node\Stmt[] $closureSignatureStmts the statements of $closureSignatureBody
* @param array<int, true> $settledClosureSites spl_object_id() of the closure nodes
* @param bool $observingClosures the template arguments are resolved, the closure signatures observed again
* @param array<int, array{Expr\Closure, int, bool}> $byRefSites spl_object_id() of the closure node => the node, its statement index, whether every invocation was seen
* @param array<int, array{Expr\Variable, Type, Type}> $staticVariableTypes spl_object_id() of a `static` variable node => the node, its phpdoc and native type - see StaticVariableInference
* @param array<int, array{Node\Stmt\Static_, array<string, ConditionalExpressionHolder[]>}> $staticVariableConditionalExpressions spl_object_id() of the last statement of a run of `static` statements => the statement, the conditional expressions between the run's variables - see StaticVariableInference::getRuns()
*/
public function __construct(
private readonly ?self $parent,
private readonly ?array $resolutions = null,
private readonly array $siteStatementIndexes = [],
private readonly ?Node $closureSignatureBody = null,
private readonly array $closureSignatureStmts = [],
private readonly array $settledClosureSites = [],
private readonly bool $observingClosures = false,
private readonly array $byRefSites = [],
private readonly array $staticVariableTypes = [],
private readonly array $staticVariableConditionalExpressions = [],
)
{
}
/**
* @return array{Type, Type}|null
*/
public function getStaticVariableTypes(Expr\Variable $var): ?array
{
$types = $this->staticVariableTypes[spl_object_id($var)] ?? null;
if ($types === null || $types[0] !== $var) {
return null;
}
return [$types[1], $types[2]];
}
/**
* @return array<string, ConditionalExpressionHolder[]>
*/
public function getStaticVariableConditionalExpressions(Node\Stmt\Static_ $stmt): array
{
$conditionalExpressions = $this->staticVariableConditionalExpressions[spl_object_id($stmt)] ?? null;
if ($conditionalExpressions === null || $conditionalExpressions[0] !== $stmt) {
return [];
}
return $conditionalExpressions[1];
}
/**
* The frame with the inferred types of the body's `static` variables; the
* statements holding them are walked again in the second pass. The walks
* inferring the types observed, so on a resolved frame the markers of the
* types are replaced by what the frame resolved them to - as the second
* pass replaces them at their sites.
*
* @param array<int, array{Expr\Variable, Type, Type}> $staticVariableTypes
* @param array<int, true> $statementIndexes
* @param array<int, array{Node\Stmt\Static_, array<string, ConditionalExpressionHolder[]>}> $conditionalExpressions
*/
public function withStaticVariableTypes(array $staticVariableTypes, array $statementIndexes, array $conditionalExpressions = []): self
{
if ($this->resolutions !== null) {
foreach ($staticVariableTypes as $id => [$var, $type, $nativeType]) {
$staticVariableTypes[$id] = [$var, $this->resolveMarkers($type), $this->resolveMarkers($nativeType)];
}
}
return new self(
$this->parent,
$this->resolutions,
$this->siteStatementIndexes + $statementIndexes,
$this->closureSignatureBody,
$this->closureSignatureStmts,
$this->settledClosureSites,
$this->observingClosures,
$this->byRefSites,
$staticVariableTypes,
$conditionalExpressions,
);
}
/**
* How the second pass treats the by-ref uses of a closure created in this
* frame's body - see ClosureSignatureInference::getByRefSiteMode().
*
* @return 'local'|'escaped'|null
*/
public function getByRefSiteMode(Expr $site): ?string
{
$byRefSite = $this->byRefSites[spl_object_id($site)] ?? null;
if ($byRefSite !== null && $byRefSite[0] === $site) {
return $byRefSite[2] ? 'local' : 'escaped';
}
return $this->parent !== null ? $this->parent->getByRefSiteMode($site) : null;
}
/**
* The closures of this frame's body whose every invocation was seen, with
* the index of the statement creating them.
*
* @return list<array{Expr\Closure, int}>
*/
public function getLocalByRefSites(): array
{
$sites = [];
foreach ($this->byRefSites as [$site, $statementIndex, $local]) {
if (!$local) {
continue;
}
$sites[] = [$site, $statementIndex];
}
return $sites;
}
/**
* The resolved frame with the closure signatures observed in the closure
* observation pass (see TemplateArgumentResolver::resolveObservedClosures()).
*
* @param array<string, Type> $closureResolutions
* @param array<int, true> $closureSiteStatementIndexes
* @param array<int, true> $settledClosureSites
* @param array<int, array{Expr\Closure, int, bool}> $byRefSites
*/
public function withObservedClosures(array $closureResolutions, array $closureSiteStatementIndexes, array $settledClosureSites, array $byRefSites = []): self
{
return new self(
$this->parent,
($this->resolutions ?? []) + $closureResolutions,
$this->siteStatementIndexes + $closureSiteStatementIndexes,
$this->closureSignatureBody,
$this->closureSignatureStmts,
$settledClosureSites,
byRefSites: $byRefSites,
staticVariableTypes: $this->staticVariableTypes,
staticVariableConditionalExpressions: $this->staticVariableConditionalExpressions,
);
}
/**
* Whether the closure's signature resolved to exactly what its markers stood
* for while observing - its ClosureType keeps them, see
* TemplateArgumentResolver::resolve().
*/
public function isSettledClosureSite(Expr $site): bool
{
if (isset($this->settledClosureSites[spl_object_id($site)])) {
return true;
}
return $this->parent !== null && $this->parent->isSettledClosureSite($site);
}
/** The frame of the body this frame's body is written in. */
public function getParent(): ?self
{
return $this->parent;
}
/**
* The function-like body the frame observes, asked only when a closure in
* it has its signature inferred (see ClosureSignatureInference::isClosedBody()).
*/
public function getClosureSignatureBody(): ?Node
{
return $this->closureSignatureBody;
}
/** @return Node\Stmt[] */
public function getClosureSignatureStmts(): array
{
return $this->closureSignatureStmts;
}
public function isObserving(): bool
{
return $this->resolutions === null;
}
/**
* Whether closures get signature markers and their sends are collected:
* in the observation pass, and in the closure observation pass that walks
* with the template arguments already resolved.
*/
public function isObservingClosures(): bool
{
return $this->resolutions === null || $this->observingClosures;
}
public function firstSiteStatementIndex(): ?int
{
$first = null;
foreach (array_keys($this->siteStatementIndexes) as $index) {
if ($first !== null && $index >= $first) {
continue;
}
$first = $index;
}
return $first;
}
public function ownsSiteInStatement(int $statementIndex): bool
{
return isset($this->siteStatementIndexes[$statementIndex]);
}
public function hasSiteAtOrAfter(int $statementIndex): bool
{
foreach (array_keys($this->siteStatementIndexes) as $index) {
if ($index >= $statementIndex) {
return true;
}
}
return false;
}
/**
* The resolution of the site's template argument, or - for a site this
* frame never observed (never asked during the observation pass, a native
* flavour) - what an unconstrained argument resolves to.
*/
public function resolveOrUnconstrained(Expr $site, TemplateType $template): Type
{
return $this->resolve($site, $template->getName()) ?? self::resolveUnconstrained($site, $template, fn (Expr $site, string $templateName): ?Type => $this->resolve($site, $templateName));
}
/**
* Nothing was inferred, sent or passed in: use the template's default or
* bound, resolving sibling arguments in dependent bounds (`U of T`).
* An unknown argument does not imply that the object holds nothing.
*
* @param callable(Expr, string): ?Type $resolve
*/
public static function resolveUnconstrained(Expr $site, TemplateType $template, callable $resolve): Type
{
$default = $template->getDefault();
if ($default !== null) {
return $default;
}
$bound = $template->getBound();
if (!$bound->hasTemplateOrLateResolvableType()) {
return $bound;
}
$scope = $template->getScope();
return TypeTraverser::map($bound, static function (Type $type, callable $traverse) use ($site, $scope, $resolve): Type {
if ($type instanceof TemplateType && $type->getScope()->equals($scope)) {
return $resolve($site, $type->getName()) ?? $type->getDefault() ?? $traverse($type->getBound());
}
return $traverse($type);
});
}
/**
* The resolved type of a template argument of the site, or null for a site
* this frame and its parents never observed.
*/
public function resolve(Expr $site, string $templateName): ?Type
{
$key = self::key($site, $templateName);
if (isset($this->resolutions[$key])) {
return $this->resolutions[$key];
}
if ($this->parent !== null) {
return $this->parent->resolve($site, $templateName);
}
return null;
}
/**
* Distinguishes cache entries computed while observing from those computed
* with the resolutions installed (the closure type cache keys on scope state
* that does not change between the two passes).
*/
public function getResolutionCacheKeySuffix(): string
{
$frame = $this;
while ($frame !== null) {
if (!$frame->isObserving()) {
return sprintf('|templateArguments:%d', spl_object_id($frame));
}
$frame = $frame->parent;
}
return '';
}
private function resolveMarkers(Type $type): Type
{
return TypeTraverser::map($type, function (Type $type, callable $traverse): Type {
if ($type instanceof UnresolvedTemplateArgumentType && !$type->isClosureSignature()) {
$site = $type->getSite();
return $traverse($this->resolve($site, $type->getTemplateName()) ?? $type->getInitialType() ?? $this->resolveOrUnconstrained($site, $type->getTemplate()));
}
return $traverse($type);
});
}
private static function key(Expr $site, string $templateName): string
{
return spl_object_id($site) . '#' . $templateName;
}
}