Repository navigation
Expand file tree
/
Copy pathWhileHandler.php
More file actions
264 lines (248 loc) · 11.3 KB
/
Copy pathWhileHandler.php
File metadata and controls
264 lines (248 loc) · 11.3 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\StmtHandler;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\While_;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\InternalStatementResult;
use PHPStan\Analyser\LoopWrittenVariableNames;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\NoopNodeCallback;
use PHPStan\Analyser\RecordingNodeCallback;
use PHPStan\Analyser\StatementContext;
use PHPStan\Analyser\StmtHandler;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\BreaklessWhileLoopNode;
use PHPStan\Turbo\ShadowedByTurboExtension;
use function array_merge;
use function count;
/**
* @implements StmtHandler<While_>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/WhileHandler.cpp')]
final class WhileHandler implements StmtHandler
{
public function __construct(
#[AutowiredParameter]
private bool $polluteScopeWithLoopInitialAssignments,
#[AutowiredParameter]
private bool $treatPhpDocTypesAsCertain,
)
{
}
public function supports(Stmt $stmt): bool
{
return $stmt instanceof While_;
}
public function processStmt(
NodeScopeResolver $nodeScopeResolver,
Stmt $stmt,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
$originalStorage = $storage;
$storage = $originalStorage->duplicate();
// pass-local storages are pushed for the duration of each pass so
// in-pass asks (applySpecifiedTypes pricing, branch-scope derivation)
// read the pass's own results instead of re-pricing on demand
$scope->pushExpressionResultStorage($storage);
try {
$condResult = $nodeScopeResolver->processExprNode($stmt, $stmt->cond, $scope, $storage, new NoopNodeCallback(), ExpressionContext::createDeep(resolveTemplateArguments: false));
$beforeCondBooleanType = ($this->treatPhpDocTypesAsCertain ? $condResult->getType() : $condResult->getNativeType())->toBoolean();
$condScope = $condResult->getFalseyScope();
if (!$context->isTopLevel() && $beforeCondBooleanType->isFalse()->yes()) {
if (!$this->polluteScopeWithLoopInitialAssignments) {
$scope = $condScope->mergeWith($scope);
}
return new InternalStatementResult(
$scope,
hasYield: $condResult->hasYield(),
isAlwaysTerminating: false,
exitPoints: [],
throwPoints: $condResult->getThrowPoints(),
impurePoints: $condResult->getImpurePoints(),
variableFlow: $condResult->getVariableFlow(),
);
}
$bodyScope = $condResult->getTruthyScope();
} finally {
$scope->popExpressionResultStorage();
}
$replayCondRecording = null;
$replayBodyRecording = null;
$replayCondResult = null;
$replayPassStorage = null;
$replayPassResult = null;
$prevEntryScope = null;
$previousPass = null;
$previousPassStorage = null;
if ($context->shouldConvergeLoops()) {
$count = 0;
$bodyIsReplayable = $nodeScopeResolver->isReplayableConvergenceBody($stmt, $stmt->stmts);
do {
$prevScope = $bodyScope;
$bodyScope = $bodyScope->mergeWith($scope);
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
// walking is deterministic in the entry scope - an unchanged entry
// reproduces the previous pass's exit, so the verification walk is skipped
$bodyScope = $prevScope;
break;
}
$prevEntryScope = $bodyScope;
$storage = $originalStorage->duplicate();
if ($previousPassStorage !== null) {
// the statements this pass replays answer from the results the previous pass stored
$storage->mergeResults($previousPassStorage);
}
$condRecording = $bodyIsReplayable ? new RecordingNodeCallback() : new NoopNodeCallback();
$bodyRecording = new RecordingNodeCallback();
$scope->pushExpressionResultStorage($storage);
try {
$passCondResult = $nodeScopeResolver->processExprNode($stmt, $stmt->cond, $bodyScope, $storage, $condRecording, ExpressionContext::createDeep(resolveTemplateArguments: false));
$bodyScope = $passCondResult->getTruthyScope();
$passRecord = null;
$bodyScopeResult = $nodeScopeResolver->processLoopPassStmtNodes($stmt, $stmt->stmts, $bodyScope, $storage, $bodyRecording, $context->enterLoopPass()->withoutTemplateArgumentResolution(), $previousPass, $passRecord)->filterOutLoopExitPoints();
$previousPass = $passRecord;
$previousPassStorage = $storage;
$backEdgeScope = $bodyScopeResult->getLoopBackEdgeScope();
} finally {
$scope->popExpressionResultStorage();
}
if ($backEdgeScope === null) {
$bodyScope = $prevScope;
break;
}
$bodyScope = $backEdgeScope;
// the candidate to replace the final walk when this pass's
// entry turns out to be the fixpoint
if ($condRecording instanceof RecordingNodeCallback) {
$replayCondRecording = $condRecording;
$replayBodyRecording = $bodyRecording;
$replayPassStorage = $storage;
$replayPassResult = $bodyScopeResult;
$replayCondResult = $passCondResult;
}
if ($bodyScope->equals($prevScope)) {
break;
}
if ($count >= NodeScopeResolver::GENERALIZE_AFTER_ITERATION) {
$bodyScope = $prevScope->generalizeWith(
$bodyScope,
LoopWrittenVariableNames::collect($stmt, VariableFlow::sequence($passCondResult->getVariableFlow(), $bodyScopeResult->getVariableFlow())),
);
}
$count++;
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
}
$bodyScope = $bodyScope->mergeWith($scope);
$bodyScopeMaybeRan = $bodyScope;
$storage = $originalStorage;
if (
$replayCondRecording !== null && $replayBodyRecording !== null
&& $replayPassStorage !== null && $replayPassResult !== null
&& $replayCondResult !== null
&& $bodyScope->equals($prevEntryScope)
) {
// the final walk would repeat the recorded fixpoint pass exactly
// (same entry scope, deterministic walk) - adopt the pass's results
// and replay its emissions through the real callback instead
$originalStorage->mergeResults($replayPassStorage);
$nodeScopeResolver->replayRecording($replayCondRecording, $nodeCallback, $originalStorage, $scope);
// the While_ callback is deferred from processStmtNode(): it fires
// after the condition's result is available, with the entry scope
$nodeScopeResolver->callNodeCallback($nodeCallback, $stmt, $scope, $storage);
$nodeScopeResolver->replayRecording($replayBodyRecording, $nodeCallback, $originalStorage, $scope);
$bodyCondResult = $replayCondResult;
$finalScopeResult = $replayPassResult;
} else {
$lastPass = $previousPass !== null && $previousPass[1] !== null ? $previousPass : null;
if ($lastPass !== null) {
// before the condition's real walk stores its own results
$originalStorage->mergeResults($previousPassStorage);
}
$bodyCondResult = $nodeScopeResolver->processExprNode($stmt, $stmt->cond, $bodyScope, $storage, $nodeCallback, ExpressionContext::createDeep($context->shouldResolveTemplateArguments()));
// the While_ callback is deferred from processStmtNode(): it fires after
// the condition's real walk stored its result, with the entry scope
$nodeScopeResolver->callNodeCallback($nodeCallback, $stmt, $scope, $storage);
$bodyScope = $bodyCondResult->getTruthyScope();
if ($lastPass !== null) {
// the last pass stands in for the statements whose state it walked
// with - they replay through the real callback
$finalScopeResult = $nodeScopeResolver->processLoopFinalStmtNodes($stmt, $stmt->stmts, $bodyScope, $storage, $nodeCallback, $context, $lastPass)->filterOutLoopExitPoints();
} else {
$finalScopeResult = $nodeScopeResolver->processStmtNodesInternal($stmt, $stmt->stmts, $bodyScope, $storage, $nodeCallback, $context)->filterOutLoopExitPoints();
}
}
$backEdgeScope = $finalScopeResult->getLoopBackEdgeScope();
$backEdgeDead = $backEdgeScope === null;
$finalScope = $backEdgeScope ?? $finalScopeResult->getScope();
// the loop condition narrows the post-loop scope to its falsey branch;
// $finalScope (after the body ran) is a different scope than the condition's
// own, so reprocess the condition there rather than re-running its result.
// The duplicate lets subresults whose state did not change in the body
// answer from the final pass instead of being re-priced.
$finalScope = $finalScope->applySpecifiedTypes($nodeScopeResolver->processExprOnDemand($stmt->cond, $finalScope, $storage->duplicate())->getSpecifiedTypesForScope($finalScope, TypeSpecifierContext::createFalsey()));
$alwaysIterates = false;
$neverIterates = false;
if ($context->isTopLevel()) {
$condBooleanType = ($this->treatPhpDocTypesAsCertain ? $bodyCondResult->getType() : $bodyCondResult->getNativeType())->toBoolean();
$alwaysIterates = $condBooleanType->isTrue()->yes();
$neverIterates = $condBooleanType->isFalse()->yes();
}
$breakExitPoints = $finalScopeResult->getExitPointsByType(Break_::class);
if (count($breakExitPoints) > 0) {
$breakScope = $alwaysIterates || $backEdgeDead ? null : $finalScope;
foreach ($breakExitPoints as $breakExitPoint) {
$breakScope = $breakScope === null ? $breakExitPoint->getScope() : $breakScope->mergeWith($breakExitPoint->getScope());
}
$finalScope = $breakScope;
}
$isIterableAtLeastOnce = $beforeCondBooleanType->isTrue()->yes();
$nodeScopeResolver->callNodeCallback($nodeCallback, new BreaklessWhileLoopNode($stmt, $finalScopeResult->toPublic()->getExitPoints(), $finalScopeResult->hasYield()), $bodyScopeMaybeRan, $storage);
if ($alwaysIterates) {
$isAlwaysTerminating = count($finalScopeResult->getExitPointsByType(Break_::class)) === 0;
} elseif ($isIterableAtLeastOnce) {
$isAlwaysTerminating = $finalScopeResult->isAlwaysTerminating();
} else {
$isAlwaysTerminating = false;
}
if ($backEdgeDead && count($breakExitPoints) === 0) {
$finalScope = null;
}
if (!$isIterableAtLeastOnce) {
if (!$this->polluteScopeWithLoopInitialAssignments) {
$condScope = $condScope->mergeWith($scope);
}
$finalScope = $finalScope === null ? $condScope : $finalScope->mergeWith($condScope);
}
$finalScope ??= $finalScopeResult->getScope();
$throwPoints = $condResult->getThrowPoints();
$impurePoints = $condResult->getImpurePoints();
if (!$neverIterates) {
$throwPoints = array_merge($throwPoints, $finalScopeResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $finalScopeResult->getImpurePoints());
}
return new InternalStatementResult(
$finalScope,
hasYield: $finalScopeResult->hasYield() || $condResult->hasYield(),
isAlwaysTerminating: $isAlwaysTerminating,
exitPoints: $finalScopeResult->getExitPointsForOuterLoop(),
throwPoints: $throwPoints,
impurePoints: $impurePoints,
// the body may run or not whatever the condition says: a write in
// it does not make an earlier write dead, and a usage in it counts
variableFlow: VariableFlow::loop($bodyCondResult->getVariableFlow(), $finalScopeResult->getVariableFlow(), null, false, true),
dependencies: Dependencies::merge($bodyCondResult->getDependencies(), $finalScopeResult->getDependencies()),
);
}
}