Repository navigation
Expand file tree
/
Copy pathIdenticalNarrowingHelper.php
More file actions
1198 lines (1079 loc) · 49.2 KB
/
Copy pathIdenticalNarrowingHelper.php
File metadata and controls
1198 lines (1079 loc) · 49.2 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler\Helper;
use Countable;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\RicherScopeGetTypeHelper;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\AlwaysRememberedExpr;
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantFloatType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\FloatType;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\ResourceType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function count;
use function in_array;
/**
* New-world narrowing for `===` (and, via a negated context, `!==`): composed
* from the operands' ExpressionResults, no scope asks and no synthetic nodes.
* The evaluation scope is a create-time constant of the calling handler (it
* carries the flavour and feeds entry composition), never the asking scope.
*
* Null from the entry points means the shape carries no specific narrowing
* (unknown-class ::class sides, null-context asks) and the caller applies
* the default truthy/falsey narrowing.
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../../turbo-ext/src/IdenticalNarrowingHelper.cpp')]
final class IdenticalNarrowingHelper
{
public function __construct(
private DefaultNarrowingHelper $defaultNarrowingHelper,
private ReflectionProvider $reflectionProvider,
private CountNarrowingHelper $countNarrowingHelper,
private ExprPrinter $exprPrinter,
private RicherScopeGetTypeHelper $richerScopeGetTypeHelper,
)
{
}
/**
* @param callable(): Type $identicalTypeCallback the comparison's own type
* in Identical semantics (the caller flips a NotIdentical verdict)
*/
public function specifyIdentical(
NodeScopeResolver $nodeScopeResolver,
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $leftArgResult,
?ExpressionResult $rightArgResult,
callable $identicalTypeCallback,
): ?SpecifiedTypes
{
if ($context->null()) {
return null;
}
// slices 1+2 cover comparisons against a null/true/false literal;
// everything else falls through to the scalar-literal slice below
if ($left instanceof Expr\ConstFetch && in_array($left->name->toLowerString(), ['null', 'true', 'false'], true)) {
$constantName = $left->name->toLowerString();
$subject = $right;
$subjectResult = $rightResult;
} elseif ($right instanceof Expr\ConstFetch && in_array($right->name->toLowerString(), ['null', 'true', 'false'], true)) {
$constantName = $right->name->toLowerString();
$subject = $left;
$subjectResult = $leftResult;
} else {
// a side whose TYPE is a constant bool (match (true) arms, bool
// class constants) compares like the literal - the old
// constant-binary handling, composed
$unwrappedLeft = $left instanceof AlwaysRememberedExpr ? $left->getExpr() : $left;
$unwrappedRight = $right instanceof AlwaysRememberedExpr ? $right->getExpr() : $right;
$leftType = $this->literalType($unwrappedLeft) ?? $leftResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (($leftType->isTrue()->yes() || $leftType->isFalse()->yes()) && !$unwrappedRight instanceof Expr\ConstFetch) {
return $this->specifyAgainstBool($right, $rightResult, $leftType->isTrue()->yes(), $context, $evaluationScope);
}
$rightType = $this->literalType($unwrappedRight) ?? $rightResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (($rightType->isTrue()->yes() || $rightType->isFalse()->yes()) && !$unwrappedLeft instanceof Expr\ConstFetch) {
return $this->specifyAgainstBool($left, $leftResult, $rightType->isTrue()->yes(), $context, $evaluationScope);
}
$types = $this->specifyAgainstScalarLiteral($left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
if ($types !== null) {
return $types;
}
return $this->specifyGeneral($left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
if ($constantName === 'null') {
// deliberately NOT guarded by specifyDecidedComparison(): a decided
// null comparison still emits its subtraction entry so assign-time
// conditional holders fire ($id = $x?->prop; if ($id !== null) makes
// $x non-null even when $id's own type already excludes null) - the
// old path's blanket guard here is what kept bug-10482 red
return $this->defaultNarrowingHelper->createSubjectTypes(
$evaluationScope,
$subject,
$subjectResult,
new NullType(),
$context,
);
}
return $this->specifyAgainstBool($subject, $subjectResult, $constantName === 'true', $context, $evaluationScope);
}
/**
* A bool constant pins itself through the entries and runs the subject's
* own narrowing in the matching bool context - identity, not truthiness:
* `=== false` is the false context, not falsey.
*/
private function specifyAgainstBool(
Expr $subject,
ExpressionResult $subjectResult,
bool $value,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
): SpecifiedTypes
{
$types = $this->defaultNarrowingHelper->createSubjectTypes(
$evaluationScope,
$subject,
$subjectResult,
new ConstantBooleanType($value),
$context,
);
// a nullsafe chain that did not produce the constant may have
// short-circuited instead - its own narrowing only holds when the
// comparison succeeded
$unwrappedSubject = $subject instanceof AlwaysRememberedExpr ? $subject->getExpr() : $subject;
if (!$context->true() && ($unwrappedSubject instanceof Expr\NullsafeMethodCall || $unwrappedSubject instanceof Expr\NullsafePropertyFetch)) {
return $types;
}
$boolContext = $value ? TypeSpecifierContext::createTrue() : TypeSpecifierContext::createFalse();
return $types->unionWith($subjectResult->getSpecifiedTypesForScope(
$evaluationScope,
$context->true() ? $boolContext : $boolContext->negate(),
));
}
/**
* Slice 3: comparisons against a scalar literal or a class constant
* (`$a === 5`, `$s === Foo::BAR`, `$suit === Suit::Hearts`) pin the
* single-valued side onto the other operand - the composed form of the
* finite-types narrowing at the tail of the old identical path.
*/
/**
* @param callable(): Type $identicalTypeCallback
*/
private function specifyAgainstScalarLiteral(
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $leftArgResult,
?ExpressionResult $rightArgResult,
callable $identicalTypeCallback,
): ?SpecifiedTypes
{
if ($this->isScalarLiteral($left)) {
$constantExpr = $left;
$constantResult = $leftResult;
$subject = $right;
$subjectResult = $rightResult;
} elseif ($this->isScalarLiteral($right)) {
$constantExpr = $right;
$constantResult = $rightResult;
$subject = $left;
$subjectResult = $leftResult;
} else {
return null;
}
$unwrappedSubject = $subject instanceof AlwaysRememberedExpr ? $subject->getExpr() : $subject;
if ($unwrappedSubject instanceof Expr\FuncCall) {
$familyTypes = $this->specifyFuncCallFamilies($subject, $subjectResult, $unwrappedSubject, $constantExpr, $this->literalType($constantExpr) ?? $constantResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted), $context, $evaluationScope, $subject === $left ? $leftArgResult : $rightArgResult);
if ($familyTypes === null) {
return null;
}
if ($familyTypes !== false) {
return $familyTypes;
}
} elseif ($unwrappedSubject instanceof Expr\ClassConstFetch && $unwrappedSubject->class instanceof Expr) {
// only ::class composes; a constant fetched off an object falls back
if ($unwrappedSubject->name instanceof Expr || $unwrappedSubject->name->toLowerString() !== 'class') {
return null;
}
} elseif (!$this->isSubjectCoveredAgainstConstant($subject)) {
return null;
}
$constantType = $this->literalType($constantExpr) ?? $constantResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (count($constantType->getFiniteTypes()) !== 1) {
// a class constant does not have to be single-valued
return null;
}
// $a::class === Foo::class narrows $a to a final Foo when true;
// other contexts and plain-string sides only pin the fetch
if (
$unwrappedSubject instanceof Expr\ClassConstFetch
&& $unwrappedSubject->class instanceof Expr
&& $context->true()
&& $constantExpr instanceof Expr\ClassConstFetch
) {
$constantStrings = $constantType->getConstantStrings();
if (count($constantStrings) === 1 && $constantStrings[0]->getValue() !== '') {
if (!$this->reflectionProvider->hasClass($constantStrings[0]->getValue())) {
// an unknown class name narrows like instanceof - not composed yet
return null;
}
return $this->defaultNarrowingHelper->createForSubject(
$unwrappedSubject->class,
new ObjectType($constantStrings[0]->getValue(), classReflection: $this->reflectionProvider->getClass($constantStrings[0]->getValue())->asFinal()),
$context,
$evaluationScope,
)->unionWith($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, $constantType, $context));
}
}
$decidedTypes = $this->specifyDecidedComparison($left, $right, $leftResult, $rightResult, $context, $evaluationScope, $identicalTypeCallback);
if ($decidedTypes !== null) {
return $decidedTypes;
}
$types = $this->defaultNarrowingHelper->createSubjectTypes(
$evaluationScope,
$subject,
$subjectResult,
$constantType,
$context,
);
// a single-valued subject pins its value onto the literal side too
$subjectType = $subjectResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (count($subjectType->getFiniteTypes()) === 1) {
$types = $types->unionWith($this->defaultNarrowingHelper->createSubjectTypes(
$evaluationScope,
$constantExpr,
$constantResult,
$subjectType,
$context,
));
}
return $types;
}
/**
* A statically decided comparison tells the false context nothing: the
* branch is dead on the certain flavour, and subtracting the constant
* would wrongly leak into the wider native flavour (mixed~'ab'). The
* NeverType entries mirror the old identical tail's no-op.
*
* @param callable(): Type $identicalTypeCallback
*/
private function specifyDecidedComparison(
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
callable $identicalTypeCallback,
): ?SpecifiedTypes
{
if (!$context->false()) {
return null;
}
$identicalType = $identicalTypeCallback();
$isTrue = $identicalType->isTrue()->yes();
if (!$isTrue && !$identicalType->isFalse()->yes()) {
return null;
}
$never = new NeverType();
$contextForTypes = $isTrue ? $context->negate() : $context;
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, $never, $contextForTypes)->unionWith(
$this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, $never, $contextForTypes),
);
}
private function getTypeFromGettypeStringValue(string $value): ?Type
{
if ($value === 'string') {
return new StringType();
}
if ($value === 'array') {
return new ArrayType(new MixedType(), new MixedType());
}
if ($value === 'boolean') {
return new BooleanType();
}
if (in_array($value, ['resource', 'resource (closed)'], true)) {
return new ResourceType();
}
if ($value === 'integer') {
return new IntegerType();
}
if ($value === 'double') {
return new FloatType();
}
if ($value === 'NULL') {
return new NullType();
}
if ($value === 'object') {
return new ObjectWithoutClassType();
}
return null;
}
/**
* The general expr-vs-expr tail of the identical narrowing: a
* single-valued side pins its value onto the other, otherwise both sides
* pin each other's types in the true context and cross-exclude in the
* false one. Runs only for operand shapes whose specialized narrowing is
* already composed - calls and ::class fetches still fall back.
*
* @param callable(): Type $identicalTypeCallback
*/
private function specifyGeneral(
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $leftArgResult,
?ExpressionResult $rightArgResult,
callable $identicalTypeCallback,
): ?SpecifiedTypes
{
$unwrappedLeft = $left instanceof AlwaysRememberedExpr ? $left->getExpr() : $left;
$unwrappedRight = $right instanceof AlwaysRememberedExpr ? $right->getExpr() : $right;
// a `$a::class` side falls back only where the old instanceof-style
// blocks would fire: a true context with a single class-name string
// or a `static::class`-like fetch on the other side; everything else
// narrows generically
if ($context->true()) {
foreach ([
[$unwrappedLeft, $left, $leftResult, $unwrappedRight, $rightResult],
[$unwrappedRight, $right, $rightResult, $unwrappedLeft, $leftResult],
] as [$sideUnwrapped, $side, $sideResult, $otherUnwrapped, $otherResult]) {
if (!($sideUnwrapped instanceof Expr\ClassConstFetch) || !($sideUnwrapped->class instanceof Expr)) {
continue;
}
// only `$expr::class` names the fetched-on class - any other
// constant ($obj::TYPE === '<some class name>') compares plain
// values and must not narrow the fetched-on object
if ($sideUnwrapped->name instanceof Expr || $sideUnwrapped->name->toLowerString() !== 'class') {
continue;
}
$otherType = $otherResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$otherStrings = $otherType->getConstantStrings();
if (count($otherStrings) !== 1 || $otherStrings[0]->getValue() === '') {
// $a::class === static::class narrows $a to the class-string's object type
if ($otherUnwrapped instanceof Expr\ClassConstFetch && $otherUnwrapped->class instanceof Name) {
$otherObjectType = $otherType->getClassStringObjectType();
if ($otherObjectType->isObject()->yes()) {
return $this->defaultNarrowingHelper->createForSubject(
$sideUnwrapped->class,
$otherObjectType,
$context,
$evaluationScope,
)->unionWith($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $side, $sideResult, $otherType, $context));
}
}
continue;
}
if (!$this->reflectionProvider->hasClass($otherStrings[0]->getValue())) {
// an unknown class narrows like instanceof: intersect the
// fetched-on object with the named type (it cannot be pinned
// as final without reflection)
return $this->defaultNarrowingHelper->createForSubject(
$sideUnwrapped->class,
new ObjectType($otherStrings[0]->getValue()),
$context,
$evaluationScope,
)->unionWith($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $side, $sideResult, $otherStrings[0], $context));
}
return $this->defaultNarrowingHelper->createForSubject(
$sideUnwrapped->class,
new ObjectType($otherStrings[0]->getValue(), classReflection: $this->reflectionProvider->getClass($otherStrings[0]->getValue())->asFinal()),
$context,
$evaluationScope,
)->unionWith($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $side, $sideResult, $otherStrings[0], $context));
}
}
$leftType = $this->literalType($unwrappedLeft) ?? $leftResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$rightType = $this->literalType($unwrappedRight) ?? $rightResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
// fn1() === fn2() merges both normalized directions
if ($unwrappedLeft instanceof Expr\FuncCall && $unwrappedRight instanceof Expr\FuncCall) {
// count($a) === count($b): a decided size flows across; otherwise
// one non-empty side makes both non-empty
if (
$context->true()
&& $unwrappedLeft->name instanceof Name && in_array($unwrappedLeft->name->toLowerString(), ['count', 'sizeof'], true) && !$unwrappedLeft->isFirstClassCallable() && isset($unwrappedLeft->getArgs()[0])
&& $unwrappedRight->name instanceof Name && in_array($unwrappedRight->name->toLowerString(), ['count', 'sizeof'], true) && !$unwrappedRight->isFirstClassCallable() && isset($unwrappedRight->getArgs()[0])
) {
if ($leftArgResult === null || $rightArgResult === null) {
return null;
}
$rightArgType = $rightArgResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$countTypes = $this->countNarrowingHelper->specifyCountSize($unwrappedRight, $rightArgType, $leftType, $context, $evaluationScope, $unwrappedRight);
if ($countTypes !== null) {
return $countTypes;
}
$leftArgType = $leftArgResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (
$leftArgType->isArray()->yes()
&& $rightArgType->isArray()->yes()
&& !$rightType->isConstantScalarValue()->yes()
&& ($leftArgType->isIterableAtLeastOnce()->yes() || $rightArgType->isIterableAtLeastOnce()->yes())
) {
return $this->defaultNarrowingHelper->createForSubject($unwrappedLeft->getArgs()[0]->value, new NonEmptyArrayType(), $context, $evaluationScope)->unionWith(
$this->defaultNarrowingHelper->createForSubject($unwrappedRight->getArgs()[0]->value, new NonEmptyArrayType(), $context, $evaluationScope),
);
}
}
$leftDirection = $this->specifyFuncCallFamilies($left, $leftResult, $unwrappedLeft, $right, $rightType, $context, $evaluationScope, $leftArgResult);
$rightDirection = $this->specifyFuncCallFamilies($right, $rightResult, $unwrappedRight, $left, $leftType, $context, $evaluationScope, $rightArgResult);
if ($leftDirection === null || $rightDirection === null) {
return null;
}
$merged = null;
if ($leftDirection !== false) {
$merged = $leftDirection;
}
if ($rightDirection !== false) {
$merged = $merged !== null ? $merged->unionWith($rightDirection) : $rightDirection;
}
if ($merged !== null) {
return $merged;
}
// neither family matched - the generic tail below pins both sides
}
// a single call side runs the family compositions with the other
// side's TYPE as the constant - the composed form of the old
// normalization that moved the call to the left
if ($unwrappedLeft instanceof Expr\FuncCall || $unwrappedRight instanceof Expr\FuncCall) {
if ($unwrappedLeft instanceof Expr\FuncCall) {
$familyTypes = $this->specifyFuncCallFamilies($left, $leftResult, $unwrappedLeft, $right, $rightType, $context, $evaluationScope, $leftArgResult);
} else {
$familyTypes = $this->specifyFuncCallFamilies($right, $rightResult, $unwrappedRight, $left, $leftType, $context, $evaluationScope, $rightArgResult);
}
if ($familyTypes === null) {
return null;
}
if ($familyTypes !== false) {
return $familyTypes;
}
}
$decidedTypes = $this->specifyDecidedComparison($left, $right, $leftResult, $rightResult, $context, $evaluationScope, $identicalTypeCallback);
if ($decidedTypes !== null) {
return $decidedTypes;
}
$types = null;
if (
count($leftType->getFiniteTypes()) === 1
|| (
$context->true()
&& $leftType->isConstantValue()->yes()
&& !$rightType->equals($leftType)
&& $rightType->isSuperTypeOf($leftType)->yes())
) {
$types = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, $leftType, $context);
}
if (
count($rightType->getFiniteTypes()) === 1
|| (
$context->true()
&& $rightType->isConstantValue()->yes()
&& !$leftType->equals($rightType)
&& $leftType->isSuperTypeOf($rightType)->yes()
)
) {
$leftTypes = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, $rightType, $context);
$types = $types !== null ? $types->unionWith($leftTypes) : $leftTypes;
}
if ($types !== null) {
return $types;
}
$leftExprString = $this->exprPrinter->printExpr($unwrappedLeft);
$rightExprString = $this->exprPrinter->printExpr($unwrappedRight);
if ($leftExprString === $rightExprString) {
if (!$unwrappedLeft instanceof Expr\Variable || !$unwrappedRight instanceof Expr\Variable) {
return new SpecifiedTypes([], []);
}
}
if ($context->true()) {
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, $rightType, $context)->unionWith(
$this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, $leftType, $context),
);
} elseif ($context->false()) {
return $this->defaultNarrowingHelper->toSureTypes($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, $leftType, $context), $evaluationScope)
->intersectWith($this->defaultNarrowingHelper->toSureTypes($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, $rightType, $context), $evaluationScope));
}
return new SpecifiedTypes([], []);
}
/**
* New-world narrowing for `==` (and, via a negated context, `!=`):
* loose comparisons reduce to falsy-set pins, truthiness delegation, or
* the identical narrowing when coercion cannot differ - all composed
* from the operand results, no synthetic nodes. Uncovered shapes return
* null and fall back to the old-world Equal path.
*/
public function specifyEqual(
NodeScopeResolver $nodeScopeResolver,
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $leftArgResult,
?ExpressionResult $rightArgResult,
): ?SpecifiedTypes
{
if ($context->null()) {
return null;
}
$identicalTypeCallback = fn (): Type => $this->richerScopeGetTypeHelper->getIdenticalResult($evaluationScope, new Expr\BinaryOp\Identical($left, $right), $nodeScopeResolver)->type;
$unwrappedLeft = $left instanceof AlwaysRememberedExpr ? $left->getExpr() : $left;
$unwrappedRight = $right instanceof AlwaysRememberedExpr ? $right->getExpr() : $right;
$leftType = $this->literalType($unwrappedLeft) ?? $leftResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$rightType = $this->literalType($unwrappedRight) ?? $rightResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$leftScalarValues = $leftType->getConstantScalarValues();
$rightScalarValues = $rightType->getConstantScalarValues();
if (count($leftScalarValues) === 1 && !$unwrappedRight instanceof Expr\ConstFetch) {
$constantSideTypes = $this->specifyEqualAgainstConstantSide($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $right, $rightResult, $leftScalarValues[0], $leftType, $rightType, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
if ($constantSideTypes !== false) {
return $constantSideTypes;
}
} elseif (count($rightScalarValues) === 1 && !$unwrappedLeft instanceof Expr\ConstFetch) {
$constantSideTypes = $this->specifyEqualAgainstConstantSide($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $left, $leftResult, $rightScalarValues[0], $rightType, $leftType, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
if ($constantSideTypes !== false) {
return $constantSideTypes;
}
}
// a side that coerces to a known bool compares the other side's
// truthiness - the literal-bool identical narrowing composes it
$leftBool = $leftType->toBoolean();
if (($leftBool->isTrue()->yes() || $leftBool->isFalse()->yes()) && $rightType->isBoolean()->yes()) {
// the literal side of the delegation needs no result; the subject side is the right operand
return $this->specifyIdentical($nodeScopeResolver, new Expr\ConstFetch(new Name($leftBool->isTrue()->yes() ? 'true' : 'false')), $right, $rightResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
$rightBool = $rightType->toBoolean();
if (($rightBool->isTrue()->yes() || $rightBool->isFalse()->yes()) && $leftType->isBoolean()->yes()) {
return $this->specifyIdentical($nodeScopeResolver, $left, new Expr\ConstFetch(new Name($rightBool->isTrue()->yes() ? 'true' : 'false')), $leftResult, $leftResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
// an empty constant array equals only empty countables
if ($rightType->isArray()->yes() && $leftType->isConstantArray()->yes() && $leftType->isIterableAtLeastOnce()->no()) {
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, new NonEmptyArrayType(), $context->negate());
}
if ($leftType->isArray()->yes() && $rightType->isConstantArray()->yes() && $rightType->isIterableAtLeastOnce()->no()) {
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, new NonEmptyArrayType(), $context->negate());
}
// same-type sides cannot coerce - loose equals strict
if (
($leftType->isString()->yes() && $rightType->isString()->yes())
|| ($leftType->isInteger()->yes() && $rightType->isInteger()->yes())
|| ($leftType->isFloat()->yes() && $rightType->isFloat()->yes())
|| ($leftType->isEnum()->yes() && $rightType->isEnum()->yes())
) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
$leftExprString = $this->exprPrinter->printExpr($left);
$rightExprString = $this->exprPrinter->printExpr($right);
if ($leftExprString === $rightExprString) {
if (!$left instanceof Expr\Variable || !$right instanceof Expr\Variable) {
return new SpecifiedTypes([], []);
}
}
$leftTypes = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $left, $leftResult, $leftType, $context);
$rightTypes = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $right, $rightResult, $rightType, $context);
return $context->true()
? $leftTypes->unionWith($rightTypes)
: $this->defaultNarrowingHelper->toSureTypes($leftTypes, $evaluationScope)->intersectWith($this->defaultNarrowingHelper->toSureTypes($rightTypes, $evaluationScope));
}
/**
* Identity narrowing of a subject against a known constant type - the
* entry point for callers that hold no comparison node at all (the
* assign-time conditional holders compare the assigned expression with
* falsy sentinels). $constantExpr is only printed into reverse entries,
* never walked. Null means the shape is not composed and the caller
* keeps its old-world path.
*
* @param callable(): Type $identicalTypeCallback
*/
public function specifyIdenticalAgainstType(
Expr $subject,
ExpressionResult $subjectResult,
Expr $constantExpr,
Type $constantType,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $subjectArgResult,
callable $identicalTypeCallback,
): ?SpecifiedTypes
{
if ($context->null()) {
return null;
}
if ($constantType->isNull()->yes()) {
// unguarded like the null-literal slice - the subtraction entry
// must keep firing conditional holders
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, new NullType(), $context);
}
$unwrappedSubject = $subject instanceof AlwaysRememberedExpr ? $subject->getExpr() : $subject;
if ($constantType->isTrue()->yes() || $constantType->isFalse()->yes()) {
$types = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, new ConstantBooleanType($constantType->isTrue()->yes()), $context);
if (!$context->true() && ($unwrappedSubject instanceof Expr\NullsafeMethodCall || $unwrappedSubject instanceof Expr\NullsafePropertyFetch)) {
return $types;
}
$boolContext = $constantType->isTrue()->yes() ? TypeSpecifierContext::createTrue() : TypeSpecifierContext::createFalse();
return $types->unionWith($subjectResult->getSpecifiedTypesForScope(
$evaluationScope,
$context->true() ? $boolContext : $boolContext->negate(),
));
}
if ($unwrappedSubject instanceof Expr\FuncCall) {
$familyTypes = $this->specifyFuncCallFamilies($subject, $subjectResult, $unwrappedSubject, $constantExpr, $constantType, $context, $evaluationScope, $subjectArgResult);
if ($familyTypes === null) {
return null;
}
if ($familyTypes !== false) {
return $familyTypes;
}
} elseif ($unwrappedSubject instanceof Expr\ClassConstFetch && $unwrappedSubject->class instanceof Expr) {
return null;
}
if ($context->false()) {
$identicalType = $identicalTypeCallback();
$isTrue = $identicalType->isTrue()->yes();
if ($isTrue || $identicalType->isFalse()->yes()) {
$never = new NeverType();
$contextForTypes = $isTrue ? $context->negate() : $context;
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, $never, $contextForTypes)->unionWith(
$this->defaultNarrowingHelper->createForSubject($constantExpr, $never, $contextForTypes, $evaluationScope),
);
}
}
$types = $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, $constantType, $context);
$subjectType = $subjectResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if (count($subjectType->getFiniteTypes()) === 1) {
$types = $types->unionWith($this->defaultNarrowingHelper->createForSubject($constantExpr, $subjectType, $context, $evaluationScope));
}
return $types;
}
/**
* The == narrowing against a single-valued side: a family answer, null
* to fall back to the old-world path, or false when nothing matched and
* the caller continues with the coercion branches.
*
* @param callable(): Type $identicalTypeCallback
* @return SpecifiedTypes|false|null
*/
private function specifyEqualAgainstConstantSide(
NodeScopeResolver $nodeScopeResolver,
Expr $left,
Expr $right,
ExpressionResult $leftResult,
ExpressionResult $rightResult,
Expr $subject,
ExpressionResult $subjectResult,
mixed $value,
Type $constantType,
Type $otherType,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $leftArgResult,
?ExpressionResult $rightArgResult,
callable $identicalTypeCallback,
): SpecifiedTypes|false|null
{
$unwrappedSubject = $subject instanceof AlwaysRememberedExpr ? $subject->getExpr() : $subject;
if ($value === null) {
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, new UnionType([
new NullType(),
new ConstantBooleanType(false),
new ConstantIntegerType(0),
new ConstantFloatType(0.0),
new ConstantStringType(''),
new ConstantArrayType([], []),
]), $context);
}
// a bool constant compares by the subject's truthiness
if ($value === false) {
return $subjectResult->getSpecifiedTypesForScope(
$evaluationScope,
$context->true() ? TypeSpecifierContext::createFalsey() : TypeSpecifierContext::createFalsey()->negate(),
);
}
if ($value === true) {
return $subjectResult->getSpecifiedTypesForScope(
$evaluationScope,
$context->true() ? TypeSpecifierContext::createTruthy() : TypeSpecifierContext::createTruthy()->negate(),
);
}
/* There is a difference between php 7.x and 8.x on the equality
* behavior between zero and the empty string, so to be conservative
* we leave it untouched regardless of the language version */
if ($value === 0 && !$otherType->isInteger()->yes() && !$otherType->isBoolean()->yes()) {
$trueTypes = $context->true()
? [new NullType(), new ConstantBooleanType(false), new ConstantIntegerType(0), new ConstantFloatType(0.0), new StringType()]
: [new NullType(), new ConstantBooleanType(false), new ConstantIntegerType(0), new ConstantFloatType(0.0), new ConstantStringType('0')];
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, new UnionType($trueTypes), $context);
}
if ($value === '') {
$trueTypes = $context->true()
? [new NullType(), new ConstantBooleanType(false), new ConstantIntegerType(0), new ConstantFloatType(0.0), new ConstantStringType('')]
: [new NullType(), new ConstantBooleanType(false), new ConstantStringType('')];
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, new UnionType($trueTypes), $context);
}
// loose equals strict for these call results and class names
if (
$unwrappedSubject instanceof Expr\FuncCall
&& $unwrappedSubject->name instanceof Name
&& !$unwrappedSubject->isFirstClassCallable()
&& isset($unwrappedSubject->getArgs()[0])
) {
$funcName = $unwrappedSubject->name->toLowerString();
if (in_array($funcName, ['gettype', 'get_class', 'get_debug_type'], true) && $constantType->isString()->yes()) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
if ($context->true() && $funcName === 'preg_match' && (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
}
if (
$unwrappedSubject instanceof Expr\ClassConstFetch
&& !($unwrappedSubject->name instanceof Expr)
&& $unwrappedSubject->name->toLowerString() === 'class'
&& $constantType->isString()->yes()
) {
return $this->specifyIdentical($nodeScopeResolver, $left, $right, $leftResult, $rightResult, $context, $evaluationScope, $leftArgResult, $rightArgResult, $identicalTypeCallback);
}
return false;
}
/**
* The function-family compositions, shared by the literal and the
* TYPE-based constant sides: a family answer, null to fall back to the
* old-world path, or false when no family matched and the caller narrows
* generically.
*
* @return SpecifiedTypes|false|null
*/
private function specifyFuncCallFamilies(
Expr $subject,
ExpressionResult $subjectResult,
Expr\FuncCall $call,
Expr $constantExpr,
Type $constantType,
TypeSpecifierContext $context,
MutatingScope $evaluationScope,
?ExpressionResult $argResult,
): SpecifiedTypes|false|null
{
if (!($call->name instanceof Name) || $call->isFirstClassCallable() || !isset($call->getArgs()[0])) {
return false;
}
// preg_match(...) === 1 is the call's own truthy narrowing - the
// type-specifying extensions narrow the by-ref \$matches argument
if (
$call->name->toLowerString() === 'preg_match'
) {
if ($context->true() && (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()) {
return $subjectResult->getSpecifiedTypesForScope($evaluationScope, $context);
}
// other constants and contexts only pin the call below
}
// a trimmed string that is not '' was a non-empty string already
if (
in_array($call->name->toLowerString(), ['trim', 'ltrim', 'rtrim', 'chop', 'mb_trim', 'mb_ltrim', 'mb_rtrim'], true)
) {
if ($context->false()) {
$constantStrings = $constantType->getConstantStrings();
if (count($constantStrings) === 1 && $constantStrings[0]->getValue() === '') {
$argExpr = $call->getArgs()[0]->value;
if ($argResult === null) {
return null;
}
if ($argResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted)->isString()->yes()) {
return $this->defaultNarrowingHelper->createForSubject(
$argExpr,
new IntersectionType([new StringType(), new AccessoryNonEmptyStringType()]),
$context->negate(),
$evaluationScope,
);
}
}
}
// other constants and contexts only pin the call
}
// a known parent class narrows the argument to the child side of it
if ($call->name->toLowerString() === 'get_parent_class') {
if ($context->true()) {
$constantStrings = $constantType->getConstantStrings();
if (count($constantStrings) === 1 && $constantStrings[0]->getValue() !== '') {
$argExpr = $call->getArgs()[0]->value;
if ($argResult === null) {
return null;
}
$argType = $argResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
$objectType = new ObjectType($constantStrings[0]->getValue());
$classStringType = new GenericClassStringType($objectType);
if ($argType->isString()->yes()) {
$narrowed = $classStringType;
} elseif ($argType->isObject()->yes()) {
$narrowed = $objectType;
} else {
$narrowed = TypeCombinator::union($objectType, $classStringType);
}
return $this->defaultNarrowingHelper->createForSubject($argExpr, $narrowed, $context, $evaluationScope);
}
}
// other contexts and non-single class names only pin the call
}
// a string function whose result is a non-empty literal had a
// non-empty (non-falsy for a non-falsy literal) string argument;
// case-mapping functions pin the case accessory on the literal side
if (
in_array($call->name->toLowerString(), [
'substr', 'strstr', 'stristr', 'strchr', 'strrchr', 'strtolower', 'strtoupper', 'ucfirst', 'lcfirst',
'mb_substr', 'mb_strstr', 'mb_stristr', 'mb_strchr', 'mb_strrchr', 'mb_strtolower', 'mb_strtoupper', 'mb_ucfirst', 'mb_lcfirst',
'ucwords', 'mb_convert_case', 'mb_convert_kana',
], true)
) {
if ($context->truthy() && $constantType->isNonEmptyString()->yes()) {
$argExpr = $call->getArgs()[0]->value;
if ($argResult === null) {
return null;
}
$argType = $argResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if ($argType->isString()->yes()) {
$types = new SpecifiedTypes();
$funcName = $call->name->toLowerString();
if (in_array($funcName, ['strtolower', 'mb_strtolower'], true)) {
$types = $this->defaultNarrowingHelper->createForSubject($constantExpr, TypeCombinator::intersect($constantType, new AccessoryLowercaseStringType()), $context, $evaluationScope);
} elseif (in_array($funcName, ['strtoupper', 'mb_strtoupper'], true)) {
$types = $this->defaultNarrowingHelper->createForSubject($constantExpr, TypeCombinator::intersect($constantType, new AccessoryUppercaseStringType()), $context, $evaluationScope);
}
$accessory = $constantType->isNonFalsyString()->yes()
? new AccessoryNonFalsyStringType()
: new AccessoryNonEmptyStringType();
return $types->unionWith($this->defaultNarrowingHelper->createForSubject(
$argExpr,
TypeCombinator::intersect($argType, $accessory),
$context,
$evaluationScope,
));
}
}
// a non-string argument, an empty literal or a non-truthy
// context only pins the call
}
// count($x) === N reconstructs the array shape by its size - before
// the decided guard so exhaustive size switches keep collapsing
if (
in_array($call->name->toLowerString(), ['count', 'sizeof'], true)
) {
if (!$constantType->isInteger()->yes()) {
return null;
}
$argExpr = $call->getArgs()[0]->value;
if (IntegerRangeType::fromInterval(null, -1)->isSuperTypeOf($constantType)->yes()) {
return $this->defaultNarrowingHelper->createForSubject($argExpr, new NeverType(), $context, $evaluationScope);
}
if ($argResult === null) {
return null;
}
$argType = $argResult->getTypeOnScope($evaluationScope, $evaluationScope->nativeTypesPromoted);
if ((new ConstantIntegerType(0))->isSuperTypeOf($constantType)->yes()) {
$newArgType = $context->truthy() && !$argType->isArray()->yes()
? new UnionType([new ObjectType(Countable::class), new ConstantArrayType([], [])])
: new ConstantArrayType([], []);
return $this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, $constantType, $context)->unionWith(
$this->defaultNarrowingHelper->createForSubject($argExpr, $newArgType, $context, $evaluationScope),
);
}
$countTypes = $this->countNarrowingHelper->specifyCountSize($call, $argType, $constantType, $context, $evaluationScope, $call);
if ($countTypes !== null) {
// the old path pinned the call only through the remembered
// wrapper; the composed pin covers wrapper and call alike
if ($subject !== $call) {
return $countTypes->unionWith($this->defaultNarrowingHelper->createSubjectTypes($evaluationScope, $subject, $subjectResult, $constantType, $context));