Repository navigation
Expand file tree
/
Copy pathStaticPropertyFetchHandler.php
More file actions
274 lines (250 loc) · 11 KB
/
Copy pathStaticPropertyFetchHandler.php
File metadata and controls
274 lines (250 loc) · 11 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\VarLikeIdentifier;
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\ImpurePoint;
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\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Properties\FoundPropertyReflection;
use PHPStan\Rules\Properties\PropertyReflectionFinder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_map;
use function array_merge;
use function count;
/**
* @implements ExprHandler<StaticPropertyFetch>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/StaticPropertyFetchHandler.cpp')]
final class StaticPropertyFetchHandler implements ExprHandler
{
public function __construct(
private PropertyReflectionFinder $propertyReflectionFinder,
private ExpressionResultFactory $expressionResultFactory,
private DefaultNarrowingHelper $defaultNarrowingHelper,
private ReflectionProvider $reflectionProvider,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof StaticPropertyFetch;
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$classResult = null;
if ($expr->class instanceof Expr) {
$classResult = $nodeScopeResolver->processExprNode($stmt, $expr->class, $scope, $storage, $nodeCallback, $context->enterDeep());
$scope = $classResult->getScope();
}
$nameResult = null;
if (!$expr->name instanceof VarLikeIdentifier) {
$nameResult = $nodeScopeResolver->processExprNode($stmt, $expr->name, $scope, $storage, $nodeCallback, $context->enterDeep());
}
return $this->composeResult($expr, $classResult, $nameResult, $beforeScope);
}
/**
* Builds the static property read's ExpressionResult from the
* already-walked class and name results - the fetch is not re-walked.
* 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(StaticPropertyFetch $expr, ?ExpressionResult $classResult, ?ExpressionResult $nameResult, MutatingScope $beforeScope): ExpressionResult
{
$scope = $beforeScope;
$hasYield = false;
$throwPoints = [];
$impurePoints = [
new ImpurePoint(
$scope,
$expr,
'staticPropertyAccess',
'static property access',
true,
),
];
$isAlwaysTerminating = false;
if ($classResult !== null) {
$hasYield = $classResult->hasYield();
$throwPoints = $classResult->getThrowPoints();
$impurePoints = $classResult->getImpurePoints();
$isAlwaysTerminating = $classResult->isAlwaysTerminating();
$scope = $classResult->getScope();
}
$mayShortCircuit = false;
if ($nameResult !== null) {
// `$a?->b::$$name` is a link in a nullsafe chain and may never run - see
// MethodCallHandler::processExpr(). Only the dynamic name is skipped with
// it, so a plain `::$name` never has to resolve the class expression type.
$mayShortCircuit = $classResult !== null
&& $classResult->containsNullsafe()
&& TypeCombinator::containsNull($classResult->getType());
$hasYield = $hasYield || $nameResult->hasYield();
$throwPoints = array_merge($throwPoints, $nameResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $nameResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || (!$mayShortCircuit && $nameResult->isAlwaysTerminating());
$scope = $nameResult->getScope();
if ($mayShortCircuit) {
// the dynamic name expression was not evaluated in the
// short-circuited world
$scope = $scope->mergeWith($classResult->getScope());
}
}
$result = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence(
$classResult !== null ? $classResult->getVariableFlow() : null,
$nameResult !== null && $mayShortCircuit
? VariableFlow::choice($nameResult->getVariableFlow(), null)
: ($nameResult !== null ? $nameResult->getVariableFlow() : null),
VariableFlowBuilder::throws($expr, $throwPoints),
),
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
impurePoints: $impurePoints,
containsNullsafe: $classResult !== null && $classResult->containsNullsafe(),
issetabilityDescriptor: IssetabilityDescriptor::property($classResult, fn (MutatingScope $s): ?FoundPropertyReflection => $this->propertyReflectionFinder->findPropertyReflectionFromNode($expr, $s), $expr),
typeCallback: function (bool $nativeTypesPromoted) use ($expr, $classResult, $nameResult, $beforeScope): Type {
$classType = $classResult !== null
? ($nativeTypesPromoted ? $classResult->getNativeType() : $classResult->getType())
: null;
$shortCircuit = static fn (Type $type): Type => $classResult !== null && $classResult->containsNullsafe() && $classType !== null && TypeCombinator::containsNull($classType)
? TypeCombinator::addNull($type)
: $type;
// the property's class/visibility/assign context is lexical, so it
// comes from beforeScope; the scope-dependent class-expression type
// is read from the operand result above, and the native-vs-phpdoc
// distinction comes from that type and the reflection accessor below.
$reflectionScope = $beforeScope;
if ($expr->class instanceof Name) {
$staticPropertyFetchedOnType = $reflectionScope->resolveTypeByName($expr->class);
} else {
// every caller walks a non-Name class and passes its result
if ($classType === null) {
throw new ShouldNotHappenException();
}
$staticPropertyFetchedOnType = TypeCombinator::removeNull($classType)->getObjectTypeOrClassStringObjectType();
}
$resolveProperty = function (string $propertyName) use ($nativeTypesPromoted, $reflectionScope, $staticPropertyFetchedOnType, $classType, $classResult, $expr): Type {
if ($nativeTypesPromoted) {
// unlike getStaticPropertyReflection(), do not pick only the union
// members that have the property - a fetch on e.g. a null member
// does not produce the property's native type
if ($classType !== null && !$classResult->containsNullsafe() && TypeCombinator::containsNull($classType)) {
return new ErrorType();
}
if (!$staticPropertyFetchedOnType->hasStaticProperty($propertyName)->yes()) {
return new ErrorType();
}
$propertyReflection = $reflectionScope->getStaticPropertyReflection($staticPropertyFetchedOnType, $propertyName);
if ($propertyReflection === null) {
return new ErrorType();
}
if (!$propertyReflection->hasNativeType()) {
return new MixedType();
}
return $propertyReflection->getNativeType();
}
return $this->propertyFetchType($reflectionScope, $staticPropertyFetchedOnType, $propertyName, $expr) ?? new ErrorType();
};
if ($expr->name instanceof VarLikeIdentifier) {
return $shortCircuit($resolveProperty($expr->name->toString()));
}
// dynamic static property fetch Foo::${$name}: resolve each possible
// name from beforeScope. The asking scope is not narrowed per name,
// so such fetches can be less precise.
// every caller walks a non-VarLikeIdentifier name and passes its result
if ($nameResult === null) {
throw new ShouldNotHappenException();
}
$nameType = $nativeTypesPromoted ? $nameResult->getNativeType() : $nameResult->getType();
if (count($nameType->getConstantStrings()) > 0) {
return TypeCombinator::union(
...array_map(static function ($constantString) use ($resolveProperty): Type {
if ($constantString->getValue() === '') {
return new ErrorType();
}
return $resolveProperty($constantString->getValue());
}, $nameType->getConstantStrings()),
);
}
return new MixedType();
},
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context),
);
return $result->withDependencies(Dependencies::merge(
$classResult !== null ? $classResult->getDependencies() : null,
$nameResult !== null ? $nameResult->getDependencies() : null,
$this->getDependencies($beforeScope, $expr, $classResult, $result),
));
}
/**
* The class the property is fetched from, the class declaring it, and the classes in its type.
*/
private function getDependencies(MutatingScope $scope, StaticPropertyFetch $expr, ?ExpressionResult $classResult, ExpressionResult $result): ?Dependencies
{
$types = [$result->getType()];
$classNames = [];
if ($classResult !== null) {
$types[] = $classResult->getType();
} elseif ($expr->class instanceof Name) {
$classNames[] = $scope->resolveName($expr->class);
}
if ($expr->name instanceof VarLikeIdentifier) {
$propertyName = $expr->name->toString();
if ($classResult !== null) {
$propertyReflection = $scope->getStaticPropertyReflection($classResult->getType(), $propertyName);
if ($propertyReflection !== null) {
$classNames[] = $propertyReflection->getDeclaringClass()->getName();
}
} elseif ($expr->class instanceof Name) {
$className = $scope->resolveName($expr->class);
if ($this->reflectionProvider->hasClass($className)) {
$propertyClassReflection = $this->reflectionProvider->getClass($className);
if ($propertyClassReflection->hasStaticProperty($propertyName)) {
$classNames[] = $propertyClassReflection->getStaticProperty($propertyName)->getDeclaringClass()->getName();
}
}
}
}
return Dependencies::create($scope->getFile(), $types, $classNames);
}
private function propertyFetchType(MutatingScope $scope, Type $fetchedOnType, string $propertyName, StaticPropertyFetch $propertyFetch): ?Type
{
$propertyReflection = $scope->getStaticPropertyReflection($fetchedOnType, $propertyName);
if ($propertyReflection === null) {
return null;
}
if ($scope->isInWriteExpressionAssign($propertyFetch)) {
return $propertyReflection->getWritableType();
}
return $propertyReflection->getReadableType();
}
}