Repository navigation
Expand file tree
/
Copy pathArrayDimFetchHandler.php
More file actions
213 lines (192 loc) · 9.75 KB
/
Copy pathArrayDimFetchHandler.php
File metadata and controls
213 lines (192 loc) · 9.75 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use ArrayAccess;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt;
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\DefaultNarrowingHelper;
use PHPStan\Analyser\ExprHandler\Helper\IllegalOffsetTypeHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodCallReturnTypeHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodThrowPointHelper;
use PHPStan\Analyser\Generics\TemplateArgumentFrame;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\IssetabilityDescriptor;
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\Analyser\VariableWriteOffset;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\TypeExpr;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use TypeError;
use function array_merge;
use function is_string;
/**
* @implements ExprHandler<ArrayDimFetch>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ArrayDimFetchHandler.cpp')]
final class ArrayDimFetchHandler implements ExprHandler
{
public function __construct(
private ExpressionResultFactory $expressionResultFactory,
private DefaultNarrowingHelper $defaultNarrowingHelper,
private MethodThrowPointHelper $methodThrowPointHelper,
private MethodCallReturnTypeHelper $methodCallReturnTypeHelper,
private PhpVersion $phpVersion,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof ArrayDimFetch;
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
if ($expr->dim === null) {
$varResult = $nodeScopeResolver->processExprNode($stmt, $expr->var, $scope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow()->enterArrayDimFetchRoot());
return $this->composeResult($nodeScopeResolver, $stmt, $expr, null, $varResult, $storage, $context, $beforeScope);
}
$dimResult = $nodeScopeResolver->processExprNode($stmt, $expr->dim, $scope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow());
$varResult = $nodeScopeResolver->processExprNode($stmt, $expr->var, $dimResult->getScope(), $storage, $nodeCallback, $context->enterDeepKeepingValueFlow()->enterArrayDimFetchRoot());
return $this->composeResult($nodeScopeResolver, $stmt, $expr, $dimResult, $varResult, $storage, $context, $beforeScope);
}
/**
* Builds the offset read's ExpressionResult from the already-walked
* dimension and receiver results - the chain is not re-walked (only the
* ArrayAccess offsetGet simulation runs, over synthetic nodes).
* processExpr() routes through this; AssignHandler::prepareTarget() calls it
* to price a read-modify-write target from the write walk's child results.
*/
public function composeResult(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, ArrayDimFetch $expr, ?ExpressionResult $dimResult, ExpressionResult $varResult, ExpressionResultStorage $storage, ExpressionContext $context, MutatingScope $beforeScope): ExpressionResult
{
$scope = $varResult->getScope();
if ($expr->dim === null || $dimResult === null) {
return $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence($varResult->getVariableFlow(), self::offsetRead($expr, null, $context)),
hasYield: $varResult->hasYield(),
isAlwaysTerminating: $varResult->isAlwaysTerminating(),
throwPoints: $varResult->getThrowPoints(),
impurePoints: $varResult->getImpurePoints(),
containsNullsafe: $varResult->containsNullsafe(),
// `$arr[]` only appears as an assignment target; reading it is a NeverType
typeCallback: static fn (): Type => new NeverType(),
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context),
dependencies: $varResult->getDependencies(),
);
}
$throwPoints = array_merge($dimResult->getThrowPoints(), $varResult->getThrowPoints());
$impurePoints = array_merge($dimResult->getImpurePoints(), $varResult->getImpurePoints());
$varType = $varResult->getType();
// an offset read that is a link in a nullsafe chain may never run - see
// MethodCallHandler::processExpr(). The dimension is walked BEFORE the
// receiver here, so the short-circuited world is the pre-dimension scope.
$mayShortCircuit = $varResult->containsNullsafe() && TypeCombinator::containsNull($varType);
if ($mayShortCircuit) {
$scope = $scope->mergeWith($beforeScope);
}
$offsetGetCall = null;
if (!$varType->isArray()->yes() && !(new ObjectType(ArrayAccess::class))->isSuperTypeOf($varType)->no()) {
$throwPoints = array_merge($throwPoints, $this->methodThrowPointHelper->getThrowPointsForCallOnType(
$scope,
$context,
$varType,
new MethodCall(new TypeExpr($varType), 'offsetGet'),
));
// the offsetGet return type resolves directly in the typeCallback (per
// flavour); the fabricated node is only the payload dynamic return
// type extensions receive - nothing walks it. Gated by the same
// maybe-ArrayAccess condition, so plain arrays never reach it.
$offsetGetCall = new MethodCall($expr->var, new Identifier('offsetGet'), [new Arg($expr->dim)], [TemplateArgumentFrame::SYNTHETIC_SITE_ATTRIBUTE => true]);
}
if (
$this->phpVersion->throwsTypeErrorForIllegalOffsets()
// only array and string offset reads throw TypeError for illegal offsets,
// reads on null and other scalars emit a warning, ArrayAccess objects go through offsetGet();
// isset() and empty() of a string offset are false instead
&& (!$varType->isArray()->no() || (!$context->isIssetTarget() && !$varType->isString()->no()))
&& IllegalOffsetTypeHelper::mayOffsetThrowTypeError($dimResult->getType())
) {
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(TypeError::class), $expr, false);
}
$result = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence(
$varResult->getVariableFlow(),
// the dimension was not evaluated in the short-circuited world
$mayShortCircuit
? VariableFlow::choice($dimResult->getVariableFlow(), null)
: $dimResult->getVariableFlow(),
self::offsetRead($expr, $dimResult, $context),
VariableFlowBuilder::throws($expr, $throwPoints),
),
hasYield: $dimResult->hasYield() || $varResult->hasYield(),
isAlwaysTerminating: (!$mayShortCircuit && $dimResult->isAlwaysTerminating()) || $varResult->isAlwaysTerminating(),
throwPoints: $throwPoints,
impurePoints: $impurePoints,
containsNullsafe: $varResult->containsNullsafe(),
issetabilityDescriptor: IssetabilityDescriptor::offset($varResult, $dimResult),
typeCallback: function (bool $nativeTypesPromoted) use ($varResult, $dimResult, $offsetGetCall, $scope): Type {
$offsetAccessibleType = ($nativeTypesPromoted ? $varResult->getNativeType() : $varResult->getType());
$shortCircuit = static fn (Type $type): Type => $varResult->containsNullsafe() && TypeCombinator::containsNull($offsetAccessibleType)
? TypeCombinator::addNull($type)
: $type;
if (
$offsetGetCall !== null
&& !$offsetAccessibleType->isArray()->yes()
&& (new ObjectType(ArrayAccess::class))->isSuperTypeOf($offsetAccessibleType)->yes()
) {
if ($nativeTypesPromoted) {
$methodReflection = $scope->getMethodReflection($offsetAccessibleType, 'offsetGet');
if ($methodReflection === null) {
return $shortCircuit(new ErrorType());
}
return $shortCircuit(ParametersAcceptorSelector::combineAcceptors($methodReflection->getVariants())->getNativeReturnType());
}
return $shortCircuit($this->methodCallReturnTypeHelper->methodCallReturnType($scope, $offsetAccessibleType, 'offsetGet', $offsetGetCall) ?? new ErrorType());
}
return $shortCircuit($offsetAccessibleType->getOffsetValueType(($nativeTypesPromoted ? $dimResult->getNativeType() : $dimResult->getType())));
},
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted),
);
// the classes in the type of the value at the offset
return $result->withDependencies(Dependencies::merge(
$varResult->getDependencies(),
$dimResult->getDependencies(),
Dependencies::create($beforeScope->getFile(), [$result->getType()]),
));
}
private static function offsetRead(ArrayDimFetch $expr, ?ExpressionResult $dimResult, ExpressionContext $context): ?VariableFlow
{
if ($context->isUnsetTarget() || !$expr->var instanceof Expr\Variable || !is_string($expr->var->name)) {
return null;
}
$target = $context->getValueFlowTarget();
return VariableFlow::read($expr->var->name, $target !== null ? $target->getId() : null, offset: $dimResult !== null ? VariableWriteOffset::fromType($dimResult->getType()) : null);
}
}