1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use PhpParser\Node;
6: use PhpParser\Node\Expr;
7: use PhpParser\Node\Expr\FuncCall;
8: use PhpParser\Node\Expr\Instanceof_;
9: use PhpParser\Node\Expr\MethodCall;
10: use PhpParser\Node\Expr\PropertyFetch;
11: use PhpParser\Node\Expr\StaticCall;
12: use PhpParser\Node\Identifier;
13: use PhpParser\Node\Name;
14: use PHPStan\DependencyInjection\AutowiredService;
15: use PHPStan\DependencyInjection\Container;
16: use PHPStan\Node\Expr\AlwaysRememberedExpr;
17: use PHPStan\Node\Printer\ExprPrinter;
18: use PHPStan\Reflection\ReflectionProvider;
19: use PHPStan\TrinaryLogic;
20: use PHPStan\Turbo\ShadowedByTurboExtension;
21: use PHPStan\Type\ExtensionClassHelper;
22: use PHPStan\Type\FunctionTypeSpecifyingExtension;
23: use PHPStan\Type\MethodTypeSpecifyingExtension;
24: use PHPStan\Type\NullType;
25: use PHPStan\Type\StaticMethodTypeSpecifyingExtension;
26: use PHPStan\Type\StaticTypeFactory;
27: use PHPStan\Type\Type;
28: use PHPStan\Type\TypeCombinator;
29: use function array_merge;
30: use function is_array;
31:
32: #[AutowiredService(name: 'typeSpecifier', factory: '@typeSpecifierFactory::create')]
33: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/TypeSpecifier.cpp')]
34: final class TypeSpecifier
35: {
36:
37: private const CONTAINS_CALL_ATTRIBUTE_NAME = 'containsCall';
38:
39: /** @var MethodTypeSpecifyingExtension[][]|null */
40: private ?array $methodTypeSpecifyingExtensionsByClass = null;
41:
42: /** @var StaticMethodTypeSpecifyingExtension[][]|null */
43: private ?array $staticMethodTypeSpecifyingExtensionsByClass = null;
44:
45: /**
46: * @param FunctionTypeSpecifyingExtension[] $functionTypeSpecifyingExtensions
47: * @param MethodTypeSpecifyingExtension[] $methodTypeSpecifyingExtensions
48: * @param StaticMethodTypeSpecifyingExtension[] $staticMethodTypeSpecifyingExtensions
49: */
50: public function __construct(
51: private ExprPrinter $exprPrinter,
52: private ReflectionProvider $reflectionProvider,
53: private array $functionTypeSpecifyingExtensions,
54: private array $methodTypeSpecifyingExtensions,
55: private array $staticMethodTypeSpecifyingExtensions,
56: private bool $rememberPossiblyImpureFunctionValues,
57: private Container $container,
58: )
59: {
60: }
61:
62: /**
63: * @api
64: */
65: public function specifyTypesInCondition(
66: Scope $scope,
67: Expr $expr,
68: TypeSpecifierContext $context,
69: ): SpecifiedTypes
70: {
71: if ($expr instanceof Expr\CallLike && $expr->isPartialFunctionApplication()) {
72: return (new SpecifiedTypes([], []))->setRootExpr($expr);
73: }
74:
75: $exprHandler = ExprHandlerRegistry::resolve($expr, $this->container);
76: if ($exprHandler !== null) {
77: if ($scope instanceof MutatingScope) {
78: return $scope->specifyTypesOfNewWorldHandlerNode($expr, $context);
79: }
80: }
81:
82: return $this->specifyDefaultTypes($scope, $expr, $context);
83: }
84:
85: /**
86: * Fallback used by ExprHandler::specifyTypes implementations that have no
87: * Expr-specific narrowing: applies the default truthy/falsey narrowing, or
88: * returns empty SpecifiedTypes in a null context.
89: *
90: * @internal
91: */
92: public function specifyDefaultTypes(Scope $scope, Expr $expr, TypeSpecifierContext $context): SpecifiedTypes
93: {
94: if (!$context->null()) {
95: return $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
96: }
97:
98: return (new SpecifiedTypes([], []))->setRootExpr($expr);
99: }
100:
101: /** @internal */
102: public function handleDefaultTruthyOrFalseyContext(TypeSpecifierContext $context, Expr $expr, Scope $scope): SpecifiedTypes
103: {
104: if ($context->null()) {
105: return (new SpecifiedTypes([], []))->setRootExpr($expr);
106: }
107: if (!$context->truthy()) {
108: $type = StaticTypeFactory::truthy();
109: return $this->create($expr, $type, TypeSpecifierContext::createFalse(), $scope)->setRootExpr($expr);
110: } elseif (!$context->falsey()) {
111: $type = StaticTypeFactory::falsey();
112: return $this->create($expr, $type, TypeSpecifierContext::createFalse(), $scope)->setRootExpr($expr);
113: }
114:
115: return (new SpecifiedTypes([], []))->setRootExpr($expr);
116: }
117:
118: /**
119: * @api
120: */
121: public function create(
122: Expr $expr,
123: Type $type,
124: TypeSpecifierContext $context,
125: Scope $scope,
126: ): SpecifiedTypes
127: {
128: if ($expr instanceof Instanceof_ || $expr instanceof Expr\List_) {
129: return (new SpecifiedTypes([], []))->setRootExpr($expr);
130: }
131:
132: $specifiedExprs = [];
133: if ($expr instanceof Expr\Assign) {
134: $specifiedExprs[] = $expr->var;
135: $specifiedExprs[] = $expr->expr;
136:
137: while ($expr->expr instanceof Expr\Assign) {
138: $specifiedExprs[] = $expr->expr->var;
139: $expr = $expr->expr;
140: }
141: } elseif ($expr instanceof Expr\AssignOp\Coalesce) {
142: $specifiedExprs[] = $expr->var;
143: } else {
144: $specifiedExprs[] = $expr;
145: }
146:
147: $types = null;
148:
149: foreach ($specifiedExprs as $specifiedExpr) {
150: $newTypes = $this->createForExpr($specifiedExpr, $type, $context, $scope);
151:
152: if ($types === null) {
153: $types = $newTypes;
154: } else {
155: $types = $types->unionWith($newTypes);
156: }
157: }
158:
159: return $types;
160: }
161:
162: private function createForExpr(
163: Expr $expr,
164: Type $type,
165: TypeSpecifierContext $context,
166: Scope $scope,
167: ): SpecifiedTypes
168: {
169: // the null-containment probe only feeds the nullsafe-shortcircuit unwrap
170: // and createNullsafeTypes() - both are no-ops for a bare variable, so the
171: // probe (and its type ask) is skipped for one
172: if (!$expr instanceof Expr\Variable) {
173: if ($context->true()) {
174: $containsNull = !$type->isNull()->no() && !$scope->getType($expr)->isNull()->no();
175: } elseif ($context->false()) {
176: $containsNull = !TypeCombinator::containsNull($type) && !$scope->getType($expr)->isNull()->no();
177: }
178: }
179:
180: $originalExpr = $expr;
181: $exprType = $type;
182: if (isset($containsNull) && !$containsNull) {
183: $expr = NullsafeOperatorHelper::getNullsafeShortcircuitedExpr($expr);
184: }
185:
186: if (
187: !$context->null()
188: && $expr instanceof Expr\BinaryOp\Coalesce
189: ) {
190: if (
191: ($context->true() && $type->isSuperTypeOf($scope->getType($expr->right))->no())
192: || ($context->false() && $type->isSuperTypeOf($scope->getType($expr->right))->yes())
193: ) {
194: $expr = $expr->left;
195: // a null left side would make the coalesce the right side,
196: // which the type rules out, so the left side is not null either
197: $exprType = $context->true() ? TypeCombinator::removeNull($type) : TypeCombinator::addNull($type);
198: }
199: }
200:
201: if (
202: $expr instanceof FuncCall
203: && $expr->name instanceof Name
204: && !$this->reflectionProvider->hasFunction($expr->name, $scope)
205: ) {
206: return new SpecifiedTypes([], []);
207: }
208:
209: if (!($expr instanceof AlwaysRememberedExpr) && $this->expressionContainsNonPureCall($expr, $scope)) {
210: if (isset($containsNull) && !$containsNull) {
211: return $this->createNullsafeTypes($originalExpr, $scope, $context, $type);
212: }
213:
214: return new SpecifiedTypes([], []);
215: }
216:
217: $sureTypes = [];
218: $sureNotTypes = [];
219: if ($context->false()) {
220: $exprString = $this->exprPrinter->printExpr($expr);
221: $sureNotTypes[$exprString] = [$expr, $exprType];
222:
223: if ($expr !== $originalExpr) {
224: $originalExprString = $this->exprPrinter->printExpr($originalExpr);
225: $sureNotTypes[$originalExprString] = [$originalExpr, $type];
226: }
227: } elseif ($context->true()) {
228: $exprString = $this->exprPrinter->printExpr($expr);
229: $sureTypes[$exprString] = [$expr, $exprType];
230:
231: if ($expr !== $originalExpr) {
232: $originalExprString = $this->exprPrinter->printExpr($originalExpr);
233: $sureTypes[$originalExprString] = [$originalExpr, $type];
234: }
235: }
236:
237: $types = new SpecifiedTypes($sureTypes, $sureNotTypes);
238: if (isset($containsNull) && !$containsNull) {
239: return $this->createNullsafeTypes($originalExpr, $scope, $context, $type)->unionWith($types);
240: }
241:
242: return $types;
243: }
244:
245: private function expressionContainsNonPureCall(Expr $expr, Scope $scope): bool
246: {
247: // The answer for an expression without any call in it cannot change between
248: // scopes, and most specified expressions (plain variables, property fetches,
249: // constant fetches) are of that shape, so it's remembered on the node itself.
250: if ($expr->getAttribute(self::CONTAINS_CALL_ATTRIBUTE_NAME) === false) {
251: return false;
252: }
253:
254: $containsCall = false;
255: $containsNonPureCall = $this->findNonPureCall($expr, $scope, $containsCall);
256: if (!$containsCall) {
257: $expr->setAttribute(self::CONTAINS_CALL_ATTRIBUTE_NAME, false);
258: }
259:
260: return $containsNonPureCall;
261: }
262:
263: /**
264: * Depth-first pre-order search for a call that isn't known to be pure, replacing a
265: * NodeFinder::findFirst() call - this runs for every expression being specified,
266: * so the traverser/visitor machinery overhead was significant.
267: *
268: * $containsCall is set when the sub-tree contains a call of any kind.
269: */
270: private function findNonPureCall(Node $node, Scope $scope, bool &$containsCall): bool
271: {
272: if ($node instanceof Expr\CallLike) {
273: $containsCall = true;
274:
275: if ($this->callIsNotPure($node, $scope)) {
276: return true;
277: }
278: }
279:
280: foreach ($node->getSubNodeNames() as $subNodeName) {
281: $subNode = $node->$subNodeName;
282: if ($subNode instanceof Node) {
283: if ($this->findNonPureCall($subNode, $scope, $containsCall)) {
284: return true;
285: }
286: } elseif (is_array($subNode)) {
287: foreach ($subNode as $subNodeItem) {
288: if (
289: $subNodeItem instanceof Node
290: && $this->findNonPureCall($subNodeItem, $scope, $containsCall)
291: ) {
292: return true;
293: }
294: }
295: }
296: }
297:
298: return false;
299: }
300:
301: private function callIsNotPure(Expr\CallLike $call, Scope $scope): bool
302: {
303: if ($call instanceof FuncCall) {
304: if ($call->name instanceof Name) {
305: if (!$this->reflectionProvider->hasFunction($call->name, $scope)) {
306: return false;
307: }
308:
309: return $this->isNotPure($this->reflectionProvider->getFunction($call->name, $scope)->hasSideEffects());
310: }
311:
312: $nameType = $scope->getType($call->name);
313: if ($nameType->isCallable()->yes()) {
314: $isPure = null;
315: foreach ($nameType->getCallableParametersAcceptors($scope) as $variant) {
316: $variantIsPure = $variant->isPure();
317: $isPure = $isPure === null ? $variantIsPure : $isPure->and($variantIsPure);
318: }
319: if ($isPure !== null) {
320: return $this->isNotPure($isPure->negate());
321: }
322: }
323:
324: return false;
325: }
326:
327: if ($call instanceof MethodCall) {
328: if (!$call->name instanceof Identifier) {
329: return true;
330: }
331:
332: $methodReflection = $scope->getMethodReflection($scope->getType($call->var), $call->name->name);
333: if ($methodReflection === null) {
334: return true;
335: }
336:
337: return $this->isNotPure($methodReflection->hasSideEffects());
338: }
339:
340: if ($call instanceof StaticCall) {
341: if (!$call->name instanceof Identifier) {
342: return true;
343: }
344:
345: if ($call->class instanceof Name) {
346: $calledOnType = $scope->resolveTypeByName($call->class);
347: } else {
348: $calledOnType = $scope->getType($call->class);
349: }
350:
351: $methodReflection = $scope->getMethodReflection($calledOnType, $call->name->name);
352: if ($methodReflection === null) {
353: return true;
354: }
355:
356: return $this->isNotPure($methodReflection->hasSideEffects());
357: }
358:
359: return false;
360: }
361:
362: private function isNotPure(TrinaryLogic $hasSideEffects): bool
363: {
364: if ($hasSideEffects->yes()) {
365: return true;
366: }
367:
368: return !$this->rememberPossiblyImpureFunctionValues && !$hasSideEffects->no();
369: }
370:
371: private function createNullsafeTypes(Expr $expr, Scope $scope, TypeSpecifierContext $context, ?Type $type): SpecifiedTypes
372: {
373: if ($expr instanceof Expr\NullsafePropertyFetch) {
374: if ($type !== null) {
375: $propertyFetchTypes = $this->create(new PropertyFetch($expr->var, $expr->name), $type, $context, $scope);
376: } else {
377: $propertyFetchTypes = $this->create(new PropertyFetch($expr->var, $expr->name), new NullType(), TypeSpecifierContext::createFalse(), $scope);
378: }
379:
380: return $propertyFetchTypes->unionWith(
381: $this->create($expr->var, new NullType(), TypeSpecifierContext::createFalse(), $scope),
382: );
383: }
384:
385: if ($expr instanceof Expr\NullsafeMethodCall) {
386: if ($type !== null) {
387: $methodCallTypes = $this->create(new MethodCall($expr->var, $expr->name, $expr->args), $type, $context, $scope);
388: } else {
389: $methodCallTypes = $this->create(new MethodCall($expr->var, $expr->name, $expr->args), new NullType(), TypeSpecifierContext::createFalse(), $scope);
390: }
391:
392: return $methodCallTypes->unionWith(
393: $this->create($expr->var, new NullType(), TypeSpecifierContext::createFalse(), $scope),
394: );
395: }
396:
397: if ($expr instanceof Expr\PropertyFetch) {
398: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
399: }
400:
401: if ($expr instanceof Expr\MethodCall) {
402: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
403: }
404:
405: if ($expr instanceof Expr\ArrayDimFetch) {
406: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
407: }
408:
409: if ($expr instanceof Expr\StaticPropertyFetch && $expr->class instanceof Expr) {
410: return $this->createNullsafeTypes($expr->class, $scope, $context, null);
411: }
412:
413: if ($expr instanceof Expr\StaticCall && $expr->class instanceof Expr) {
414: return $this->createNullsafeTypes($expr->class, $scope, $context, null);
415: }
416:
417: return new SpecifiedTypes([], []);
418: }
419:
420: /**
421: * @return FunctionTypeSpecifyingExtension[]
422: *
423: * @internal
424: */
425: public function getFunctionTypeSpecifyingExtensions(): array
426: {
427: return $this->functionTypeSpecifyingExtensions;
428: }
429:
430: /**
431: * @return MethodTypeSpecifyingExtension[]
432: *
433: * @internal
434: */
435: public function getMethodTypeSpecifyingExtensionsForClass(string $className): array
436: {
437: if ($this->methodTypeSpecifyingExtensionsByClass === null) {
438: $byClass = [];
439: foreach ($this->methodTypeSpecifyingExtensions as $extension) {
440: $byClass[$extension->getClass()][] = $extension;
441: }
442:
443: $this->methodTypeSpecifyingExtensionsByClass = $byClass;
444: }
445: return $this->getTypeSpecifyingExtensionsForType($this->methodTypeSpecifyingExtensionsByClass, $className);
446: }
447:
448: /**
449: * @return StaticMethodTypeSpecifyingExtension[]
450: *
451: * @internal
452: */
453: public function getStaticMethodTypeSpecifyingExtensionsForClass(string $className): array
454: {
455: if ($this->staticMethodTypeSpecifyingExtensionsByClass === null) {
456: $byClass = [];
457: foreach ($this->staticMethodTypeSpecifyingExtensions as $extension) {
458: $byClass[$extension->getClass()][] = $extension;
459: }
460:
461: $this->staticMethodTypeSpecifyingExtensionsByClass = $byClass;
462: }
463: return $this->getTypeSpecifyingExtensionsForType($this->staticMethodTypeSpecifyingExtensionsByClass, $className);
464: }
465:
466: /**
467: * @param MethodTypeSpecifyingExtension[][]|StaticMethodTypeSpecifyingExtension[][] $extensions
468: * @return mixed[]
469: */
470: private function getTypeSpecifyingExtensionsForType(array $extensions, string $className): array
471: {
472: $extensionsForClass = [[]];
473: $extensionClassNames = ExtensionClassHelper::getExtensionClassNames($this->reflectionProvider, $className);
474: foreach ($extensionClassNames as $extensionClassName) {
475: if (!isset($extensions[$extensionClassName])) {
476: continue;
477: }
478:
479: $extensionsForClass[] = $extensions[$extensionClassName];
480: }
481:
482: return array_merge(...$extensionsForClass);
483: }
484:
485: }
486: