Repository navigation
Expand file tree
/
Copy pathAssignOpHandler.php
More file actions
326 lines (289 loc) · 13.3 KB
/
Copy pathAssignOpHandler.php
File metadata and controls
326 lines (289 loc) · 13.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
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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use DivisionByZeroError;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\AssignTargetWalkMode;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultFactory;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\ExprHandler;
use PHPStan\Analyser\ExprHandler\Helper\CoalesceCompositionHelper;
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
use PHPStan\Analyser\ExprHandler\Helper\ImplicitToStringCallHelper;
use PHPStan\Analyser\Generics\ClosureSignatureInference;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\CoalesceExpressionNode;
use PHPStan\Node\Variable\VariableWrite;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StaticTypeFactory;
use PHPStan\Type\Type;
use TypeError;
use function array_merge;
use function count;
use function get_class;
use function is_string;
use function sprintf;
/**
* @implements ExprHandler<AssignOp>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/AssignOpHandler.cpp')]
final class AssignOpHandler implements ExprHandler
{
public function __construct(
private AssignHandler $assignHandler,
private InitializerExprTypeResolver $initializerExprTypeResolver,
private ImplicitToStringCallHelper $implicitToStringCallHelper,
private ExpressionResultFactory $expressionResultFactory,
private DefaultNarrowingHelper $defaultNarrowingHelper,
private CoalesceCompositionHelper $coalesceCompositionHelper,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof AssignOp;
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$target = $this->assignHandler->prepareTarget(
$nodeScopeResolver,
$scope,
$storage,
$stmt,
$expr->var,
$expr,
$nodeCallback,
$context,
$expr instanceof Expr\AssignOp\Coalesce ? AssignTargetWalkMode::coalesceReadModifyWrite() : AssignTargetWalkMode::readModifyWrite(),
);
$targetReadResult = $target->getTargetReadResult();
$condResult = $expr instanceof Expr\AssignOp\Coalesce ? $targetReadResult : null;
$chainResults = $target->getTargetChainResults();
$rightResult = null;
$valueBeforeScope = $target->getScope();
$valueScope = $valueBeforeScope;
$valueContext = $context;
if ($expr instanceof Expr\AssignOp\Coalesce) {
if ($condResult === null) {
throw new ShouldNotHappenException();
}
// the value expr only evaluates when the left side is null or
// unset - the falsey isset() narrowing, composed from the left read
$valueScope = $valueScope->applySpecifiedTypes($this->coalesceCompositionHelper->getRightSideScopeSpecifiedTypes($valueScope, $expr->var, $condResult, $chainResults, $expr));
if ($expr->var instanceof Expr\Variable && is_string($expr->var->name)) {
$valueContext = $valueContext->enterRightSideAssign(
$expr->var->name,
$expr->expr,
);
}
}
$valueFlowWrite = VariableFlowBuilder::writeSite($expr->var, VariableWrite::KIND_READ_MODIFY_WRITE, $valueScope, $storage);
$valueContext = $valueFlowWrite !== null ? $valueContext->enterDeep()->enterValueFlow($valueFlowWrite, false) : $valueContext->enterDeep();
$valueResult = $nodeScopeResolver->processExprNode($stmt, $expr->expr, $valueScope, $storage, $nodeCallback, $valueContext);
$rhsResult = $valueResult;
if ($expr instanceof Expr\AssignOp\Coalesce) {
$rightResult = $valueResult;
$coalescedScope = $rightResult->getScope()->mergeWith($valueBeforeScope);
if ($nodeScopeResolver->observingTemplateArgumentFrame($coalescedScope) !== null) {
$coalescedScope = $coalescedScope->addTemplateArgumentConstraints(ClosureSignatureInference::collectAbsorbedInUnion([$condResult->getType(), $rightResult->getType()]));
}
$valueResult = $this->expressionResultFactory->create(
$coalescedScope,
$valueBeforeScope,
$expr->expr,
$rightResult->hasYield(),
$rightResult->isAlwaysTerminating() && $condResult->getType()->isNull()->yes(),
$rightResult->getThrowPoints(),
$rightResult->getImpurePoints(),
typeCallback: static fn () => new MixedType(),
specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
);
}
$typeCallback = function (bool $nativeTypesPromoted) use ($expr, $nodeScopeResolver, $beforeScope, $condResult, $chainResults, $rightResult, $targetReadResult, $rhsResult): Type {
// the operands' results are in hand: the target read from
// prepareTarget(), the value expr from the phase between
// prepareTarget() and applyWrite() - no storage round-trip
$getType = static function (Expr $e) use ($expr, $nodeScopeResolver, $beforeScope, $targetReadResult, $rhsResult, $nativeTypesPromoted): Type {
$s = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
if ($e === $expr->var) {
return $targetReadResult->getTypeOnScope($s, $s->nativeTypesPromoted);
}
if ($e === $expr->expr) {
return $rhsResult->getTypeOnScope($s, $s->nativeTypesPromoted);
}
// InitializerExprTypeResolver also asks about synthetic composed
// nodes (e.g. Mod($left, $right) for modulo bounds) - price those
return $nodeScopeResolver->processSyntheticOnDemand($e, $s)->getTypeOnScope($s, $s->nativeTypesPromoted);
};
if ($expr instanceof Expr\AssignOp\Coalesce) {
return $this->coalesceCompositionHelper->composeType(
$nodeScopeResolver,
$expr->var,
$condResult,
$rightResult,
$beforeScope,
$chainResults,
$expr,
$nativeTypesPromoted,
);
}
if ($expr instanceof Expr\AssignOp\Concat) {
return $this->initializerExprTypeResolver->getConcatType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\BitwiseAnd) {
return $this->initializerExprTypeResolver->getBitwiseAndType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\BitwiseOr) {
return $this->initializerExprTypeResolver->getBitwiseOrType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\BitwiseXor) {
return $this->initializerExprTypeResolver->getBitwiseXorType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Div) {
return $this->initializerExprTypeResolver->getDivType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Mod) {
return $this->initializerExprTypeResolver->getModType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Plus) {
return $this->initializerExprTypeResolver->getPlusType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Minus) {
return $this->initializerExprTypeResolver->getMinusType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Mul) {
return $this->initializerExprTypeResolver->getMulType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\Pow) {
return $this->initializerExprTypeResolver->getPowType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\ShiftLeft) {
return $this->initializerExprTypeResolver->getShiftLeftType($expr->var, $expr->expr, $getType);
}
if ($expr instanceof Expr\AssignOp\ShiftRight) {
return $this->initializerExprTypeResolver->getShiftRightType($expr->var, $expr->expr, $getType);
}
throw new ShouldNotHappenException(sprintf('Unhandled %s', get_class($expr)));
};
$specifyTypesCallback = function (TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $condResult, $beforeScope): SpecifiedTypes {
$types = $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context);
if (!$expr instanceof Expr\AssignOp\Coalesce || $context->null()) {
return $types;
}
// a truthiness constraint on `$x ??= y` also constrains the assigned
// target - the specify-side mirror of the createTypesCallback below
// (the raw term on the assign node itself cannot be unpacked at the
// application point)
if (!$context->truthy()) {
$removedType = StaticTypeFactory::truthy();
} elseif (!$context->falsey()) {
$removedType = StaticTypeFactory::falsey();
} else {
return $types;
}
$cs = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
return $types->unionWith($this->defaultNarrowingHelper->createSubjectTypes($cs, $expr->var, $condResult, $removedType, TypeSpecifierContext::createFalse())->setRootExpr($expr));
};
$createTypesCallback = null;
if ($expr instanceof Expr\AssignOp\Coalesce) {
// a type constraint on `$x ??= y` constrains the assigned variable -
// what TypeSpecifier::create() recovered by its AssignOp\Coalesce arm
$createTypesCallback = function (Type $constraintType, TypeSpecifierContext $cctx, bool $nativeTypesPromoted) use ($expr, $condResult, $beforeScope): SpecifiedTypes {
$cs = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
return $this->defaultNarrowingHelper->createSubjectTypes($cs, $expr->var, $condResult, $constraintType, $cctx);
};
}
// the result standing for the whole `$lvalue OP= value` expression - the
// value applyWrite() writes to the target
$assignOpValueResult = $this->expressionResultFactory->create(
$beforeScope,
beforeScope: $beforeScope,
expr: $expr,
hasYield: false,
isAlwaysTerminating: false,
throwPoints: [],
impurePoints: [],
typeCallback: $typeCallback,
specifyTypesCallback: $specifyTypesCallback,
createTypesCallback: $createTypesCallback,
);
// applyWrite() emits nodes (PropertyAssignNode) whose rules ask about
// this whole `$lvalue OP= value` expression - store its result first so
// those asks answer from the storage; processExprNode() overwrites it
// with the final result after this handler returns
$nodeScopeResolver->storeExpressionResult($storage, $expr, $assignOpValueResult);
$assignResult = $this->assignHandler->applyWrite(
$nodeScopeResolver,
$target,
$valueResult,
$assignOpValueResult,
$stmt,
$storage,
$nodeCallback,
$context,
);
$scope = $assignResult->getScope();
$throwPoints = $assignResult->getThrowPoints();
$impurePoints = $assignResult->getImpurePoints();
if (
($expr instanceof Expr\AssignOp\Div || $expr instanceof Expr\AssignOp\Mod) &&
!$rhsResult->getTypeOnScope($scope, false)->toNumber()->isSuperTypeOf(new ConstantIntegerType(0))->no()
) {
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(DivisionByZeroError::class), $expr, false);
}
if ($expr instanceof Expr\AssignOp\Concat) {
$toStringResult = $this->implicitToStringCallHelper->processImplicitToStringCall($expr->expr, $scope, $rhsResult);
$throwPoints = array_merge($throwPoints, $toStringResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $toStringResult->getImpurePoints());
}
if ($expr instanceof Expr\AssignOp\Coalesce) {
if ($condResult === null || $rightResult === null) {
throw new ShouldNotHappenException();
}
$nodeScopeResolver->callNodeCallbackWithExpression($nodeCallback, new CoalesceExpressionNode($expr, $condResult, $rightResult, 'on left side of ??='), $beforeScope, $storage, $context);
}
$writeFlow = VariableFlow::sequence(
$rhsResult->getVariableFlow(),
$valueFlowWrite !== null && $context->isValueConsumed() ? VariableFlow::inputs($valueFlowWrite->getId(), $context->getValueFlowTarget() !== null ? $context->getValueFlowTarget()->getId() : null) : null,
// an illegal offset throws before the write
count($target->getIllegalOffsetDimFetches()) > 0 ? VariableFlow::throwing(new ObjectType(TypeError::class), true) : null,
VariableFlowBuilder::targetWrite($expr->var, VariableWrite::KIND_READ_MODIFY_WRITE, $scope, $storage),
);
$variableFlow = VariableFlow::sequence(
VariableFlowBuilder::targetRead($expr->var, $storage, true, !($expr instanceof Expr\AssignOp\Coalesce) && $valueFlowWrite !== null ? $valueFlowWrite->getId() : null),
$expr instanceof Expr\AssignOp\Coalesce ? VariableFlow::choice($writeFlow, null) : $writeFlow,
);
return $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: $variableFlow,
hasYield: $assignResult->hasYield(),
isAlwaysTerminating: $assignResult->isAlwaysTerminating(),
throwPoints: $throwPoints,
impurePoints: $impurePoints,
typeCallback: $typeCallback,
specifyTypesCallback: $specifyTypesCallback,
createTypesCallback: $createTypesCallback,
dependencies: Dependencies::merge($rhsResult->getDependencies(), $assignResult->getDependencies()),
);
}
}