Repository navigation
Expand file tree
/
Copy pathMethodCallHandler.php
More file actions
382 lines (349 loc) · 15.3 KB
/
Copy pathMethodCallHandler.php
File metadata and controls
382 lines (349 loc) · 15.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
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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\CalledMethodProcessor;
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\EarlyTerminatingCallHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodCallReturnTypeHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodThrowPointHelper;
use PHPStan\Analyser\ExprHandler\Helper\NullsafeShortCircuitingHelper;
use PHPStan\Analyser\ImpurePoint;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\PossiblyImpureCallExpr;
use PHPStan\Node\InvalidateExprNode;
use PHPStan\Reflection\Callables\SimpleImpurePoint;
use PHPStan\Reflection\ExtendedParametersAcceptor;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use function array_map;
use function array_merge;
use function count;
use function sprintf;
use function strtolower;
/**
* @implements ExprHandler<MethodCall>
*/
#[AutowiredService]
final class MethodCallHandler implements ExprHandler
{
public function __construct(
private CalledMethodProcessor $calledMethodProcessor,
private EarlyTerminatingCallHelper $earlyTerminatingCallHelper,
private MethodCallReturnTypeHelper $methodCallReturnTypeHelper,
private MethodThrowPointHelper $methodThrowPointHelper,
private ReflectionProvider $reflectionProvider,
#[AutowiredParameter]
private bool $rememberPossiblyImpureFunctionValues,
private ExpressionResultFactory $expressionResultFactory,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof MethodCall && !$expr->isFirstClassCallable();
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$originalScope = $scope;
if (
($expr->var instanceof Expr\Closure || $expr->var instanceof Expr\ArrowFunction)
&& $expr->name instanceof Identifier
&& strtolower($expr->name->name) === 'call'
&& isset($expr->getArgs()[0])
) {
$closureCallScope = $scope->enterClosureCall(
$scope->getType($expr->getArgs()[0]->value),
$scope->getNativeType($expr->getArgs()[0]->value),
);
}
$varResult = $nodeScopeResolver->processExprNode($stmt, $expr->var, $closureCallScope ?? $scope, $storage, $nodeCallback, $context->enterDeep());
$hasYield = $varResult->hasYield();
$throwPoints = $varResult->getThrowPoints();
$impurePoints = $varResult->getImpurePoints();
$isAlwaysTerminating = $varResult->isAlwaysTerminating();
$scope = $varResult->getScope();
if (isset($closureCallScope)) {
$scope = $scope->restoreOriginalScopeAfterClosureBind($originalScope);
}
$parametersAcceptor = null;
$variants = [];
$namedArgumentsVariants = null;
$methodReflection = null;
$calledOnType = $varResult->getType();
if ($expr->name instanceof Identifier) {
$methodName = $expr->name->name;
$methodReflection = $scope->getMethodReflection($calledOnType, $methodName);
if ($methodReflection !== null) {
$variants = $methodReflection->getVariants();
$namedArgumentsVariants = $methodReflection->getNamedArgumentsVariants();
// A structural acceptor (names/positions/variadic) drives argument
// normalization, the impure point and the throw point - generics are
// resolved type-driven by processArgs() into $resolvedParametersAcceptor.
$parametersAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $variants, $namedArgumentsVariants);
}
} else {
$methodNameResult = $nodeScopeResolver->processExprNode($stmt, $expr->name, $scope, $storage, $nodeCallback, $context->enterDeep());
$throwPoints = array_merge($throwPoints, $methodNameResult->getThrowPoints());
$scope = $methodNameResult->getScope();
}
if ($methodReflection !== null) {
$impurePoint = SimpleImpurePoint::createFromVariant($methodReflection, $parametersAcceptor, $scope, $expr->getArgs());
if ($impurePoint !== null) {
$impurePoints[] = new ImpurePoint($scope, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain());
}
} else {
$impurePoints[] = new ImpurePoint(
$scope,
$expr,
'methodCall',
'call to unknown method',
false,
);
}
$normalizedExpr = $expr;
if ($parametersAcceptor !== null) {
$normalizedExpr = ArgumentsNormalizer::reorderMethodArguments($parametersAcceptor, $expr) ?? $expr;
$returnType = $parametersAcceptor->getReturnType();
$isAlwaysTerminating = $isAlwaysTerminating || ($returnType instanceof NeverType && $returnType->isExplicit());
}
$argsResult = $nodeScopeResolver->processArgs(
$stmt,
$methodReflection,
$methodReflection !== null ? $scope->getNakedMethod($calledOnType, $methodReflection->getName()) : null,
$variants,
$namedArgumentsVariants,
$normalizedExpr,
$scope,
$storage,
$nodeCallback,
$context,
);
$resolvedParametersAcceptor = $argsResult->getResolvedParametersAcceptor();
$scope = $argsResult->getScope();
if ($methodReflection !== null) {
// The early structural check above only sees the unresolved acceptor
// return type; a conditional-return never (e.g. `($x is Foo ? never :
// string)`) only resolves to never once the actual argument types are
// folded in by the type-driven resolved acceptor.
if ($resolvedParametersAcceptor !== null) {
$resolvedReturnType = $resolvedParametersAcceptor->getReturnType();
$isAlwaysTerminating = $isAlwaysTerminating || ($resolvedReturnType instanceof NeverType && $resolvedReturnType->isExplicit());
}
$methodThrowPoint = $this->methodThrowPointHelper->getThrowPoint($methodReflection, $parametersAcceptor, $normalizedExpr, $scope, $context);
if ($methodThrowPoint !== null) {
$throwPoints[] = $methodThrowPoint;
}
if ($methodReflection->getName() === '__construct' || $methodReflection->hasSideEffects()->yes()) {
$nodeScopeResolver->callNodeCallback($nodeCallback, new InvalidateExprNode($normalizedExpr->var), $scope, $storage);
$scope = $scope->invalidateExpression($normalizedExpr->var, true, $methodReflection->getDeclaringClass());
$scope = $nodeScopeResolver->widenNeverTypeArguments($scope, $normalizedExpr->var);
} elseif ($this->rememberPossiblyImpureFunctionValues && $methodReflection->hasSideEffects()->maybe() && !$methodReflection->getDeclaringClass()->isBuiltin()) {
// the remembered call value and the @phpstan-self-out type are
// generic-sensitive: resolve them from the type-driven acceptor
// processArgs() selected (generics resolved against the actual arg
// types), falling back to the structural acceptor for dynamic callees.
$acceptorForGenerics = $resolvedParametersAcceptor ?? $parametersAcceptor;
$scope = $scope->assignExpression(
new PossiblyImpureCallExpr($normalizedExpr, $normalizedExpr->var, sprintf('%s::%s()', $methodReflection->getDeclaringClass()->getDisplayName(), $methodReflection->getName())),
$acceptorForGenerics->getReturnType(),
new MixedType(),
);
}
if (!$methodReflection->isStatic()) {
$selfOutType = $methodReflection->getSelfOutType();
if ($selfOutType !== null) {
$acceptorForGenerics = $resolvedParametersAcceptor ?? $parametersAcceptor;
$scope = $scope->assignExpression(
$normalizedExpr->var,
TemplateTypeHelper::resolveTemplateTypes(
$selfOutType,
$acceptorForGenerics->getResolvedTemplateTypeMap(),
$acceptorForGenerics instanceof ExtendedParametersAcceptor ? $acceptorForGenerics->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
TemplateTypeVariance::createCovariant(),
),
$scope->getNativeType($normalizedExpr->var),
);
}
}
} else {
$nodeScopeResolver->callNodeCallback($nodeCallback, new InvalidateExprNode($normalizedExpr->var), $scope, $storage);
$scope = $scope->invalidateExpression($normalizedExpr->var, true);
$scope = $nodeScopeResolver->widenNeverTypeArguments($scope, $normalizedExpr->var);
$throwPoints[] = InternalThrowPoint::createImplicit($scope, $expr);
}
if (
$methodReflection === null
|| (!$methodReflection->getDeclaringClass()->isBuiltin() && !$methodReflection->hasSideEffects()->no())
) {
$scope = $scope->invalidateVolatileExpressions();
}
$hasYield = $hasYield || $argsResult->hasYield();
$throwPoints = array_merge($throwPoints, $argsResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $argsResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || $argsResult->isAlwaysTerminating();
$result = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
impurePoints: $impurePoints,
containsNullsafe: $varResult->containsNullsafe(),
);
$calledOnType = $originalScope->getType($expr->var);
if (!$expr->name instanceof Identifier) {
return $result;
}
$methodName = $expr->name->name;
$methodReflection = $originalScope->getMethodReflection($calledOnType, $methodName);
if ($methodReflection === null) {
return $result;
}
if (
$scope->isInClass()
&& $scope->getClassReflection()->getName() === $methodReflection->getDeclaringClass()->getName()
&& ($scope->getFunctionName() !== null && strtolower($scope->getFunctionName()) === '__construct')
&& TypeUtils::findThisType($calledOnType) !== null
) {
$calledMethodScope = $this->calledMethodProcessor->processCalledMethod($nodeScopeResolver, $methodReflection);
if ($calledMethodScope !== null) {
$scope = $scope->mergeInitializedProperties($calledMethodScope);
return $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
hasYield: $result->hasYield(),
isAlwaysTerminating: $result->isAlwaysTerminating(),
throwPoints: $result->getThrowPoints(),
impurePoints: $result->getImpurePoints(),
);
}
}
return $result;
}
public function resolveType(MutatingScope $scope, Expr $expr): Type
{
if (
$expr->name instanceof Identifier
&& $this->earlyTerminatingCallHelper->isEarlyTerminatingMethodCall($expr->name->name, $scope->getType($expr->var))
) {
return new NeverType(true);
}
if ($expr->name instanceof Identifier) {
if ($scope->nativeTypesPromoted) {
$methodReflection = $scope->getMethodReflection(
$scope->getNativeType($expr->var),
$expr->name->name,
);
if ($methodReflection === null) {
$returnType = new ErrorType();
} else {
$returnType = ParametersAcceptorSelector::combineAcceptors($methodReflection->getVariants())->getNativeReturnType();
}
return NullsafeShortCircuitingHelper::getType($scope, $expr->var, $returnType);
}
$returnType = $this->methodCallReturnTypeHelper->methodCallReturnType(
$scope,
$scope->getType($expr->var),
$expr->name->name,
$expr,
);
if ($returnType === null) {
$returnType = new ErrorType();
}
return NullsafeShortCircuitingHelper::getType($scope, $expr->var, $returnType);
}
$nameType = $scope->getType($expr->name);
if (count($nameType->getConstantStrings()) > 0) {
return TypeCombinator::union(
...array_map(static fn ($constantString) => $constantString->getValue() === '' ? new ErrorType() : $scope
->filterByTruthyValue(new Identical($expr->name, new String_($constantString->getValue())))
->getType(new MethodCall($expr->var, new Identifier($constantString->getValue()), $expr->args)), $nameType->getConstantStrings()),
);
}
return new MixedType();
}
public function specifyTypes(TypeSpecifier $typeSpecifier, Scope $scope, Expr $expr, TypeSpecifierContext $context): SpecifiedTypes
{
if (!$expr->name instanceof Identifier) {
return $typeSpecifier->specifyDefaultTypes($scope, $expr, $context);
}
$methodCalledOnType = $scope->getType($expr->var);
$methodReflection = $scope->getMethodReflection($methodCalledOnType, $expr->name->name);
if ($methodReflection !== null) {
// lazy create parametersAcceptor, as creation can be expensive
$parametersAcceptor = null;
$normalizedExpr = $expr;
$args = $expr->getArgs();
if (count($args) > 0) {
$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs($scope, $args, $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
$normalizedExpr = ArgumentsNormalizer::reorderMethodArguments($parametersAcceptor, $expr) ?? $expr;
}
$referencedClasses = $methodCalledOnType->getObjectClassNames();
if (
count($referencedClasses) === 1
&& $this->reflectionProvider->hasClass($referencedClasses[0])
) {
$methodClassReflection = $this->reflectionProvider->getClass($referencedClasses[0]);
foreach ($typeSpecifier->getMethodTypeSpecifyingExtensionsForClass($methodClassReflection->getName()) as $extension) {
if (!$extension->isMethodSupported($methodReflection, $normalizedExpr, $context)) {
continue;
}
return $extension->specifyTypes($methodReflection, $normalizedExpr, $scope, $context);
}
}
if (count($args) > 0) {
$specifiedTypes = $typeSpecifier->specifyTypesFromConditionalReturnType($context, $expr, $parametersAcceptor, $scope);
if ($specifiedTypes !== null) {
return $specifiedTypes;
}
}
$assertions = $methodReflection->getAsserts();
if ($assertions->getAll() !== []) {
$parametersAcceptor ??= ParametersAcceptorSelector::selectFromArgs($scope, $args, $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
$asserts = $assertions->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
$type,
$parametersAcceptor->getResolvedTemplateTypeMap(),
$parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
TemplateTypeVariance::createInvariant(),
));
$specifiedTypes = $typeSpecifier->specifyTypesFromAsserts($context, $expr, $asserts, $parametersAcceptor, $scope);
if ($specifiedTypes !== null) {
return $specifiedTypes
->unionWith($typeSpecifier->handleDefaultTruthyOrFalseyContext($context, $expr, $scope))
->setRootExpr($specifiedTypes->getRootExpr());
}
}
}
return $typeSpecifier->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
}
}