forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchHandler.php
More file actions
572 lines (507 loc) · 18.7 KB
/
MatchHandler.php
File metadata and controls
572 lines (507 loc) · 18.7 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\ExprHandler;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\AlwaysRememberedExpr;
use PHPStan\Node\MatchExpressionArm;
use PHPStan\Node\MatchExpressionArmBody;
use PHPStan\Node\MatchExpressionArmCondition;
use PHPStan\Node\MatchExpressionNode;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use UnhandledMatchError;
use function array_key_exists;
use function array_merge;
use function array_values;
use function count;
use function ksort;
use function strtolower;
use const SORT_NUMERIC;
/**
* @implements ExprHandler<Match_>
*/
#[AutowiredService]
final class MatchHandler implements ExprHandler
{
public function __construct(
#[AutowiredParameter]
private bool $treatPhpDocTypesAsCertain,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof Match_;
}
public function resolveType(MutatingScope $scope, Expr $expr): Type
{
$cond = $expr->cond;
$condType = $scope->getType($cond);
$types = [];
$matchScope = $scope;
$arms = $expr->arms;
if ($condType->isEnum()->yes()) {
// enum match analysis would work even without this if branch
// but would be much slower
// this avoids using ObjectType::$subtractedType which is slow for huge enums
// because of repeated union type normalization
$enumCases = $condType->getEnumCases();
if (count($enumCases) > 0) {
$indexedEnumCases = [];
foreach ($enumCases as $enumCase) {
$indexedEnumCases[strtolower($enumCase->getClassName())][$enumCase->getEnumCaseName()] = $enumCase;
}
$unusedIndexedEnumCases = $indexedEnumCases;
foreach ($arms as $i => $arm) {
if ($arm->conds === null) {
continue;
}
$conditionCases = [];
foreach ($arm->conds as $armCond) {
if (!$armCond instanceof Expr\ClassConstFetch) {
continue 2;
}
if (!$armCond->class instanceof Name) {
continue 2;
}
if (!$armCond->name instanceof Identifier) {
continue 2;
}
$fetchedClassName = $scope->resolveName($armCond->class);
$loweredFetchedClassName = strtolower($fetchedClassName);
if (!array_key_exists($loweredFetchedClassName, $indexedEnumCases)) {
continue 2;
}
$caseName = $armCond->name->toString();
if (!array_key_exists($caseName, $indexedEnumCases[$loweredFetchedClassName])) {
continue 2;
}
$conditionCases[] = $indexedEnumCases[$loweredFetchedClassName][$caseName];
unset($unusedIndexedEnumCases[$loweredFetchedClassName][$caseName]);
}
$conditionCasesCount = count($conditionCases);
if ($conditionCasesCount === 0) {
throw new ShouldNotHappenException();
} elseif ($conditionCasesCount === 1) {
$conditionCaseType = $conditionCases[0];
} else {
$conditionCaseType = new UnionType($conditionCases);
}
$types[] = $matchScope->addTypeToExpression(
$cond,
$conditionCaseType,
)->getType($arm->body);
unset($arms[$i]);
}
$remainingCases = [];
foreach ($unusedIndexedEnumCases as $cases) {
foreach ($cases as $case) {
$remainingCases[] = $case;
}
}
$remainingCasesCount = count($remainingCases);
if ($remainingCasesCount === 0) {
$remainingType = new NeverType();
} elseif ($remainingCasesCount === 1) {
$remainingType = $remainingCases[0];
} else {
$remainingType = new UnionType($remainingCases);
}
$matchScope = $matchScope->addTypeToExpression($cond, $remainingType);
}
}
foreach ($arms as $arm) {
if ($arm->conds === null) {
if ($expr->hasAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME)) {
$arm->body->setAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME, $expr->getAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME));
}
$types[] = $matchScope->getType($arm->body);
continue;
}
if (count($arm->conds) === 0) {
throw new ShouldNotHappenException();
}
$filteringExpr = $this->getFilteringExprForMatchArm($expr, $arm->conds);
$filteringExprType = $matchScope->getType($filteringExpr);
if (!$filteringExprType->isFalse()->yes()) {
$truthyScope = $matchScope->filterByTruthyValue($filteringExpr);
if ($expr->hasAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME)) {
$arm->body->setAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME, $expr->getAttribute(MutatingScope::KEEP_VOID_ATTRIBUTE_NAME));
}
$types[] = $truthyScope->getType($arm->body);
}
$matchScope = $matchScope->filterByFalseyValue($filteringExpr);
}
return TypeCombinator::union(...$types);
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$deepContext = $context->enterDeep();
$condType = $scope->getType($expr->cond);
$condNativeType = $scope->getNativeType($expr->cond);
$condResult = $nodeScopeResolver->processExprNode($stmt, $expr->cond, $scope, $storage, $nodeCallback, $deepContext);
$scope = $condResult->getScope();
$hasYield = $condResult->hasYield();
$throwPoints = $condResult->getThrowPoints();
$impurePoints = $condResult->getImpurePoints();
$isAlwaysTerminating = $condResult->isAlwaysTerminating();
$matchScope = $scope->enterMatch($expr, $condType, $condNativeType);
$armNodes = [];
$hasDefaultCond = false;
$hasAlwaysTrueCond = false;
$arms = $expr->arms;
$armCondsToSkip = [];
$armBodyScopes = [];
if ($condType->isEnum()->yes()) {
// enum match analysis would work even without this if branch
// but would be much slower
// this avoids using ObjectType::$subtractedType which is slow for huge enums
// because of repeated union type normalization
$enumCases = $condType->getEnumCases();
if (count($enumCases) > 0) {
$indexedEnumCases = [];
foreach ($enumCases as $enumCase) {
$indexedEnumCases[strtolower($enumCase->getClassName())][$enumCase->getEnumCaseName()] = $enumCase;
}
$unusedIndexedEnumCases = $indexedEnumCases;
foreach ($arms as $i => $arm) {
if ($arm->conds === null) {
continue;
}
// Pre-validate all conditions before processing to avoid
// partial consumption of enum cases when a later condition
// causes the arm to be skipped.
// Use break instead of continue to stop fast-path processing
// entirely - subsequent arms must also go through the slow
// path to preserve correct evaluation order.
foreach ($arm->conds as $cond) {
if (!$cond instanceof Expr\ClassConstFetch) {
break 2;
}
if (!$cond->class instanceof Name) {
break 2;
}
if (!$cond->name instanceof Identifier) {
break 2;
}
$fetchedClassName = $scope->resolveName($cond->class);
$loweredFetchedClassName = strtolower($fetchedClassName);
if (!array_key_exists($loweredFetchedClassName, $indexedEnumCases)) {
break 2;
}
$caseName = $cond->name->toString();
if (!array_key_exists($caseName, $indexedEnumCases[$loweredFetchedClassName])) {
break 2;
}
}
$condNodes = [];
$conditionCases = [];
$conditionExprs = [];
foreach ($arm->conds as $j => $cond) {
if (!$cond instanceof Expr\ClassConstFetch) {
throw new ShouldNotHappenException();
}
if (!$cond->class instanceof Name) {
throw new ShouldNotHappenException();
}
if (!$cond->name instanceof Identifier) {
throw new ShouldNotHappenException();
}
$fetchedClassName = $scope->resolveName($cond->class);
$loweredFetchedClassName = strtolower($fetchedClassName);
if (!array_key_exists($loweredFetchedClassName, $indexedEnumCases)) {
throw new ShouldNotHappenException();
}
if (!array_key_exists($loweredFetchedClassName, $unusedIndexedEnumCases)) {
throw new ShouldNotHappenException();
}
$caseName = $cond->name->toString();
if (!array_key_exists($caseName, $indexedEnumCases[$loweredFetchedClassName])) {
throw new ShouldNotHappenException();
}
$enumCase = $indexedEnumCases[$loweredFetchedClassName][$caseName];
$conditionCases[] = $enumCase;
$armConditionScope = $matchScope;
if (!array_key_exists($caseName, $unusedIndexedEnumCases[$loweredFetchedClassName])) {
// force "always false"
$armConditionScope = $armConditionScope->removeTypeFromExpression(
$expr->cond,
$enumCase,
);
} else {
$unusedCasesCount = 0;
foreach ($unusedIndexedEnumCases as $cases) {
$unusedCasesCount += count($cases);
}
if ($unusedCasesCount === 1) {
$hasAlwaysTrueCond = true;
// force "always true"
$armConditionScope = $armConditionScope->addTypeToExpression(
$expr->cond,
$enumCase,
);
}
}
$nodeScopeResolver->processExprNode($stmt, $cond, $armConditionScope, $storage, $nodeCallback, $deepContext);
$condNodes[] = new MatchExpressionArmCondition(
$cond,
$armConditionScope,
$cond->getStartLine(),
);
$conditionExprs[] = $cond;
unset($unusedIndexedEnumCases[$loweredFetchedClassName][$caseName]);
$armCondsToSkip[$i][$j] = true;
}
$conditionCasesCount = count($conditionCases);
if ($conditionCasesCount === 0) {
throw new ShouldNotHappenException();
} elseif ($conditionCasesCount === 1) {
$conditionCaseType = $conditionCases[0];
} else {
$conditionCaseType = new UnionType($conditionCases);
}
$filteringExpr = $this->getFilteringExprForMatchArm($expr, $conditionExprs);
$matchArmBodyScope = $matchScope->addTypeToExpression(
$expr->cond,
$conditionCaseType,
)->filterByTruthyValue($filteringExpr);
$matchArmBody = new MatchExpressionArmBody($matchArmBodyScope, $arm->body);
$armNodes[$i] = new MatchExpressionArm($matchArmBody, $condNodes, $arm->getStartLine());
$armResult = $nodeScopeResolver->processExprNode(
$stmt,
$arm->body,
$matchArmBodyScope,
$storage,
$nodeCallback,
ExpressionContext::createTopLevel(),
);
$armScope = $armResult->getScope();
if (!$armResult->isAlwaysTerminating()) {
$armBodyScopes[] = $armScope;
}
$hasYield = $hasYield || $armResult->hasYield();
$throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
unset($arms[$i]);
}
$remainingCases = [];
foreach ($unusedIndexedEnumCases as $cases) {
foreach ($cases as $case) {
$remainingCases[] = $case;
}
}
$remainingCasesCount = count($remainingCases);
if ($remainingCasesCount === 0) {
$remainingType = new NeverType();
} elseif ($remainingCasesCount === 1) {
$remainingType = $remainingCases[0];
} else {
$remainingType = new UnionType($remainingCases);
}
$matchScope = $matchScope->addTypeToExpression($expr->cond, $remainingType);
}
}
foreach ($arms as $i => $arm) {
if ($arm->conds === null) {
$hasDefaultCond = true;
$matchArmBody = new MatchExpressionArmBody($matchScope, $arm->body);
$armNodes[$i] = new MatchExpressionArm($matchArmBody, [], $arm->getStartLine());
$armResult = $nodeScopeResolver->processExprNode($stmt, $arm->body, $matchScope, $storage, $nodeCallback, ExpressionContext::createTopLevel());
$matchScope = $armResult->getScope();
$hasYield = $hasYield || $armResult->hasYield();
$throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
if (!$armResult->isAlwaysTerminating()) {
$armBodyScopes[] = $matchScope;
}
continue;
}
if (count($arm->conds) === 0) {
throw new ShouldNotHappenException();
}
$filteringExprs = [];
$armCondScope = $matchScope;
$condNodes = [];
$armCondResultScope = $matchScope;
$bodyScope = null;
foreach ($arm->conds as $j => $armCond) {
if (isset($armCondsToSkip[$i][$j])) {
continue;
}
$condNodes[] = new MatchExpressionArmCondition($armCond, $armCondScope, $armCond->getStartLine());
$armCondResult = $nodeScopeResolver->processExprNode($stmt, $armCond, $armCondScope, $storage, $nodeCallback, $deepContext);
$hasYield = $hasYield || $armCondResult->hasYield();
$throwPoints = array_merge($throwPoints, $armCondResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $armCondResult->getImpurePoints());
$armCondExpr = new BinaryOp\Identical($expr->cond, $armCond);
$armCondResultScope = $armCondResult->getScope();
$armCondType = $this->treatPhpDocTypesAsCertain ? $armCondResultScope->getType($armCondExpr) : $armCondResultScope->getNativeType($armCondExpr);
if ($armCondType->isTrue()->yes()) {
$hasAlwaysTrueCond = true;
}
$armCondScope = $armCondResultScope->filterByFalseyValue($armCondExpr);
if ($bodyScope === null) {
$bodyScope = $armCondResultScope->filterByTruthyValue($armCondExpr);
} else {
$bodyScope = $bodyScope->mergeWith($armCondResultScope->filterByTruthyValue($armCondExpr));
}
$filteringExprs[] = $armCond;
}
$filteringExpr = $this->getFilteringExprForMatchArm($expr, $filteringExprs);
$bodyScope ??= $matchScope->filterByTruthyValue($filteringExpr);
$matchArmBody = new MatchExpressionArmBody($bodyScope, $arm->body);
$armNodes[$i] = new MatchExpressionArm($matchArmBody, $condNodes, $arm->getStartLine());
$armResult = $nodeScopeResolver->processExprNode(
$stmt,
$arm->body,
$bodyScope,
$storage,
$nodeCallback,
ExpressionContext::createTopLevel(),
);
$armScope = $armResult->getScope();
if (!$armResult->isAlwaysTerminating()) {
$armBodyScopes[] = $armScope;
}
$hasYield = $hasYield || $armResult->hasYield();
$throwPoints = array_merge($throwPoints, $armResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $armResult->getImpurePoints());
$matchScope = $armCondScope->filterByFalseyValue($filteringExpr);
}
if (!$hasDefaultCond && !$hasAlwaysTrueCond && $condType->isBoolean()->yes() && $condType->isConstantScalarValue()->yes()) {
if ($this->isScopeConditionallyImpossible($matchScope)) {
$hasAlwaysTrueCond = true;
$matchScope = $matchScope->addTypeToExpression($expr->cond, new NeverType());
}
}
$scopeForMatchNodeCallback = $scope;
$isExhaustive = $hasDefaultCond || $hasAlwaysTrueCond;
if (!$isExhaustive) {
$remainingType = $matchScope->getType($expr->cond);
if ($remainingType instanceof NeverType) {
$isExhaustive = true;
}
}
if ($isExhaustive) {
$preMatchConditionalExpressions = $scope->getConditionalExpressions();
$armBodyFinalScope = null;
foreach ($armBodyScopes as $armBodyScope) {
$armBodyFinalScope = $armBodyScope->mergeWith($armBodyFinalScope);
}
if ($armBodyFinalScope !== null) {
// Prevent conditional expressions created during arm scope merging
// from leaking into the post-match scope. These encode relationships
// between arm-narrowed types (e.g. "if equals(A) is false, then
// equals(B) is true") that should not affect subsequent code.
$scope = $armBodyFinalScope->replaceConditionalExpressions($preMatchConditionalExpressions);
}
} else {
$armBodyFinalScope = null;
foreach ($armBodyScopes as $armBodyScope) {
$armBodyFinalScope = $armBodyScope->mergeWith($armBodyFinalScope);
}
if ($armBodyFinalScope !== null) {
$scope = $scope->mergeWith($armBodyFinalScope);
}
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(UnhandledMatchError::class), $expr, false);
}
ksort($armNodes, SORT_NUMERIC);
$nodeScopeResolver->callNodeCallback($nodeCallback, new MatchExpressionNode($expr->cond, array_values($armNodes), $expr, $matchScope), $scopeForMatchNodeCallback, $storage);
if ($expr->cond instanceof AlwaysRememberedExpr) {
$expr->cond = $expr->cond->getExpr();
}
return new ExpressionResult(
$scope,
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
impurePoints: $impurePoints,
);
}
/**
* @param Expr[] $conditions
*/
private function getFilteringExprForMatchArm(Match_ $expr, array $conditions): BinaryOp\Identical|FuncCall
{
if (count($conditions) === 1) {
return new BinaryOp\Identical($expr->cond, $conditions[0]);
}
$items = [];
foreach ($conditions as $filteringExpr) {
$items[] = new Node\ArrayItem($filteringExpr);
}
return new FuncCall(
new Name\FullyQualified('in_array'),
[
new Arg($expr->cond),
new Arg(new Array_($items)),
new Arg(new ConstFetch(new Name\FullyQualified('true'))),
],
);
}
private function isScopeConditionallyImpossible(MutatingScope $scope): bool
{
$boolVars = [];
foreach ($scope->getDefinedVariables() as $varName) {
$varType = $scope->getVariableType($varName);
if (!$varType->isBoolean()->yes() || $varType->isConstantScalarValue()->yes()) {
continue;
}
$boolVars[] = $varName;
}
if ($boolVars === []) {
return false;
}
// Check if any boolean variable's both truth values lead to contradictions
foreach ($boolVars as $varName) {
$varExpr = new Variable($varName);
$truthyScope = $scope->filterByTruthyValue($varExpr);
$truthyContradiction = $this->scopeHasNeverVariable($truthyScope, $boolVars);
if (!$truthyContradiction) {
continue;
}
$falseyScope = $scope->filterByFalseyValue($varExpr);
$falseyContradiction = $this->scopeHasNeverVariable($falseyScope, $boolVars);
if ($falseyContradiction) {
return true;
}
}
return false;
}
/**
* @param string[] $varNames
*/
private function scopeHasNeverVariable(MutatingScope $scope, array $varNames): bool
{
foreach ($varNames as $varName) {
$type = $scope->getVariableType($varName);
if ($type instanceof NeverType) {
return true;
}
}
return false;
}
}