Repository navigation
Expand file tree
/
Copy pathCountNarrowingHelper.php
More file actions
220 lines (192 loc) · 7.28 KB
/
Copy pathCountNarrowingHelper.php
File metadata and controls
220 lines (192 loc) · 7.28 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler\Helper;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Accessory\HasOffsetValueType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
use function sprintf;
use const COUNT_NORMAL;
/**
* Narrows a count()/sizeof() argument by the known size of the result -
* shape reconstruction for constant arrays and lists. The former
* TypeSpecifier::specifyTypesForCountFuncCall(), composed through
* createForSubject() instead of TypeSpecifier::create().
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../../turbo-ext/src/CountNarrowingHelper.cpp')]
final class CountNarrowingHelper
{
public function __construct(
private DefaultNarrowingHelper $defaultNarrowingHelper,
private ExprPrinter $exprPrinter,
)
{
}
public function isNormalCountCall(FuncCall $countFuncCall, Type $typeToCount, MutatingScope $scope): TrinaryLogic
{
if (count($countFuncCall->getArgs()) === 1) {
return TrinaryLogic::createYes();
}
$modeArg = $countFuncCall->getArgs()[1]->value;
// the mode argument was processed with the call - a census over the suite
// and self-analysis found every ask answered from the stored result
$storage = $scope->getCurrentExpressionResultStorage();
$modeResult = $storage?->findExpressionResult($modeArg);
if ($modeResult === null) {
throw new ShouldNotHappenException(sprintf('count() mode argument on line %d has no stored ExpressionResult.', $modeArg->getStartLine()));
}
$mode = $modeResult->getTypeOnScope($scope, $scope->nativeTypesPromoted);
return (new ConstantIntegerType(COUNT_NORMAL))->isSuperTypeOf($mode)->result->or($typeToCount->getIterableValueType()->isArray()->negate());
}
public function specifyCountSize(
FuncCall $countFuncCall,
Type $type,
Type $sizeType,
TypeSpecifierContext $context,
MutatingScope $scope,
Expr $rootExpr,
): ?SpecifiedTypes
{
$isConstantArray = $type->isConstantArray();
$isList = $type->isList();
$oneOrMore = IntegerRangeType::fromInterval(1, null);
if (
!$this->isNormalCountCall($countFuncCall, $type, $scope)->yes()
|| (!$isConstantArray->yes() && !$isList->yes())
|| !$oneOrMore->isSuperTypeOf($sizeType)->yes()
|| $sizeType->isSuperTypeOf($type->getArraySize())->yes()
) {
return null;
}
if ($context->falsey() && $isConstantArray->yes()) {
$remainingSize = TypeCombinator::remove($type->getArraySize(), $sizeType);
if (!$remainingSize instanceof NeverType) {
$negatedContext = $context->false()
? TypeSpecifierContext::createTrue()
: TypeSpecifierContext::createTruthy();
$result = $this->specifyCountSize(
$countFuncCall,
$type,
$remainingSize,
$negatedContext,
$scope,
$rootExpr,
);
if ($result !== null) {
return $result;
}
}
// Fallback: directly filter constant arrays by their exact sizes.
// This avoids using TypeCombinator::remove() with falsey context,
// which can incorrectly remove arrays whose count doesn't match
// but whose shape is a subtype of the matched array.
$keptTypes = [];
foreach ($type->getConstantArrays() as $arrayType) {
if ($sizeType->isSuperTypeOf($arrayType->getArraySize())->yes()) {
continue;
}
$keptTypes[] = $arrayType;
}
if ($keptTypes !== []) {
return $this->defaultNarrowingHelper->createForSubject(
$countFuncCall->getArgs()[0]->value,
TypeCombinator::union(...$keptTypes),
$context->negate(),
$scope,
)->setRootExpr($rootExpr);
}
}
$resultTypes = [];
foreach ($type->getArrays() as $arrayType) {
$isSizeSuperTypeOfArraySize = $sizeType->isSuperTypeOf($arrayType->getArraySize());
if ($isSizeSuperTypeOfArraySize->no()) {
continue;
}
if ($context->falsey() && $isSizeSuperTypeOfArraySize->maybe()) {
continue;
}
if ($isList->yes()) {
$resultTypes[] = $arrayType->truncateListToSize($sizeType);
continue;
}
foreach ($arrayType->getConstantArrays() as $constantArray) {
$arrayType = $this->narrowShapeToSize($constantArray, $sizeType);
}
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
}
if ($context->truthy() && $isConstantArray->yes() && $isList->yes()) {
$hasOptionalKeysOrUnsealed = false;
foreach ($type->getConstantArrays() as $arrayType) {
if ($arrayType->getOptionalKeys() !== [] || $arrayType->isUnsealed()->yes()) {
// Unsealed CATs can't be narrowed via the
// `HasOffsetValueType`-only shortcut below — the
// intersection of an unsealed shape with a single-slot
// constraint produces `NeverType`. Fall through to
// the full builder-based narrowing, which carries the
// unsealed slot via the loop above.
$hasOptionalKeysOrUnsealed = true;
break;
}
}
if (!$hasOptionalKeysOrUnsealed) {
$argExpr = $countFuncCall->getArgs()[0]->value;
$argExprString = $this->exprPrinter->printExpr($argExpr);
[$sizeMin, $sizeMax] = ConstantArrayType::extractTruncateListBounds($sizeType);
$sureTypes = [];
$sureNotTypes = [];
if ($sizeMin !== null && $sizeMin >= 1) {
$sureTypes[$argExprString] = [$argExpr, new HasOffsetValueType(new ConstantIntegerType($sizeMin - 1), new MixedType())];
}
if ($sizeMax !== null) {
$sureNotTypes[$argExprString] = [$argExpr, new HasOffsetValueType(new ConstantIntegerType($sizeMax), new MixedType())];
}
if ($sureTypes !== [] || $sureNotTypes !== []) {
return (new SpecifiedTypes($sureTypes, $sureNotTypes))->setRootExpr($rootExpr);
}
}
}
return $this->defaultNarrowingHelper->createForSubject($countFuncCall->getArgs()[0]->value, TypeCombinator::union(...$resultTypes), $context, $scope)->setRootExpr($rootExpr);
}
/**
* A sealed shape whose size can only be the number of its required keys has none of the optional ones,
* and one whose size can only be the number of all its keys has every one of them.
*/
private function narrowShapeToSize(ConstantArrayType $arrayType, Type $sizeType): Type
{
$optionalKeys = $arrayType->getOptionalKeys();
if ($optionalKeys === [] || !$arrayType->isUnsealed()->no()) {
return $arrayType;
}
$keyTypes = $arrayType->getKeyTypes();
$sizeType = TypeCombinator::intersect($sizeType, $arrayType->getArraySize());
if ((new ConstantIntegerType(count($keyTypes) - count($optionalKeys)))->isSuperTypeOf($sizeType)->yes()) {
$narrowed = $arrayType;
foreach ($optionalKeys as $i) {
$narrowed = $narrowed->unsetOffset($keyTypes[$i]);
}
return $narrowed;
}
if ((new ConstantIntegerType(count($keyTypes)))->isSuperTypeOf($sizeType)->yes()) {
foreach ($optionalKeys as $i) {
$arrayType = $arrayType->makeOffsetRequired($keyTypes[$i]);
}
}
return $arrayType;
}
}