Repository navigation
Expand file tree
/
Copy pathTryCatchHandler.php
More file actions
365 lines (321 loc) · 14 KB
/
Copy pathTryCatchHandler.php
File metadata and controls
365 lines (321 loc) · 14 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\StmtHandler;
use Error;
use Exception;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\TryCatch;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\InternalStatementExitPoint;
use PHPStan\Analyser\InternalStatementResult;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\StatementContext;
use PHPStan\Analyser\StatementsHandler;
use PHPStan\Analyser\StmtHandler;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\CatchWithUnthrownExceptionNode;
use PHPStan\Node\Expr\TypeExpr;
use PHPStan\Node\FinallyExitPointsNode;
use PHPStan\Node\ReturnAfterFinallyNode;
use PHPStan\Node\Variable\VariableWrite;
use PHPStan\Node\VariableAssignNode;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeCombinator;
use Throwable;
use function array_fill_keys;
use function array_keys;
use function array_merge;
use function count;
use function is_string;
/**
* @implements StmtHandler<TryCatch>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TryCatchHandler.cpp')]
final class TryCatchHandler implements StmtHandler
{
public function __construct(
private StatementsHandler $statementsHandler,
)
{
}
public function supports(Stmt $stmt): bool
{
return $stmt instanceof TryCatch;
}
public function processStmt(
NodeScopeResolver $nodeScopeResolver,
Stmt $stmt,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
$dependencies = [];
$catchFlows = [];
$finallyFlow = null;
$branchScopeResult = $nodeScopeResolver->processStmtNodesInternal($stmt, $stmt->stmts, $scope, $storage, $nodeCallback, $context);
$dependencies[] = $branchScopeResult->getDependencies();
$branchScope = $branchScopeResult->getScope();
$finalScope = $branchScopeResult->isAlwaysTerminating() ? null : $branchScope;
// what the template argument observation collected in every block,
// including the ones that end by leaving the try-catch
$blockScopes = [$branchScope];
$exitPoints = [];
$finallyExitPoints = [];
$alwaysTerminating = $branchScopeResult->isAlwaysTerminating();
$hasYield = $branchScopeResult->hasYield();
if ($stmt->finally !== null) {
$finallyScope = $branchScope;
} else {
$finallyScope = null;
}
foreach ($branchScopeResult->getExitPoints() as $exitPoint) {
$finallyExitPoints[] = $exitPoint->toPublic();
if ($exitPoint->getStatement() instanceof Node\Stmt\Expression && $exitPoint->getStatement()->expr instanceof Expr\Throw_) {
continue;
}
if ($finallyScope !== null) {
$finallyScope = $finallyScope->mergeWith($exitPoint->getScope());
}
$exitPoints[] = $exitPoint;
}
$throwPoints = $branchScopeResult->getThrowPoints();
$impurePoints = $branchScopeResult->getImpurePoints();
$throwPointsForLater = [];
$pastCatchTypes = new NeverType();
foreach ($stmt->catches as $catchNode) {
$nodeScopeResolver->callNodeCallback($nodeCallback, $catchNode, $scope, $storage);
$caughtClassNames = [];
foreach ($catchNode->types as $catchNodeType) {
$caughtClassNames[] = $scope->resolveName($catchNodeType);
}
$dependencies[] = Dependencies::create($scope->getFile(), classNames: $caughtClassNames);
$originalCatchTypes = [];
$catchTypes = [];
foreach ($catchNode->types as $catchNodeType) {
$catchType = new ObjectType($catchNodeType->toString());
$originalCatchTypes[] = $catchType;
$catchTypes[] = TypeCombinator::remove($catchType, $pastCatchTypes);
}
$originalCatchType = TypeCombinator::union(...$originalCatchTypes);
$catchType = TypeCombinator::union(...$catchTypes);
$pastCatchTypes = TypeCombinator::union($pastCatchTypes, $originalCatchType);
$matchingThrowPoints = [];
$matchingCatchTypes = array_fill_keys(array_keys($originalCatchTypes), false);
// throwable matches all
foreach ($originalCatchTypes as $catchTypeIndex => $catchTypeItem) {
if (!$catchTypeItem->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
continue;
}
foreach ($throwPoints as $throwPointIndex => $throwPoint) {
$matchingThrowPoints[$throwPointIndex] = $throwPoint;
$matchingCatchTypes[$catchTypeIndex] = true;
}
}
// explicit only
$onlyExplicitIsThrow = true;
if (count($matchingThrowPoints) === 0) {
foreach ($throwPoints as $throwPointIndex => $throwPoint) {
if ($throwPoint->getType() instanceof NeverType) {
continue;
}
foreach ($catchTypes as $catchTypeIndex => $catchTypeItem) {
if ($catchTypeItem->isSuperTypeOf($throwPoint->getType())->no()) {
continue;
}
$matchingCatchTypes[$catchTypeIndex] = true;
if (!$throwPoint->isExplicit()) {
continue;
}
$throwNode = $throwPoint->getNode();
if (
!$throwNode instanceof Expr\Throw_
&& !($throwNode instanceof Node\Stmt\Expression && $throwNode->expr instanceof Expr\Throw_)
) {
$onlyExplicitIsThrow = false;
}
$matchingThrowPoints[$throwPointIndex] = $throwPoint;
}
}
}
// implicit only
// Broad catches also cover undocumented exceptions when a documented throw matches.
if (
count($matchingThrowPoints) === 0
|| $onlyExplicitIsThrow
|| $originalCatchType->isSuperTypeOf(new ObjectType(Exception::class))->yes() // phpcs:ignore SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly.ReferencedGeneralException
|| $originalCatchType->isSuperTypeOf(new ObjectType(Error::class))->yes()
) {
foreach ($throwPoints as $throwPointIndex => $throwPoint) {
if ($throwPoint->isExplicit() || $throwPoint->getType() instanceof NeverType) {
continue;
}
foreach ($catchTypes as $catchTypeItem) {
if ($catchTypeItem->isSuperTypeOf($throwPoint->getType())->no()) {
continue;
}
$matchingThrowPoints[$throwPointIndex] = $throwPoint;
}
}
}
// include previously removed throw points
if (count($matchingThrowPoints) === 0) {
if ($originalCatchType->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
foreach ($branchScopeResult->getThrowPoints() as $originalThrowPoint) {
if (!$originalThrowPoint->canContainAnyThrowable()) {
continue;
}
$matchingThrowPoints[] = $originalThrowPoint;
$matchingCatchTypes = array_fill_keys(array_keys($originalCatchTypes), true);
}
}
}
// emit error
foreach ($matchingCatchTypes as $catchTypeIndex => $matched) {
if ($matched) {
continue;
}
$nodeScopeResolver->callNodeCallback($nodeCallback, new CatchWithUnthrownExceptionNode($catchNode, $catchTypes[$catchTypeIndex], $originalCatchTypes[$catchTypeIndex]), $scope, $storage);
}
if (count($matchingThrowPoints) === 0) {
$catchFlows[] = [$originalCatchType, $this->statementsHandler->getVariableMentionFlow($catchNode)];
// the catch block is not reachable, but rules still need to see its statements;
// it is entered from where the try block can throw anything, and the result
// of the walk does not flow anywhere
$deadCatchScope = null;
foreach ($branchScopeResult->getThrowPoints() as $throwPoint) {
$deadCatchScope = $deadCatchScope === null ? $throwPoint->getScope() : $deadCatchScope->mergeWith($throwPoint->getScope());
}
$deadCatchScope = ($deadCatchScope ?? $scope->mergeWith($branchScope))->enterCatchType($catchType instanceof NeverType ? $originalCatchType : $catchType, $catchNode->var !== null && is_string($catchNode->var->name) ? $catchNode->var->name : null);
$deadCatchResult = $nodeScopeResolver->processStmtNodesInternal($catchNode, $catchNode->stmts, $deadCatchScope, $storage, $nodeCallback, $context);
$dependencies[] = $deadCatchResult->getDependencies();
continue;
}
// recompute throw points
$newThrowPoints = [];
foreach ($throwPoints as $throwPoint) {
$newThrowPoint = $throwPoint->subtractCatchType($originalCatchType);
if ($newThrowPoint->getType() instanceof NeverType) {
if (!$throwPoint->canContainAnyThrowable() || $originalCatchType->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
continue;
}
// Keep the fallback Throwable path for enclosing try blocks without
// introducing any other exception types after the documented ones were caught.
$newThrowPoint = InternalThrowPoint::createImplicit($throwPoint->getScope(), $throwPoint->getNode(), $newThrowPoint->getType());
}
$newThrowPoints[] = $newThrowPoint;
}
$throwPoints = $newThrowPoints;
$catchScope = null;
foreach ($matchingThrowPoints as $matchingThrowPoint) {
if ($catchScope === null) {
$catchScope = $matchingThrowPoint->getScope();
} else {
$catchScope = $catchScope->mergeWith($matchingThrowPoint->getScope());
}
}
$variableName = null;
if ($catchNode->var !== null) {
if (!is_string($catchNode->var->name)) {
throw new ShouldNotHappenException();
}
$variableName = $catchNode->var->name;
$nodeScopeResolver->callNodeCallback($nodeCallback, new VariableAssignNode($catchNode->var, new TypeExpr($catchType)), $scope, $storage);
}
$catchScopeResult = $nodeScopeResolver->processStmtNodesInternal($catchNode, $catchNode->stmts, $catchScope->enterCatchType($catchType, $variableName), $storage, $nodeCallback, $context);
$dependencies[] = $catchScopeResult->getDependencies();
$catchScopeForFinally = $catchScopeResult->getScope();
$blockScopes[] = $catchScopeForFinally;
$catchFlows[] = [$originalCatchType, VariableFlow::sequence($catchNode->var !== null ? VariableFlowBuilder::targetWrite($catchNode->var, VariableWrite::KIND_CATCH, $catchScopeForFinally, $storage) : null, $catchScopeResult->getVariableFlow())];
$finalScope = $catchScopeResult->isAlwaysTerminating() ? $finalScope : $catchScopeResult->getScope()->mergeWith($finalScope);
$alwaysTerminating = $alwaysTerminating && $catchScopeResult->isAlwaysTerminating();
$hasYield = $hasYield || $catchScopeResult->hasYield();
$catchThrowPoints = $catchScopeResult->getThrowPoints();
$impurePoints = array_merge($impurePoints, $catchScopeResult->getImpurePoints());
$throwPointsForLater = array_merge($throwPointsForLater, $catchThrowPoints);
if ($finallyScope !== null) {
$finallyScope = $finallyScope->mergeWith($catchScopeForFinally);
}
foreach ($catchScopeResult->getExitPoints() as $exitPoint) {
$finallyExitPoints[] = $exitPoint->toPublic();
if ($exitPoint->getStatement() instanceof Node\Stmt\Expression && $exitPoint->getStatement()->expr instanceof Expr\Throw_) {
continue;
}
if ($finallyScope !== null) {
$finallyScope = $finallyScope->mergeWith($exitPoint->getScope());
}
$exitPoints[] = $exitPoint;
}
foreach ($catchThrowPoints as $catchThrowPoint) {
if ($finallyScope === null) {
continue;
}
$finallyScope = $finallyScope->mergeWith($catchThrowPoint->getScope());
}
}
if ($finalScope === null) {
$finalScope = $scope;
}
foreach ($throwPoints as $throwPoint) {
if ($finallyScope === null) {
continue;
}
$finallyScope = $finallyScope->mergeWith($throwPoint->getScope());
}
if ($finallyScope !== null) {
$originalFinallyScope = $finallyScope;
$finallyResult = $nodeScopeResolver->processStmtNodesInternal($stmt->finally, $stmt->finally->stmts, $finallyScope, $storage, $nodeCallback, $context);
$dependencies[] = $finallyResult->getDependencies();
$finallyFlow = $finallyResult->getVariableFlow();
$alwaysTerminating = $alwaysTerminating || $finallyResult->isAlwaysTerminating();
$hasYield = $hasYield || $finallyResult->hasYield();
$throwPointsForLater = array_merge($throwPointsForLater, $finallyResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $finallyResult->getImpurePoints());
$finallyScope = $finallyResult->getScope();
$blockScopes[] = $finallyScope;
$finalScope = $finallyResult->isAlwaysTerminating() ? $finalScope : $finalScope->processFinallyScope($finallyScope, $originalFinallyScope);
if (!$finallyResult->isAlwaysTerminating()) {
// the finally block runs after the exit point, so its changes are
// part of the state the exit point leaves the try-catch with
$exitPointsAfterFinally = [];
foreach ($exitPoints as $exitPoint) {
$exitStatement = $exitPoint->getStatement();
$exitPointScope = $exitPoint->getScope()->processFinallyScope($finallyScope, $originalFinallyScope);
$exitPointsAfterFinally[] = new InternalStatementExitPoint($exitStatement, $exitPointScope);
if (!$exitStatement instanceof Node\Stmt\Return_ || $exitStatement->expr === null) {
continue;
}
$nodeScopeResolver->callNodeCallback(
$nodeCallback,
new ReturnAfterFinallyNode($exitStatement),
$exitPointScope,
$storage,
);
}
$exitPoints = $exitPointsAfterFinally;
}
if (count($finallyResult->getExitPoints()) > 0 && $finallyResult->isAlwaysTerminating()) {
$nodeScopeResolver->callNodeCallback($nodeCallback, new FinallyExitPointsNode(
$finallyResult->toPublic()->getExitPoints(),
$finallyExitPoints,
), $scope, $storage);
}
$exitPoints = array_merge($exitPoints, $finallyResult->getExitPoints());
}
foreach ($blockScopes as $blockScope) {
$finalScope = $finalScope->addTemplateArgumentConstraints($blockScope->getTemplateArgumentConstraints());
}
return new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPoints, throwPoints: array_merge($throwPoints, $throwPointsForLater), impurePoints: $impurePoints, variableFlow: VariableFlow::tryCatch($branchScopeResult->getVariableFlow(), $catchFlows, $finallyFlow), dependencies: Dependencies::merge(...$dependencies));
}
}