1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use Countable;
6: use PhpParser\Node;
7: use PhpParser\Node\Expr;
8: use PhpParser\Node\Expr\ArrayDimFetch;
9: use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
10: use PhpParser\Node\Expr\BinaryOp\BooleanOr;
11: use PhpParser\Node\Expr\BinaryOp\LogicalAnd;
12: use PhpParser\Node\Expr\BinaryOp\LogicalOr;
13: use PhpParser\Node\Expr\ClassConstFetch;
14: use PhpParser\Node\Expr\ConstFetch;
15: use PhpParser\Node\Expr\FuncCall;
16: use PhpParser\Node\Expr\Instanceof_;
17: use PhpParser\Node\Expr\MethodCall;
18: use PhpParser\Node\Expr\PropertyFetch;
19: use PhpParser\Node\Expr\StaticCall;
20: use PhpParser\Node\Expr\StaticPropertyFetch;
21: use PhpParser\Node\Name;
22: use PHPStan\DependencyInjection\AutowiredService;
23: use PHPStan\Node\Expr\AlwaysRememberedExpr;
24: use PHPStan\Node\Expr\TypeExpr;
25: use PHPStan\Node\IssetExpr;
26: use PHPStan\Node\Printer\ExprPrinter;
27: use PHPStan\Php\PhpVersion;
28: use PHPStan\Reflection\Assertions;
29: use PHPStan\Reflection\ExtendedParametersAcceptor;
30: use PHPStan\Reflection\ParametersAcceptor;
31: use PHPStan\Reflection\ParametersAcceptorSelector;
32: use PHPStan\Reflection\ReflectionProvider;
33: use PHPStan\Reflection\ResolvedFunctionVariant;
34: use PHPStan\Rules\Arrays\AllowedArrayKeysTypes;
35: use PHPStan\ShouldNotHappenException;
36: use PHPStan\TrinaryLogic;
37: use PHPStan\Type\Accessory\AccessoryArrayListType;
38: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
39: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
40: use PHPStan\Type\Accessory\HasOffsetType;
41: use PHPStan\Type\Accessory\HasPropertyType;
42: use PHPStan\Type\Accessory\NonEmptyArrayType;
43: use PHPStan\Type\ArrayType;
44: use PHPStan\Type\BooleanType;
45: use PHPStan\Type\ConditionalTypeForParameter;
46: use PHPStan\Type\Constant\ConstantArrayType;
47: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
48: use PHPStan\Type\Constant\ConstantBooleanType;
49: use PHPStan\Type\Constant\ConstantFloatType;
50: use PHPStan\Type\Constant\ConstantIntegerType;
51: use PHPStan\Type\Constant\ConstantStringType;
52: use PHPStan\Type\ConstantScalarType;
53: use PHPStan\Type\FloatType;
54: use PHPStan\Type\FunctionTypeSpecifyingExtension;
55: use PHPStan\Type\Generic\GenericClassStringType;
56: use PHPStan\Type\Generic\TemplateType;
57: use PHPStan\Type\Generic\TemplateTypeHelper;
58: use PHPStan\Type\Generic\TemplateTypeVariance;
59: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
60: use PHPStan\Type\IntegerRangeType;
61: use PHPStan\Type\IntegerType;
62: use PHPStan\Type\IntersectionType;
63: use PHPStan\Type\MethodTypeSpecifyingExtension;
64: use PHPStan\Type\MixedType;
65: use PHPStan\Type\NeverType;
66: use PHPStan\Type\NonexistentParentClassType;
67: use PHPStan\Type\NullType;
68: use PHPStan\Type\ObjectType;
69: use PHPStan\Type\ObjectWithoutClassType;
70: use PHPStan\Type\ResourceType;
71: use PHPStan\Type\StaticMethodTypeSpecifyingExtension;
72: use PHPStan\Type\StaticType;
73: use PHPStan\Type\StaticTypeFactory;
74: use PHPStan\Type\StringType;
75: use PHPStan\Type\Type;
76: use PHPStan\Type\TypeCombinator;
77: use PHPStan\Type\TypeTraverser;
78: use PHPStan\Type\UnionType;
79: use function array_key_exists;
80: use function array_map;
81: use function array_merge;
82: use function array_reverse;
83: use function array_shift;
84: use function count;
85: use function in_array;
86: use function is_string;
87: use function strtolower;
88: use function substr;
89: use const COUNT_NORMAL;
90:
91: #[AutowiredService(name: 'typeSpecifier', factory: '@typeSpecifierFactory::create')]
92: final class TypeSpecifier
93: {
94:
95: /** @var MethodTypeSpecifyingExtension[][]|null */
96: private ?array $methodTypeSpecifyingExtensionsByClass = null;
97:
98: /** @var StaticMethodTypeSpecifyingExtension[][]|null */
99: private ?array $staticMethodTypeSpecifyingExtensionsByClass = null;
100:
101: /**
102: * @param FunctionTypeSpecifyingExtension[] $functionTypeSpecifyingExtensions
103: * @param MethodTypeSpecifyingExtension[] $methodTypeSpecifyingExtensions
104: * @param StaticMethodTypeSpecifyingExtension[] $staticMethodTypeSpecifyingExtensions
105: */
106: public function __construct(
107: private ExprPrinter $exprPrinter,
108: private ReflectionProvider $reflectionProvider,
109: private PhpVersion $phpVersion,
110: private array $functionTypeSpecifyingExtensions,
111: private array $methodTypeSpecifyingExtensions,
112: private array $staticMethodTypeSpecifyingExtensions,
113: private bool $rememberPossiblyImpureFunctionValues,
114: )
115: {
116: foreach (array_merge($functionTypeSpecifyingExtensions, $methodTypeSpecifyingExtensions, $staticMethodTypeSpecifyingExtensions) as $extension) {
117: if (!($extension instanceof TypeSpecifierAwareExtension)) {
118: continue;
119: }
120:
121: $extension->setTypeSpecifier($this);
122: }
123: }
124:
125: /** @api */
126: public function specifyTypesInCondition(
127: Scope $scope,
128: Expr $expr,
129: TypeSpecifierContext $context,
130: ): SpecifiedTypes
131: {
132: if ($expr instanceof Expr\CallLike && $expr->isFirstClassCallable()) {
133: return (new SpecifiedTypes([], []))->setRootExpr($expr);
134: }
135:
136: if ($expr instanceof Instanceof_) {
137: $exprNode = $expr->expr;
138: if ($expr->class instanceof Name) {
139: $className = (string) $expr->class;
140: $lowercasedClassName = strtolower($className);
141: if ($lowercasedClassName === 'self' && $scope->isInClass()) {
142: $type = new ObjectType($scope->getClassReflection()->getName());
143: } elseif ($lowercasedClassName === 'static' && $scope->isInClass()) {
144: $type = new StaticType($scope->getClassReflection());
145: } elseif ($lowercasedClassName === 'parent') {
146: if (
147: $scope->isInClass()
148: && $scope->getClassReflection()->getParentClass() !== null
149: ) {
150: $type = new ObjectType($scope->getClassReflection()->getParentClass()->getName());
151: } else {
152: $type = new NonexistentParentClassType();
153: }
154: } else {
155: $type = new ObjectType($className);
156: }
157: return $this->create($exprNode, $type, $context, $scope)->setRootExpr($expr);
158: }
159:
160: $classType = $scope->getType($expr->class);
161: $uncertainty = false;
162: $type = TypeTraverser::map($classType, static function (Type $type, callable $traverse) use (&$uncertainty): Type {
163: if ($type instanceof UnionType || $type instanceof IntersectionType) {
164: return $traverse($type);
165: }
166: if ($type->getObjectClassNames() !== []) {
167: $uncertainty = true;
168: return $type;
169: }
170: if ($type instanceof GenericClassStringType) {
171: $uncertainty = true;
172: return $type->getGenericType();
173: }
174: if ($type instanceof ConstantStringType) {
175: return new ObjectType($type->getValue());
176: }
177: return new MixedType();
178: });
179:
180: if (!$type->isSuperTypeOf(new MixedType())->yes()) {
181: if ($context->true()) {
182: $type = TypeCombinator::intersect(
183: $type,
184: new ObjectWithoutClassType(),
185: );
186: return $this->create($exprNode, $type, $context, $scope)->setRootExpr($expr);
187: } elseif ($context->false() && !$uncertainty) {
188: $exprType = $scope->getType($expr->expr);
189: if (!$type->isSuperTypeOf($exprType)->yes()) {
190: return $this->create($exprNode, $type, $context, $scope)->setRootExpr($expr);
191: }
192: }
193: }
194: if ($context->true()) {
195: return $this->create($exprNode, new ObjectWithoutClassType(), $context, $scope)->setRootExpr($exprNode);
196: }
197: } elseif ($expr instanceof Node\Expr\BinaryOp\Identical) {
198: return $this->resolveIdentical($expr, $scope, $context);
199:
200: } elseif ($expr instanceof Node\Expr\BinaryOp\NotIdentical) {
201: return $this->specifyTypesInCondition(
202: $scope,
203: new Node\Expr\BooleanNot(new Node\Expr\BinaryOp\Identical($expr->left, $expr->right)),
204: $context,
205: )->setRootExpr($expr);
206: } elseif ($expr instanceof Expr\Cast\Bool_) {
207: return $this->specifyTypesInCondition(
208: $scope,
209: new Node\Expr\BinaryOp\Equal($expr->expr, new ConstFetch(new Name\FullyQualified('true'))),
210: $context,
211: )->setRootExpr($expr);
212: } elseif ($expr instanceof Expr\Cast\String_) {
213: return $this->specifyTypesInCondition(
214: $scope,
215: new Node\Expr\BinaryOp\NotEqual($expr->expr, new Node\Scalar\String_('')),
216: $context,
217: )->setRootExpr($expr);
218: } elseif ($expr instanceof Expr\Cast\Int_) {
219: return $this->specifyTypesInCondition(
220: $scope,
221: new Node\Expr\BinaryOp\NotEqual($expr->expr, new Node\Scalar\LNumber(0)),
222: $context,
223: )->setRootExpr($expr);
224: } elseif ($expr instanceof Expr\Cast\Double) {
225: return $this->specifyTypesInCondition(
226: $scope,
227: new Node\Expr\BinaryOp\NotEqual($expr->expr, new Node\Scalar\DNumber(0.0)),
228: $context,
229: )->setRootExpr($expr);
230: } elseif ($expr instanceof Node\Expr\BinaryOp\Equal) {
231: return $this->resolveEqual($expr, $scope, $context);
232: } elseif ($expr instanceof Node\Expr\BinaryOp\NotEqual) {
233: return $this->specifyTypesInCondition(
234: $scope,
235: new Node\Expr\BooleanNot(new Node\Expr\BinaryOp\Equal($expr->left, $expr->right)),
236: $context,
237: )->setRootExpr($expr);
238:
239: } elseif ($expr instanceof Node\Expr\BinaryOp\Smaller || $expr instanceof Node\Expr\BinaryOp\SmallerOrEqual) {
240:
241: if (
242: $expr->left instanceof FuncCall
243: && count($expr->left->getArgs()) >= 1
244: && $expr->left->name instanceof Name
245: && in_array(strtolower((string) $expr->left->name), ['count', 'sizeof', 'strlen', 'mb_strlen', 'preg_match'], true)
246: && (
247: !$expr->right instanceof FuncCall
248: || !$expr->right->name instanceof Name
249: || !in_array(strtolower((string) $expr->right->name), ['count', 'sizeof', 'strlen', 'mb_strlen', 'preg_match'], true)
250: )
251: ) {
252: $inverseOperator = $expr instanceof Node\Expr\BinaryOp\Smaller
253: ? new Node\Expr\BinaryOp\SmallerOrEqual($expr->right, $expr->left)
254: : new Node\Expr\BinaryOp\Smaller($expr->right, $expr->left);
255:
256: return $this->specifyTypesInCondition(
257: $scope,
258: new Node\Expr\BooleanNot($inverseOperator),
259: $context,
260: )->setRootExpr($expr);
261: }
262:
263: $orEqual = $expr instanceof Node\Expr\BinaryOp\SmallerOrEqual;
264: $offset = $orEqual ? 0 : 1;
265: $leftType = $scope->getType($expr->left);
266: $result = (new SpecifiedTypes([], []))->setRootExpr($expr);
267:
268: if (
269: !$context->null()
270: && $expr->right instanceof FuncCall
271: && count($expr->right->getArgs()) >= 1
272: && $expr->right->name instanceof Name
273: && in_array(strtolower((string) $expr->right->name), ['count', 'sizeof'], true)
274: && $leftType->isInteger()->yes()
275: ) {
276: $argType = $scope->getType($expr->right->getArgs()[0]->value);
277:
278: if ($leftType instanceof ConstantIntegerType) {
279: if ($orEqual) {
280: $sizeType = IntegerRangeType::createAllGreaterThanOrEqualTo($leftType->getValue());
281: } else {
282: $sizeType = IntegerRangeType::createAllGreaterThan($leftType->getValue());
283: }
284: } elseif ($leftType instanceof IntegerRangeType) {
285: $sizeType = $leftType->shift($offset);
286: } else {
287: $sizeType = $leftType;
288: }
289:
290: $specifiedTypes = $this->specifyTypesForCountFuncCall($expr->right, $argType, $sizeType, $context, $scope, $expr);
291: if ($specifiedTypes !== null) {
292: $result = $result->unionWith($specifiedTypes);
293: }
294:
295: if (
296: $context->true() && (IntegerRangeType::createAllGreaterThanOrEqualTo(1 - $offset)->isSuperTypeOf($leftType)->yes())
297: || ($context->false() && (new ConstantIntegerType(1 - $offset))->isSuperTypeOf($leftType)->yes())
298: ) {
299: if ($context->truthy() && $argType->isArray()->maybe()) {
300: $countables = [];
301: if ($argType instanceof UnionType) {
302: $countableInterface = new ObjectType(Countable::class);
303: foreach ($argType->getTypes() as $innerType) {
304: if ($innerType->isArray()->yes()) {
305: $innerType = TypeCombinator::intersect(new NonEmptyArrayType(), $innerType);
306: $countables[] = $innerType;
307: }
308:
309: if (!$countableInterface->isSuperTypeOf($innerType)->yes()) {
310: continue;
311: }
312:
313: $countables[] = $innerType;
314: }
315: }
316:
317: if (count($countables) > 0) {
318: $countableType = TypeCombinator::union(...$countables);
319:
320: return $this->create($expr->right->getArgs()[0]->value, $countableType, $context, $scope)->setRootExpr($expr);
321: }
322: }
323:
324: if ($argType->isArray()->yes()) {
325: $newType = new NonEmptyArrayType();
326: if ($context->true() && $argType->isList()->yes()) {
327: $newType = TypeCombinator::intersect($newType, new AccessoryArrayListType());
328: }
329:
330: $result = $result->unionWith(
331: $this->create($expr->right->getArgs()[0]->value, $newType, $context, $scope)->setRootExpr($expr),
332: );
333: }
334: }
335: }
336:
337: if (
338: !$context->null()
339: && $expr->right instanceof FuncCall
340: && count($expr->right->getArgs()) >= 3
341: && $expr->right->name instanceof Name
342: && in_array(strtolower((string) $expr->right->name), ['preg_match'], true)
343: && (
344: IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($leftType)->yes()
345: || ($expr instanceof Expr\BinaryOp\Smaller && IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($leftType)->yes())
346: )
347: ) {
348: // 0 < preg_match or 1 <= preg_match becomes 1 === preg_match
349: $newExpr = new Expr\BinaryOp\Identical($expr->right, new Node\Scalar\Int_(1));
350:
351: return $this->specifyTypesInCondition($scope, $newExpr, $context)->setRootExpr($expr);
352: }
353:
354: if (
355: !$context->null()
356: && $expr->right instanceof FuncCall
357: && count($expr->right->getArgs()) === 1
358: && $expr->right->name instanceof Name
359: && in_array(strtolower((string) $expr->right->name), ['strlen', 'mb_strlen'], true)
360: && $leftType->isInteger()->yes()
361: ) {
362: if (
363: $context->true() && (IntegerRangeType::createAllGreaterThanOrEqualTo(1 - $offset)->isSuperTypeOf($leftType)->yes())
364: || ($context->false() && (new ConstantIntegerType(1 - $offset))->isSuperTypeOf($leftType)->yes())
365: ) {
366: $argType = $scope->getType($expr->right->getArgs()[0]->value);
367: if ($argType->isString()->yes()) {
368: $accessory = new AccessoryNonEmptyStringType();
369:
370: if (IntegerRangeType::createAllGreaterThanOrEqualTo(2 - $offset)->isSuperTypeOf($leftType)->yes()) {
371: $accessory = new AccessoryNonFalsyStringType();
372: }
373:
374: $result = $result->unionWith($this->create($expr->right->getArgs()[0]->value, $accessory, $context, $scope)->setRootExpr($expr));
375: }
376: }
377: }
378:
379: if ($leftType instanceof ConstantIntegerType) {
380: if ($expr->right instanceof Expr\PostInc) {
381: $result = $result->unionWith($this->createRangeTypes(
382: $expr,
383: $expr->right->var,
384: IntegerRangeType::fromInterval($leftType->getValue(), null, $offset + 1),
385: $context,
386: ));
387: } elseif ($expr->right instanceof Expr\PostDec) {
388: $result = $result->unionWith($this->createRangeTypes(
389: $expr,
390: $expr->right->var,
391: IntegerRangeType::fromInterval($leftType->getValue(), null, $offset - 1),
392: $context,
393: ));
394: } elseif ($expr->right instanceof Expr\PreInc || $expr->right instanceof Expr\PreDec) {
395: $result = $result->unionWith($this->createRangeTypes(
396: $expr,
397: $expr->right->var,
398: IntegerRangeType::fromInterval($leftType->getValue(), null, $offset),
399: $context,
400: ));
401: }
402: }
403:
404: $rightType = $scope->getType($expr->right);
405: if ($rightType instanceof ConstantIntegerType) {
406: if ($expr->left instanceof Expr\PostInc) {
407: $result = $result->unionWith($this->createRangeTypes(
408: $expr,
409: $expr->left->var,
410: IntegerRangeType::fromInterval(null, $rightType->getValue(), -$offset + 1),
411: $context,
412: ));
413: } elseif ($expr->left instanceof Expr\PostDec) {
414: $result = $result->unionWith($this->createRangeTypes(
415: $expr,
416: $expr->left->var,
417: IntegerRangeType::fromInterval(null, $rightType->getValue(), -$offset - 1),
418: $context,
419: ));
420: } elseif ($expr->left instanceof Expr\PreInc || $expr->left instanceof Expr\PreDec) {
421: $result = $result->unionWith($this->createRangeTypes(
422: $expr,
423: $expr->left->var,
424: IntegerRangeType::fromInterval(null, $rightType->getValue(), -$offset),
425: $context,
426: ));
427: }
428: }
429:
430: if ($context->true()) {
431: if (!$expr->left instanceof Node\Scalar) {
432: $result = $result->unionWith(
433: $this->create(
434: $expr->left,
435: $orEqual ? $rightType->getSmallerOrEqualType($this->phpVersion) : $rightType->getSmallerType($this->phpVersion),
436: TypeSpecifierContext::createTruthy(),
437: $scope,
438: )->setRootExpr($expr),
439: );
440: }
441: if (!$expr->right instanceof Node\Scalar) {
442: $result = $result->unionWith(
443: $this->create(
444: $expr->right,
445: $orEqual ? $leftType->getGreaterOrEqualType($this->phpVersion) : $leftType->getGreaterType($this->phpVersion),
446: TypeSpecifierContext::createTruthy(),
447: $scope,
448: )->setRootExpr($expr),
449: );
450: }
451: } elseif ($context->false()) {
452: if (!$expr->left instanceof Node\Scalar) {
453: $result = $result->unionWith(
454: $this->create(
455: $expr->left,
456: $orEqual ? $rightType->getGreaterType($this->phpVersion) : $rightType->getGreaterOrEqualType($this->phpVersion),
457: TypeSpecifierContext::createTruthy(),
458: $scope,
459: )->setRootExpr($expr),
460: );
461: }
462: if (!$expr->right instanceof Node\Scalar) {
463: $result = $result->unionWith(
464: $this->create(
465: $expr->right,
466: $orEqual ? $leftType->getSmallerType($this->phpVersion) : $leftType->getSmallerOrEqualType($this->phpVersion),
467: TypeSpecifierContext::createTruthy(),
468: $scope,
469: )->setRootExpr($expr),
470: );
471: }
472: }
473:
474: return $result;
475:
476: } elseif ($expr instanceof Node\Expr\BinaryOp\Greater) {
477: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Smaller($expr->right, $expr->left), $context)->setRootExpr($expr);
478:
479: } elseif ($expr instanceof Node\Expr\BinaryOp\GreaterOrEqual) {
480: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\SmallerOrEqual($expr->right, $expr->left), $context)->setRootExpr($expr);
481:
482: } elseif ($expr instanceof FuncCall && $expr->name instanceof Name) {
483: if ($this->reflectionProvider->hasFunction($expr->name, $scope)) {
484: // lazy create parametersAcceptor, as creation can be expensive
485: $parametersAcceptor = null;
486:
487: $functionReflection = $this->reflectionProvider->getFunction($expr->name, $scope);
488: $normalizedExpr = $expr;
489: if (count($expr->getArgs()) > 0) {
490: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $functionReflection->getVariants(), $functionReflection->getNamedArgumentsVariants());
491: $normalizedExpr = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $expr) ?? $expr;
492: }
493:
494: foreach ($this->getFunctionTypeSpecifyingExtensions() as $extension) {
495: if (!$extension->isFunctionSupported($functionReflection, $normalizedExpr, $context)) {
496: continue;
497: }
498:
499: return $extension->specifyTypes($functionReflection, $normalizedExpr, $scope, $context);
500: }
501:
502: if (count($expr->getArgs()) > 0) {
503: $specifiedTypes = $this->specifyTypesFromConditionalReturnType($context, $expr, $parametersAcceptor, $scope);
504: if ($specifiedTypes !== null) {
505: return $specifiedTypes;
506: }
507: }
508:
509: $assertions = $functionReflection->getAsserts();
510: if ($assertions->getAll() !== []) {
511: $parametersAcceptor ??= ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $functionReflection->getVariants(), $functionReflection->getNamedArgumentsVariants());
512:
513: $asserts = $assertions->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
514: $type,
515: $parametersAcceptor->getResolvedTemplateTypeMap(),
516: $parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
517: TemplateTypeVariance::createInvariant(),
518: ));
519: $specifiedTypes = $this->specifyTypesFromAsserts($context, $expr, $asserts, $parametersAcceptor, $scope);
520: if ($specifiedTypes !== null) {
521: return $specifiedTypes;
522: }
523: }
524: }
525:
526: return $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
527: } elseif ($expr instanceof MethodCall && $expr->name instanceof Node\Identifier) {
528: $methodCalledOnType = $scope->getType($expr->var);
529: $methodReflection = $scope->getMethodReflection($methodCalledOnType, $expr->name->name);
530: if ($methodReflection !== null) {
531: // lazy create parametersAcceptor, as creation can be expensive
532: $parametersAcceptor = null;
533:
534: $normalizedExpr = $expr;
535: if (count($expr->getArgs()) > 0) {
536: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
537: $normalizedExpr = ArgumentsNormalizer::reorderMethodArguments($parametersAcceptor, $expr) ?? $expr;
538: }
539:
540: $referencedClasses = $methodCalledOnType->getObjectClassNames();
541: if (
542: count($referencedClasses) === 1
543: && $this->reflectionProvider->hasClass($referencedClasses[0])
544: ) {
545: $methodClassReflection = $this->reflectionProvider->getClass($referencedClasses[0]);
546: foreach ($this->getMethodTypeSpecifyingExtensionsForClass($methodClassReflection->getName()) as $extension) {
547: if (!$extension->isMethodSupported($methodReflection, $normalizedExpr, $context)) {
548: continue;
549: }
550:
551: return $extension->specifyTypes($methodReflection, $normalizedExpr, $scope, $context);
552: }
553: }
554:
555: if (count($expr->getArgs()) > 0) {
556: $specifiedTypes = $this->specifyTypesFromConditionalReturnType($context, $expr, $parametersAcceptor, $scope);
557: if ($specifiedTypes !== null) {
558: return $specifiedTypes;
559: }
560: }
561:
562: $assertions = $methodReflection->getAsserts();
563: if ($assertions->getAll() !== []) {
564: $parametersAcceptor ??= ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
565:
566: $asserts = $assertions->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
567: $type,
568: $parametersAcceptor->getResolvedTemplateTypeMap(),
569: $parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
570: TemplateTypeVariance::createInvariant(),
571: ));
572: $specifiedTypes = $this->specifyTypesFromAsserts($context, $expr, $asserts, $parametersAcceptor, $scope);
573: if ($specifiedTypes !== null) {
574: return $specifiedTypes;
575: }
576: }
577: }
578:
579: return $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
580: } elseif ($expr instanceof StaticCall && $expr->name instanceof Node\Identifier) {
581: if ($expr->class instanceof Name) {
582: $calleeType = $scope->resolveTypeByName($expr->class);
583: } else {
584: $calleeType = $scope->getType($expr->class);
585: }
586:
587: $staticMethodReflection = $scope->getMethodReflection($calleeType, $expr->name->name);
588: if ($staticMethodReflection !== null) {
589: // lazy create parametersAcceptor, as creation can be expensive
590: $parametersAcceptor = null;
591:
592: $normalizedExpr = $expr;
593: if (count($expr->getArgs()) > 0) {
594: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $staticMethodReflection->getVariants(), $staticMethodReflection->getNamedArgumentsVariants());
595: $normalizedExpr = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $expr) ?? $expr;
596: }
597:
598: $referencedClasses = $calleeType->getObjectClassNames();
599: if (
600: count($referencedClasses) === 1
601: && $this->reflectionProvider->hasClass($referencedClasses[0])
602: ) {
603: $staticMethodClassReflection = $this->reflectionProvider->getClass($referencedClasses[0]);
604: foreach ($this->getStaticMethodTypeSpecifyingExtensionsForClass($staticMethodClassReflection->getName()) as $extension) {
605: if (!$extension->isStaticMethodSupported($staticMethodReflection, $normalizedExpr, $context)) {
606: continue;
607: }
608:
609: return $extension->specifyTypes($staticMethodReflection, $normalizedExpr, $scope, $context);
610: }
611: }
612:
613: if (count($expr->getArgs()) > 0) {
614: $specifiedTypes = $this->specifyTypesFromConditionalReturnType($context, $expr, $parametersAcceptor, $scope);
615: if ($specifiedTypes !== null) {
616: return $specifiedTypes;
617: }
618: }
619:
620: $assertions = $staticMethodReflection->getAsserts();
621: if ($assertions->getAll() !== []) {
622: $parametersAcceptor ??= ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $staticMethodReflection->getVariants(), $staticMethodReflection->getNamedArgumentsVariants());
623:
624: $asserts = $assertions->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
625: $type,
626: $parametersAcceptor->getResolvedTemplateTypeMap(),
627: $parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
628: TemplateTypeVariance::createInvariant(),
629: ));
630: $specifiedTypes = $this->specifyTypesFromAsserts($context, $expr, $asserts, $parametersAcceptor, $scope);
631: if ($specifiedTypes !== null) {
632: return $specifiedTypes;
633: }
634: }
635: }
636:
637: return $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
638: } elseif ($expr instanceof BooleanAnd || $expr instanceof LogicalAnd) {
639: if (!$scope instanceof MutatingScope) {
640: throw new ShouldNotHappenException();
641: }
642: $leftTypes = $this->specifyTypesInCondition($scope, $expr->left, $context)->setRootExpr($expr);
643: $rightScope = $scope->filterByTruthyValue($expr->left);
644: $rightTypes = $this->specifyTypesInCondition($rightScope, $expr->right, $context)->setRootExpr($expr);
645: $types = $context->true() ? $leftTypes->unionWith($rightTypes) : $leftTypes->normalize($scope)->intersectWith($rightTypes->normalize($rightScope));
646: if ($context->false()) {
647: return (new SpecifiedTypes(
648: $types->getSureTypes(),
649: $types->getSureNotTypes(),
650: ))->setNewConditionalExpressionHolders(array_merge(
651: $this->processBooleanNotSureConditionalTypes($scope, $leftTypes, $rightTypes),
652: $this->processBooleanNotSureConditionalTypes($scope, $rightTypes, $leftTypes),
653: $this->processBooleanSureConditionalTypes($scope, $leftTypes, $rightTypes),
654: $this->processBooleanSureConditionalTypes($scope, $rightTypes, $leftTypes),
655: ))->setRootExpr($expr);
656: }
657:
658: return $types;
659: } elseif ($expr instanceof BooleanOr || $expr instanceof LogicalOr) {
660: if (!$scope instanceof MutatingScope) {
661: throw new ShouldNotHappenException();
662: }
663: $leftTypes = $this->specifyTypesInCondition($scope, $expr->left, $context)->setRootExpr($expr);
664: $rightScope = $scope->filterByFalseyValue($expr->left);
665: $rightTypes = $this->specifyTypesInCondition($rightScope, $expr->right, $context)->setRootExpr($expr);
666:
667: if ($context->true()) {
668: if (
669: $scope->getType($expr->left)->toBoolean()->isFalse()->yes()
670: ) {
671: $types = $rightTypes->normalize($rightScope);
672: } elseif (
673: $scope->getType($expr->left)->toBoolean()->isTrue()->yes()
674: || $scope->getType($expr->right)->toBoolean()->isFalse()->yes()
675: ) {
676: $types = $leftTypes->normalize($scope);
677: } else {
678: $types = $leftTypes->normalize($scope)->intersectWith($rightTypes->normalize($rightScope));
679: }
680: } else {
681: $types = $leftTypes->unionWith($rightTypes);
682: }
683:
684: if ($context->true()) {
685: return (new SpecifiedTypes(
686: $types->getSureTypes(),
687: $types->getSureNotTypes(),
688: ))->setNewConditionalExpressionHolders(array_merge(
689: $this->processBooleanNotSureConditionalTypes($scope, $leftTypes, $rightTypes),
690: $this->processBooleanNotSureConditionalTypes($scope, $rightTypes, $leftTypes),
691: $this->processBooleanSureConditionalTypes($scope, $leftTypes, $rightTypes),
692: $this->processBooleanSureConditionalTypes($scope, $rightTypes, $leftTypes),
693: ))->setRootExpr($expr);
694: }
695:
696: return $types;
697: } elseif ($expr instanceof Node\Expr\BooleanNot && !$context->null()) {
698: return $this->specifyTypesInCondition($scope, $expr->expr, $context->negate())->setRootExpr($expr);
699: } elseif ($expr instanceof Node\Expr\Assign) {
700: if (!$scope instanceof MutatingScope) {
701: throw new ShouldNotHappenException();
702: }
703:
704: if ($context->null()) {
705: $specifiedTypes = $this->specifyTypesInCondition($scope->exitFirstLevelStatements(), $expr->expr, $context)->setRootExpr($expr);
706:
707: // infer $arr[$key] after $key = array_rand($arr)
708: if (
709: $expr->expr instanceof FuncCall
710: && $expr->expr->name instanceof Name
711: && in_array($expr->expr->name->toLowerString(), ['array_rand'], true)
712: && count($expr->expr->getArgs()) >= 1
713: ) {
714: $numArg = null;
715: $arrayArg = $expr->expr->getArgs()[0]->value;
716: if (count($expr->expr->getArgs()) > 1) {
717: $numArg = $expr->expr->getArgs()[1]->value;
718: }
719: $one = new ConstantIntegerType(1);
720: $arrayType = $scope->getType($arrayArg);
721:
722: if (
723: $arrayType->isArray()->yes()
724: && $arrayType->isIterableAtLeastOnce()->yes()
725: && ($numArg === null || $one->isSuperTypeOf($scope->getType($numArg))->yes())
726: ) {
727: $dimFetch = new ArrayDimFetch($arrayArg, $expr->var);
728:
729: return $specifiedTypes->unionWith(
730: $this->create($dimFetch, $arrayType->getIterableValueType(), TypeSpecifierContext::createTrue(), $scope),
731: );
732: }
733: }
734:
735: // infer $arr[$key] after $key = array_key_first/last($arr)
736: if (
737: $expr->expr instanceof FuncCall
738: && $expr->expr->name instanceof Name
739: && in_array($expr->expr->name->toLowerString(), ['array_key_first', 'array_key_last'], true)
740: && count($expr->expr->getArgs()) >= 1
741: ) {
742: $arrayArg = $expr->expr->getArgs()[0]->value;
743: $arrayType = $scope->getType($arrayArg);
744: if (
745: $arrayType->isArray()->yes()
746: && $arrayType->isIterableAtLeastOnce()->yes()
747: ) {
748: $dimFetch = new ArrayDimFetch($arrayArg, $expr->var);
749: $iterableValueType = $expr->expr->name->toLowerString() === 'array_key_first'
750: ? $arrayType->getIterableValueType()
751: : $arrayType->getIterableValueType();
752:
753: return $specifiedTypes->unionWith(
754: $this->create($dimFetch, $iterableValueType, TypeSpecifierContext::createTrue(), $scope),
755: );
756: }
757: }
758:
759: // infer $list[$count] after $count = count($list) - 1
760: if (
761: $expr->expr instanceof Expr\BinaryOp\Minus
762: && $expr->expr->left instanceof FuncCall
763: && $expr->expr->left->name instanceof Name
764: && in_array($expr->expr->left->name->toLowerString(), ['count', 'sizeof'], true)
765: && count($expr->expr->left->getArgs()) >= 1
766: && $expr->expr->right instanceof Node\Scalar\Int_
767: && $expr->expr->right->value === 1
768: ) {
769: $arrayArg = $expr->expr->left->getArgs()[0]->value;
770: $arrayType = $scope->getType($arrayArg);
771: if (
772: $arrayType->isList()->yes()
773: && $arrayType->isIterableAtLeastOnce()->yes()
774: ) {
775: $dimFetch = new ArrayDimFetch($arrayArg, $expr->var);
776:
777: return $specifiedTypes->unionWith(
778: $this->create($dimFetch, $arrayType->getIterableValueType(), TypeSpecifierContext::createTrue(), $scope),
779: );
780: }
781: }
782:
783: return $specifiedTypes;
784: }
785:
786: $specifiedTypes = $this->specifyTypesInCondition($scope->exitFirstLevelStatements(), $expr->var, $context)->setRootExpr($expr);
787:
788: if ($context->true()) {
789: // infer $arr[$key] after $key = array_search($needle, $arr)
790: if (
791: $expr->expr instanceof FuncCall
792: && $expr->expr->name instanceof Name
793: && $expr->expr->name->toLowerString() === 'array_search'
794: && count($expr->expr->getArgs()) >= 2
795: ) {
796: $arrayArg = $expr->expr->getArgs()[1]->value;
797: $arrayType = $scope->getType($arrayArg);
798:
799: if ($arrayType->isArray()->yes()) {
800: $dimFetch = new ArrayDimFetch($arrayArg, $expr->var);
801: $iterableValueType = $arrayType->getIterableValueType();
802:
803: return $specifiedTypes->unionWith(
804: $this->create($dimFetch, $iterableValueType, TypeSpecifierContext::createTrue(), $scope),
805: );
806: }
807: }
808: }
809: return $specifiedTypes;
810: } elseif (
811: $expr instanceof Expr\Isset_
812: && count($expr->vars) > 0
813: && !$context->null()
814: ) {
815: // rewrite multi param isset() to and-chained single param isset()
816: if (count($expr->vars) > 1) {
817: $issets = [];
818: foreach ($expr->vars as $var) {
819: $issets[] = new Expr\Isset_([$var], $expr->getAttributes());
820: }
821:
822: $first = array_shift($issets);
823: $andChain = null;
824: foreach ($issets as $isset) {
825: if ($andChain === null) {
826: $andChain = new BooleanAnd($first, $isset);
827: continue;
828: }
829:
830: $andChain = new BooleanAnd($andChain, $isset);
831: }
832:
833: if ($andChain === null) {
834: throw new ShouldNotHappenException();
835: }
836:
837: return $this->specifyTypesInCondition($scope, $andChain, $context)->setRootExpr($expr);
838: }
839:
840: $issetExpr = $expr->vars[0];
841:
842: if (!$context->true()) {
843: if (!$scope instanceof MutatingScope) {
844: throw new ShouldNotHappenException();
845: }
846:
847: $isset = $scope->issetCheck($issetExpr, static fn () => true);
848:
849: if ($isset === false) {
850: return new SpecifiedTypes();
851: }
852:
853: $type = $scope->getType($issetExpr);
854: $isNullable = !$type->isNull()->no();
855: $exprType = $this->create(
856: $issetExpr,
857: new NullType(),
858: $context->negate(),
859: $scope,
860: )->setRootExpr($expr);
861:
862: if ($issetExpr instanceof Expr\Variable && is_string($issetExpr->name)) {
863: if ($isset === true) {
864: if ($isNullable) {
865: return $exprType;
866: }
867:
868: // variable cannot exist in !isset()
869: return $exprType->unionWith($this->create(
870: new IssetExpr($issetExpr),
871: new NullType(),
872: $context,
873: $scope,
874: ))->setRootExpr($expr);
875: }
876:
877: if ($isNullable) {
878: // reduces variable certainty to maybe
879: return $exprType->unionWith($this->create(
880: new IssetExpr($issetExpr),
881: new NullType(),
882: $context->negate(),
883: $scope,
884: ))->setRootExpr($expr);
885: }
886:
887: // variable cannot exist in !isset()
888: return $this->create(
889: new IssetExpr($issetExpr),
890: new NullType(),
891: $context,
892: $scope,
893: )->setRootExpr($expr);
894: }
895:
896: if ($isNullable && $isset === true) {
897: return $exprType;
898: }
899:
900: return new SpecifiedTypes();
901: }
902:
903: $tmpVars = [$issetExpr];
904: while (
905: $issetExpr instanceof ArrayDimFetch
906: || $issetExpr instanceof PropertyFetch
907: || (
908: $issetExpr instanceof StaticPropertyFetch
909: && $issetExpr->class instanceof Expr
910: )
911: ) {
912: if ($issetExpr instanceof StaticPropertyFetch) {
913: /** @var Expr $issetExpr */
914: $issetExpr = $issetExpr->class;
915: } else {
916: $issetExpr = $issetExpr->var;
917: }
918: $tmpVars[] = $issetExpr;
919: }
920: $vars = array_reverse($tmpVars);
921:
922: $types = new SpecifiedTypes();
923: foreach ($vars as $var) {
924:
925: if ($var instanceof Expr\Variable && is_string($var->name)) {
926: if ($scope->hasVariableType($var->name)->no()) {
927: return (new SpecifiedTypes([], []))->setRootExpr($expr);
928: }
929: }
930:
931: if (
932: $var instanceof ArrayDimFetch
933: && $var->dim !== null
934: && !$scope->getType($var->var) instanceof MixedType
935: ) {
936: $dimType = $scope->getType($var->dim);
937:
938: if ($dimType instanceof ConstantIntegerType || $dimType instanceof ConstantStringType) {
939: $types = $types->unionWith(
940: $this->create(
941: $var->var,
942: new HasOffsetType($dimType),
943: $context,
944: $scope,
945: )->setRootExpr($expr),
946: );
947: } else {
948: $varType = $scope->getType($var->var);
949: $narrowedKey = AllowedArrayKeysTypes::narrowOffsetKeyType($varType, $dimType);
950: if ($narrowedKey !== null) {
951: $types = $types->unionWith(
952: $this->create(
953: $var->dim,
954: $narrowedKey,
955: $context,
956: $scope,
957: )->setRootExpr($expr),
958: );
959: }
960: }
961: }
962:
963: if (
964: $var instanceof PropertyFetch
965: && $var->name instanceof Node\Identifier
966: ) {
967: $types = $types->unionWith(
968: $this->create($var->var, new IntersectionType([
969: new ObjectWithoutClassType(),
970: new HasPropertyType($var->name->toString()),
971: ]), TypeSpecifierContext::createTruthy(), $scope)->setRootExpr($expr),
972: );
973: } elseif (
974: $var instanceof StaticPropertyFetch
975: && $var->class instanceof Expr
976: && $var->name instanceof Node\VarLikeIdentifier
977: ) {
978: $types = $types->unionWith(
979: $this->create($var->class, new IntersectionType([
980: new ObjectWithoutClassType(),
981: new HasPropertyType($var->name->toString()),
982: ]), TypeSpecifierContext::createTruthy(), $scope)->setRootExpr($expr),
983: );
984: }
985:
986: $types = $types->unionWith(
987: $this->create($var, new NullType(), TypeSpecifierContext::createFalse(), $scope)->setRootExpr($expr),
988: );
989: }
990:
991: return $types;
992: } elseif (
993: $expr instanceof Expr\BinaryOp\Coalesce
994: && !$context->null()
995: ) {
996: if (!$context->true()) {
997: if (!$scope instanceof MutatingScope) {
998: throw new ShouldNotHappenException();
999: }
1000:
1001: $isset = $scope->issetCheck($expr->left, static fn () => true);
1002:
1003: if ($isset !== true) {
1004: return new SpecifiedTypes();
1005: }
1006:
1007: return $this->create(
1008: $expr->left,
1009: new NullType(),
1010: $context->negate(),
1011: $scope,
1012: )->setRootExpr($expr);
1013: }
1014:
1015: if ((new ConstantBooleanType(false))->isSuperTypeOf($scope->getType($expr->right)->toBoolean())->yes()) {
1016: return $this->create(
1017: $expr->left,
1018: new NullType(),
1019: TypeSpecifierContext::createFalse(),
1020: $scope,
1021: )->setRootExpr($expr);
1022: }
1023:
1024: } elseif (
1025: $expr instanceof Expr\Empty_
1026: ) {
1027: if (!$scope instanceof MutatingScope) {
1028: throw new ShouldNotHappenException();
1029: }
1030:
1031: $isset = $scope->issetCheck($expr->expr, static fn () => true);
1032: if ($isset === false) {
1033: return new SpecifiedTypes();
1034: }
1035:
1036: return $this->specifyTypesInCondition($scope, new BooleanOr(
1037: new Expr\BooleanNot(new Expr\Isset_([$expr->expr])),
1038: new Expr\BooleanNot($expr->expr),
1039: ), $context)->setRootExpr($expr);
1040: } elseif ($expr instanceof Expr\ErrorSuppress) {
1041: return $this->specifyTypesInCondition($scope, $expr->expr, $context)->setRootExpr($expr);
1042: } elseif (
1043: $expr instanceof Expr\Ternary
1044: && !$context->null()
1045: && $scope->getType($expr->else)->isFalse()->yes()
1046: ) {
1047: $conditionExpr = $expr->cond;
1048: if ($expr->if !== null) {
1049: $conditionExpr = new BooleanAnd($conditionExpr, $expr->if);
1050: }
1051:
1052: return $this->specifyTypesInCondition($scope, $conditionExpr, $context)->setRootExpr($expr);
1053:
1054: } elseif ($expr instanceof Expr\NullsafePropertyFetch && !$context->null()) {
1055: $types = $this->specifyTypesInCondition(
1056: $scope,
1057: new BooleanAnd(
1058: new Expr\BinaryOp\NotIdentical($expr->var, new ConstFetch(new Name('null'))),
1059: new PropertyFetch($expr->var, $expr->name),
1060: ),
1061: $context,
1062: )->setRootExpr($expr);
1063:
1064: $nullSafeTypes = $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
1065: return $context->true() ? $types->unionWith($nullSafeTypes) : $types->normalize($scope)->intersectWith($nullSafeTypes->normalize($scope));
1066: } elseif ($expr instanceof Expr\NullsafeMethodCall && !$context->null()) {
1067: $types = $this->specifyTypesInCondition(
1068: $scope,
1069: new BooleanAnd(
1070: new Expr\BinaryOp\NotIdentical($expr->var, new ConstFetch(new Name('null'))),
1071: new MethodCall($expr->var, $expr->name, $expr->args),
1072: ),
1073: $context,
1074: )->setRootExpr($expr);
1075:
1076: $nullSafeTypes = $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
1077: return $context->true() ? $types->unionWith($nullSafeTypes) : $types->normalize($scope)->intersectWith($nullSafeTypes->normalize($scope));
1078: } elseif (
1079: $expr instanceof Expr\New_
1080: && $expr->class instanceof Name
1081: && $this->reflectionProvider->hasClass($expr->class->toString())
1082: ) {
1083: $classReflection = $this->reflectionProvider->getClass($expr->class->toString());
1084:
1085: if ($classReflection->hasConstructor()) {
1086: $methodReflection = $classReflection->getConstructor();
1087: $asserts = $methodReflection->getAsserts();
1088:
1089: if ($asserts->getAll() !== []) {
1090: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs($scope, $expr->getArgs(), $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
1091:
1092: $asserts = $asserts->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
1093: $type,
1094: $parametersAcceptor->getResolvedTemplateTypeMap(),
1095: $parametersAcceptor instanceof ExtendedParametersAcceptor ? $parametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
1096: TemplateTypeVariance::createInvariant(),
1097: ));
1098:
1099: $specifiedTypes = $this->specifyTypesFromAsserts($context, $expr, $asserts, $parametersAcceptor, $scope);
1100:
1101: if ($specifiedTypes !== null) {
1102: return $specifiedTypes;
1103: }
1104: }
1105: }
1106: } elseif (!$context->null()) {
1107: return $this->handleDefaultTruthyOrFalseyContext($context, $expr, $scope);
1108: }
1109:
1110: return (new SpecifiedTypes([], []))->setRootExpr($expr);
1111: }
1112:
1113: private function specifyTypesForCountFuncCall(
1114: FuncCall $countFuncCall,
1115: Type $type,
1116: Type $sizeType,
1117: TypeSpecifierContext $context,
1118: Scope $scope,
1119: Expr $rootExpr,
1120: ): ?SpecifiedTypes
1121: {
1122: if (count($countFuncCall->getArgs()) === 1) {
1123: $isNormalCount = TrinaryLogic::createYes();
1124: } else {
1125: $mode = $scope->getType($countFuncCall->getArgs()[1]->value);
1126: $isNormalCount = (new ConstantIntegerType(COUNT_NORMAL))->isSuperTypeOf($mode)->result->or($type->getIterableValueType()->isArray()->negate());
1127: }
1128:
1129: $isConstantArray = $type->isConstantArray();
1130: $isList = $type->isList();
1131: $oneOrMore = IntegerRangeType::fromInterval(1, null);
1132: if (
1133: !$isNormalCount->yes()
1134: || (!$isConstantArray->yes() && !$isList->yes())
1135: || !$oneOrMore->isSuperTypeOf($sizeType)->yes()
1136: || $sizeType->isSuperTypeOf($type->getArraySize())->yes()
1137: ) {
1138: return null;
1139: }
1140:
1141: $resultTypes = [];
1142: foreach ($type->getArrays() as $arrayType) {
1143: $isSizeSuperTypeOfArraySize = $sizeType->isSuperTypeOf($arrayType->getArraySize());
1144: if ($isSizeSuperTypeOfArraySize->no()) {
1145: continue;
1146: }
1147:
1148: if ($context->falsey() && $isSizeSuperTypeOfArraySize->maybe()) {
1149: continue;
1150: }
1151:
1152: if (
1153: $sizeType instanceof ConstantIntegerType
1154: && $sizeType->getValue() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1155: && $isList->yes()
1156: && $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, $sizeType->getValue() - 1))->yes()
1157: ) {
1158: // turn optional offsets non-optional
1159: $valueTypesBuilder = ConstantArrayTypeBuilder::createEmpty();
1160: for ($i = 0; $i < $sizeType->getValue(); $i++) {
1161: $offsetType = new ConstantIntegerType($i);
1162: $valueTypesBuilder->setOffsetValueType($offsetType, $arrayType->getOffsetValueType($offsetType));
1163: }
1164: $resultTypes[] = $valueTypesBuilder->getArray();
1165: continue;
1166: }
1167:
1168: if (
1169: $sizeType instanceof IntegerRangeType
1170: && $sizeType->getMin() !== null
1171: && $sizeType->getMin() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1172: && $isList->yes()
1173: && $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($sizeType->getMax() ?? $sizeType->getMin()) - 1))->yes()
1174: ) {
1175: $builderData = [];
1176: // turn optional offsets non-optional
1177: for ($i = 0; $i < $sizeType->getMin(); $i++) {
1178: $offsetType = new ConstantIntegerType($i);
1179: $builderData[] = [$offsetType, $arrayType->getOffsetValueType($offsetType), false];
1180: }
1181: if ($sizeType->getMax() !== null) {
1182: if ($sizeType->getMax() - $sizeType->getMin() > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
1183: $resultTypes[] = $arrayType;
1184: continue;
1185: }
1186: for ($i = $sizeType->getMin(); $i < $sizeType->getMax(); $i++) {
1187: $offsetType = new ConstantIntegerType($i);
1188: $builderData[] = [$offsetType, $arrayType->getOffsetValueType($offsetType), true];
1189: }
1190: } elseif ($arrayType->isConstantArray()->yes()) {
1191: for ($i = $sizeType->getMin();; $i++) {
1192: $offsetType = new ConstantIntegerType($i);
1193: $hasOffset = $arrayType->hasOffsetValueType($offsetType);
1194: if ($hasOffset->no()) {
1195: break;
1196: }
1197: $builderData[] = [$offsetType, $arrayType->getOffsetValueType($offsetType), !$hasOffset->yes()];
1198: }
1199: } else {
1200: $resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
1201: continue;
1202: }
1203:
1204: if (count($builderData) > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
1205: $resultTypes[] = $arrayType;
1206: continue;
1207: }
1208:
1209: $builder = ConstantArrayTypeBuilder::createEmpty();
1210: foreach ($builderData as [$offsetType, $valueType, $optional]) {
1211: $builder->setOffsetValueType($offsetType, $valueType, $optional);
1212: }
1213:
1214: $resultTypes[] = $builder->getArray();
1215: continue;
1216: }
1217:
1218: $resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
1219: }
1220:
1221: return $this->create($countFuncCall->getArgs()[0]->value, TypeCombinator::union(...$resultTypes), $context, $scope)->setRootExpr($rootExpr);
1222: }
1223:
1224: private function specifyTypesForConstantBinaryExpression(
1225: Expr $exprNode,
1226: Type $constantType,
1227: TypeSpecifierContext $context,
1228: Scope $scope,
1229: Expr $rootExpr,
1230: ): ?SpecifiedTypes
1231: {
1232: if (!$context->null() && $constantType->isFalse()->yes()) {
1233: $types = $this->create($exprNode, $constantType, $context, $scope)->setRootExpr($rootExpr);
1234: if (!$context->true() && ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch)) {
1235: return $types;
1236: }
1237:
1238: return $types->unionWith($this->specifyTypesInCondition(
1239: $scope,
1240: $exprNode,
1241: $context->true() ? TypeSpecifierContext::createFalse() : TypeSpecifierContext::createFalse()->negate(),
1242: )->setRootExpr($rootExpr));
1243: }
1244:
1245: if (!$context->null() && $constantType->isTrue()->yes()) {
1246: $types = $this->create($exprNode, $constantType, $context, $scope)->setRootExpr($rootExpr);
1247: if (!$context->true() && ($exprNode instanceof Expr\NullsafeMethodCall || $exprNode instanceof Expr\NullsafePropertyFetch)) {
1248: return $types;
1249: }
1250:
1251: return $types->unionWith($this->specifyTypesInCondition(
1252: $scope,
1253: $exprNode,
1254: $context->true() ? TypeSpecifierContext::createTrue() : TypeSpecifierContext::createTrue()->negate(),
1255: )->setRootExpr($rootExpr));
1256: }
1257:
1258: return null;
1259: }
1260:
1261: private function specifyTypesForConstantStringBinaryExpression(
1262: Expr $exprNode,
1263: Type $constantType,
1264: TypeSpecifierContext $context,
1265: Scope $scope,
1266: Expr $rootExpr,
1267: ): ?SpecifiedTypes
1268: {
1269: $scalarValues = $constantType->getConstantScalarValues();
1270: if (count($scalarValues) !== 1 || !is_string($scalarValues[0])) {
1271: return null;
1272: }
1273: $constantStringValue = $scalarValues[0];
1274:
1275: if (
1276: $exprNode instanceof FuncCall
1277: && $exprNode->name instanceof Name
1278: && strtolower($exprNode->name->toString()) === 'gettype'
1279: && isset($exprNode->getArgs()[0])
1280: ) {
1281: $type = null;
1282: if ($constantStringValue === 'string') {
1283: $type = new StringType();
1284: }
1285: if ($constantStringValue === 'array') {
1286: $type = new ArrayType(new MixedType(), new MixedType());
1287: }
1288: if ($constantStringValue === 'boolean') {
1289: $type = new BooleanType();
1290: }
1291: if (in_array($constantStringValue, ['resource', 'resource (closed)'], true)) {
1292: $type = new ResourceType();
1293: }
1294: if ($constantStringValue === 'integer') {
1295: $type = new IntegerType();
1296: }
1297: if ($constantStringValue === 'double') {
1298: $type = new FloatType();
1299: }
1300: if ($constantStringValue === 'NULL') {
1301: $type = new NullType();
1302: }
1303: if ($constantStringValue === 'object') {
1304: $type = new ObjectWithoutClassType();
1305: }
1306:
1307: if ($type !== null) {
1308: $callType = $this->create($exprNode, $constantType, $context, $scope)->setRootExpr($rootExpr);
1309: $argType = $this->create($exprNode->getArgs()[0]->value, $type, $context, $scope)->setRootExpr($rootExpr);
1310: return $callType->unionWith($argType);
1311: }
1312: }
1313:
1314: if (
1315: $context->true()
1316: && $exprNode instanceof FuncCall
1317: && $exprNode->name instanceof Name
1318: && strtolower((string) $exprNode->name) === 'get_parent_class'
1319: && isset($exprNode->getArgs()[0])
1320: ) {
1321: $argType = $scope->getType($exprNode->getArgs()[0]->value);
1322: $objectType = new ObjectType($constantStringValue);
1323: $classStringType = new GenericClassStringType($objectType);
1324:
1325: if ($argType->isString()->yes()) {
1326: return $this->create(
1327: $exprNode->getArgs()[0]->value,
1328: $classStringType,
1329: $context,
1330: $scope,
1331: )->setRootExpr($rootExpr);
1332: }
1333:
1334: if ($argType->isObject()->yes()) {
1335: return $this->create(
1336: $exprNode->getArgs()[0]->value,
1337: $objectType,
1338: $context,
1339: $scope,
1340: )->setRootExpr($rootExpr);
1341: }
1342:
1343: return $this->create(
1344: $exprNode->getArgs()[0]->value,
1345: TypeCombinator::union($objectType, $classStringType),
1346: $context,
1347: $scope,
1348: )->setRootExpr($rootExpr);
1349: }
1350:
1351: if (
1352: $context->false()
1353: && $exprNode instanceof FuncCall
1354: && $exprNode->name instanceof Name
1355: && in_array(strtolower((string) $exprNode->name), [
1356: 'trim', 'ltrim', 'rtrim',
1357: 'mb_trim', 'mb_ltrim', 'mb_rtrim',
1358: ], true)
1359: && isset($exprNode->getArgs()[0])
1360: && $constantStringValue === ''
1361: ) {
1362: $argValue = $exprNode->getArgs()[0]->value;
1363: $argType = $scope->getType($argValue);
1364: if ($argType->isString()->yes()) {
1365: return $this->create(
1366: $argValue,
1367: TypeCombinator::intersect(
1368: new StringType(),
1369: new AccessoryNonEmptyStringType(),
1370: ),
1371: $context->negate(),
1372: $scope,
1373: )->setRootExpr($rootExpr);
1374: }
1375: }
1376:
1377: return null;
1378: }
1379:
1380: private function handleDefaultTruthyOrFalseyContext(TypeSpecifierContext $context, Expr $expr, Scope $scope): SpecifiedTypes
1381: {
1382: if ($context->null()) {
1383: return (new SpecifiedTypes([], []))->setRootExpr($expr);
1384: }
1385: if (!$context->truthy()) {
1386: $type = StaticTypeFactory::truthy();
1387: return $this->create($expr, $type, TypeSpecifierContext::createFalse(), $scope)->setRootExpr($expr);
1388: } elseif (!$context->falsey()) {
1389: $type = StaticTypeFactory::falsey();
1390: return $this->create($expr, $type, TypeSpecifierContext::createFalse(), $scope)->setRootExpr($expr);
1391: }
1392:
1393: return (new SpecifiedTypes([], []))->setRootExpr($expr);
1394: }
1395:
1396: private function specifyTypesFromConditionalReturnType(
1397: TypeSpecifierContext $context,
1398: Expr\CallLike $call,
1399: ParametersAcceptor $parametersAcceptor,
1400: Scope $scope,
1401: ): ?SpecifiedTypes
1402: {
1403: if (!$parametersAcceptor instanceof ResolvedFunctionVariant) {
1404: return null;
1405: }
1406:
1407: $returnType = $parametersAcceptor->getOriginalParametersAcceptor()->getReturnType();
1408: if (!$returnType instanceof ConditionalTypeForParameter) {
1409: return null;
1410: }
1411:
1412: if ($context->true()) {
1413: $leftType = new ConstantBooleanType(true);
1414: $rightType = new ConstantBooleanType(false);
1415: } elseif ($context->false()) {
1416: $leftType = new ConstantBooleanType(false);
1417: $rightType = new ConstantBooleanType(true);
1418: } elseif ($context->null()) {
1419: $leftType = new MixedType();
1420: $rightType = new NeverType();
1421: } else {
1422: return null;
1423: }
1424:
1425: $argsMap = [];
1426: $parameters = $parametersAcceptor->getParameters();
1427: foreach ($call->getArgs() as $i => $arg) {
1428: if ($arg->unpack) {
1429: continue;
1430: }
1431:
1432: if ($arg->name !== null) {
1433: $paramName = $arg->name->toString();
1434: } elseif (isset($parameters[$i])) {
1435: $paramName = $parameters[$i]->getName();
1436: } else {
1437: continue;
1438: }
1439:
1440: $argsMap['$' . $paramName] = $arg->value;
1441: }
1442:
1443: return $this->getConditionalSpecifiedTypes($returnType, $leftType, $rightType, $scope, $argsMap);
1444: }
1445:
1446: /**
1447: * @param array<string, Expr> $argsMap
1448: */
1449: private function getConditionalSpecifiedTypes(
1450: ConditionalTypeForParameter $conditionalType,
1451: Type $leftType,
1452: Type $rightType,
1453: Scope $scope,
1454: array $argsMap,
1455: ): ?SpecifiedTypes
1456: {
1457: $parameterName = $conditionalType->getParameterName();
1458: if (!array_key_exists($parameterName, $argsMap)) {
1459: return null;
1460: }
1461:
1462: $targetType = $conditionalType->getTarget();
1463: $ifType = $conditionalType->getIf();
1464: $elseType = $conditionalType->getElse();
1465:
1466: if ($leftType->isSuperTypeOf($ifType)->yes() && $rightType->isSuperTypeOf($elseType)->yes()) {
1467: $context = $conditionalType->isNegated() ? TypeSpecifierContext::createFalse() : TypeSpecifierContext::createTrue();
1468: } elseif ($leftType->isSuperTypeOf($elseType)->yes() && $rightType->isSuperTypeOf($ifType)->yes()) {
1469: $context = $conditionalType->isNegated() ? TypeSpecifierContext::createTrue() : TypeSpecifierContext::createFalse();
1470: } else {
1471: return null;
1472: }
1473:
1474: $specifiedTypes = $this->create(
1475: $argsMap[$parameterName],
1476: $targetType,
1477: $context,
1478: $scope,
1479: );
1480:
1481: if ($targetType instanceof ConstantBooleanType) {
1482: if (!$targetType->getValue()) {
1483: $context = $context->negate();
1484: }
1485:
1486: $specifiedTypes = $specifiedTypes->unionWith($this->specifyTypesInCondition($scope, $argsMap[$parameterName], $context));
1487: }
1488:
1489: return $specifiedTypes;
1490: }
1491:
1492: private function specifyTypesFromAsserts(TypeSpecifierContext $context, Expr\CallLike $call, Assertions $assertions, ParametersAcceptor $parametersAcceptor, Scope $scope): ?SpecifiedTypes
1493: {
1494: if ($context->null()) {
1495: $asserts = $assertions->getAsserts();
1496: } elseif ($context->true()) {
1497: $asserts = $assertions->getAssertsIfTrue();
1498: } elseif ($context->false()) {
1499: $asserts = $assertions->getAssertsIfFalse();
1500: } else {
1501: throw new ShouldNotHappenException();
1502: }
1503:
1504: if (count($asserts) === 0) {
1505: return null;
1506: }
1507:
1508: $argsMap = [];
1509: $parameters = $parametersAcceptor->getParameters();
1510: foreach ($call->getArgs() as $i => $arg) {
1511: if ($arg->unpack) {
1512: continue;
1513: }
1514:
1515: if ($arg->name !== null) {
1516: $paramName = $arg->name->toString();
1517: } elseif (isset($parameters[$i])) {
1518: $paramName = $parameters[$i]->getName();
1519: } elseif (count($parameters) > 0 && $parametersAcceptor->isVariadic()) {
1520: $lastParameter = array_last($parameters);
1521: $paramName = $lastParameter->getName();
1522: } else {
1523: continue;
1524: }
1525:
1526: $argsMap[$paramName][] = $arg->value;
1527: }
1528: foreach ($parameters as $parameter) {
1529: $name = $parameter->getName();
1530: $defaultValue = $parameter->getDefaultValue();
1531: if (isset($argsMap[$name]) || $defaultValue === null) {
1532: continue;
1533: }
1534: $argsMap[$name][] = new TypeExpr($defaultValue);
1535: }
1536:
1537: if ($call instanceof MethodCall) {
1538: $argsMap['this'] = [$call->var];
1539: }
1540:
1541: /** @var SpecifiedTypes|null $types */
1542: $types = null;
1543:
1544: foreach ($asserts as $assert) {
1545: foreach ($argsMap[substr($assert->getParameter()->getParameterName(), 1)] ?? [] as $parameterExpr) {
1546: $assertedType = TypeTraverser::map($assert->getType(), static function (Type $type, callable $traverse) use ($argsMap, $scope): Type {
1547: if ($type instanceof ConditionalTypeForParameter) {
1548: $parameterName = substr($type->getParameterName(), 1);
1549: if (array_key_exists($parameterName, $argsMap)) {
1550: $argType = TypeCombinator::union(...array_map(static fn (Expr $expr) => $scope->getType($expr), $argsMap[$parameterName]));
1551: $type = $type->toConditional($argType);
1552: }
1553: }
1554:
1555: return $traverse($type);
1556: });
1557:
1558: $assertExpr = $assert->getParameter()->getExpr($parameterExpr);
1559:
1560: $templateTypeMap = $parametersAcceptor->getResolvedTemplateTypeMap();
1561: $containsUnresolvedTemplate = false;
1562: TypeTraverser::map(
1563: $assert->getOriginalType(),
1564: static function (Type $type, callable $traverse) use ($templateTypeMap, &$containsUnresolvedTemplate) {
1565: if ($type instanceof TemplateType && $type->getScope()->getClassName() !== null) {
1566: $resolvedType = $templateTypeMap->getType($type->getName());
1567: if ($resolvedType === null || $type->getBound()->equals($resolvedType)) {
1568: $containsUnresolvedTemplate = true;
1569: return $type;
1570: }
1571: }
1572:
1573: return $traverse($type);
1574: },
1575: );
1576:
1577: $newTypes = $this->create(
1578: $assertExpr,
1579: $assertedType,
1580: $assert->isNegated() ? TypeSpecifierContext::createFalse() : TypeSpecifierContext::createTrue(),
1581: $scope,
1582: )->setRootExpr($containsUnresolvedTemplate || $assert->isEquality() ? $call : null);
1583: $types = $types !== null ? $types->unionWith($newTypes) : $newTypes;
1584:
1585: if (!$context->null() || !$assertedType instanceof ConstantBooleanType) {
1586: continue;
1587: }
1588:
1589: $subContext = $assertedType->getValue() ? TypeSpecifierContext::createTrue() : TypeSpecifierContext::createFalse();
1590: if ($assert->isNegated()) {
1591: $subContext = $subContext->negate();
1592: }
1593:
1594: $types = $types->unionWith($this->specifyTypesInCondition(
1595: $scope,
1596: $assertExpr,
1597: $subContext,
1598: ));
1599: }
1600: }
1601:
1602: return $types;
1603: }
1604:
1605: /**
1606: * @return array<string, ConditionalExpressionHolder[]>
1607: */
1608: private function processBooleanSureConditionalTypes(Scope $scope, SpecifiedTypes $leftTypes, SpecifiedTypes $rightTypes): array
1609: {
1610: $conditionExpressionTypes = [];
1611: foreach ($leftTypes->getSureTypes() as $exprString => [$expr, $type]) {
1612: if (!$expr instanceof Expr\Variable) {
1613: continue;
1614: }
1615: if (!is_string($expr->name)) {
1616: continue;
1617: }
1618:
1619: $conditionExpressionTypes[$exprString] = ExpressionTypeHolder::createYes(
1620: $expr,
1621: TypeCombinator::remove($scope->getType($expr), $type),
1622: );
1623: }
1624:
1625: if (count($conditionExpressionTypes) > 0) {
1626: $holders = [];
1627: foreach ($rightTypes->getSureTypes() as $exprString => [$expr, $type]) {
1628: if (!$expr instanceof Expr\Variable) {
1629: continue;
1630: }
1631: if (!is_string($expr->name)) {
1632: continue;
1633: }
1634:
1635: if (!isset($holders[$exprString])) {
1636: $holders[$exprString] = [];
1637: }
1638:
1639: $conditions = $conditionExpressionTypes;
1640: foreach ($conditions as $conditionExprString => $conditionExprTypeHolder) {
1641: $conditionExpr = $conditionExprTypeHolder->getExpr();
1642: if (!$conditionExpr instanceof Expr\Variable) {
1643: continue;
1644: }
1645: if (!is_string($conditionExpr->name)) {
1646: continue;
1647: }
1648: if ($conditionExpr->name !== $expr->name) {
1649: continue;
1650: }
1651:
1652: unset($conditions[$conditionExprString]);
1653: }
1654:
1655: if (count($conditions) === 0) {
1656: continue;
1657: }
1658:
1659: $holder = new ConditionalExpressionHolder(
1660: $conditions,
1661: new ExpressionTypeHolder($expr, TypeCombinator::intersect($scope->getType($expr), $type), TrinaryLogic::createYes()),
1662: );
1663: $holders[$exprString][$holder->getKey()] = $holder;
1664: }
1665:
1666: return $holders;
1667: }
1668:
1669: return [];
1670: }
1671:
1672: /**
1673: * @return array<string, ConditionalExpressionHolder[]>
1674: */
1675: private function processBooleanNotSureConditionalTypes(Scope $scope, SpecifiedTypes $leftTypes, SpecifiedTypes $rightTypes): array
1676: {
1677: $conditionExpressionTypes = [];
1678: foreach ($leftTypes->getSureNotTypes() as $exprString => [$expr, $type]) {
1679: if (!$expr instanceof Expr\Variable) {
1680: continue;
1681: }
1682: if (!is_string($expr->name)) {
1683: continue;
1684: }
1685:
1686: $conditionExpressionTypes[$exprString] = ExpressionTypeHolder::createYes(
1687: $expr,
1688: TypeCombinator::intersect($scope->getType($expr), $type),
1689: );
1690: }
1691:
1692: if (count($conditionExpressionTypes) > 0) {
1693: $holders = [];
1694: foreach ($rightTypes->getSureNotTypes() as $exprString => [$expr, $type]) {
1695: if (!$expr instanceof Expr\Variable) {
1696: continue;
1697: }
1698: if (!is_string($expr->name)) {
1699: continue;
1700: }
1701:
1702: if (!isset($holders[$exprString])) {
1703: $holders[$exprString] = [];
1704: }
1705:
1706: $conditions = $conditionExpressionTypes;
1707: foreach ($conditions as $conditionExprString => $conditionExprTypeHolder) {
1708: $conditionExpr = $conditionExprTypeHolder->getExpr();
1709: if (!$conditionExpr instanceof Expr\Variable) {
1710: continue;
1711: }
1712: if (!is_string($conditionExpr->name)) {
1713: continue;
1714: }
1715: if ($conditionExpr->name !== $expr->name) {
1716: continue;
1717: }
1718:
1719: unset($conditions[$conditionExprString]);
1720: }
1721:
1722: if (count($conditions) === 0) {
1723: continue;
1724: }
1725:
1726: $holder = new ConditionalExpressionHolder(
1727: $conditions,
1728: new ExpressionTypeHolder($expr, TypeCombinator::remove($scope->getType($expr), $type), TrinaryLogic::createYes()),
1729: );
1730: $holders[$exprString][$holder->getKey()] = $holder;
1731: }
1732:
1733: return $holders;
1734: }
1735:
1736: return [];
1737: }
1738:
1739: /**
1740: * @return array{Expr, ConstantScalarType, Type}|null
1741: */
1742: private function findTypeExpressionsFromBinaryOperation(Scope $scope, Node\Expr\BinaryOp $binaryOperation): ?array
1743: {
1744: $leftType = $scope->getType($binaryOperation->left);
1745: $rightType = $scope->getType($binaryOperation->right);
1746:
1747: $rightExpr = $binaryOperation->right;
1748: if ($rightExpr instanceof AlwaysRememberedExpr) {
1749: $rightExpr = $rightExpr->getExpr();
1750: }
1751:
1752: $leftExpr = $binaryOperation->left;
1753: if ($leftExpr instanceof AlwaysRememberedExpr) {
1754: $leftExpr = $leftExpr->getExpr();
1755: }
1756:
1757: if (
1758: $leftType instanceof ConstantScalarType
1759: && !$rightExpr instanceof ConstFetch
1760: ) {
1761: return [$binaryOperation->right, $leftType, $rightType];
1762: } elseif (
1763: $rightType instanceof ConstantScalarType
1764: && !$leftExpr instanceof ConstFetch
1765: ) {
1766: return [$binaryOperation->left, $rightType, $leftType];
1767: }
1768:
1769: return null;
1770: }
1771:
1772: /** @api */
1773: public function create(
1774: Expr $expr,
1775: Type $type,
1776: TypeSpecifierContext $context,
1777: Scope $scope,
1778: ): SpecifiedTypes
1779: {
1780: if ($expr instanceof Instanceof_ || $expr instanceof Expr\List_) {
1781: return (new SpecifiedTypes([], []))->setRootExpr($expr);
1782: }
1783:
1784: $specifiedExprs = [];
1785: if ($expr instanceof AlwaysRememberedExpr) {
1786: $specifiedExprs[] = $expr;
1787: $expr = $expr->expr;
1788: }
1789:
1790: if ($expr instanceof Expr\Assign) {
1791: $specifiedExprs[] = $expr->var;
1792: $specifiedExprs[] = $expr->expr;
1793:
1794: while ($expr->expr instanceof Expr\Assign) {
1795: $specifiedExprs[] = $expr->expr->var;
1796: $expr = $expr->expr;
1797: }
1798: } elseif ($expr instanceof Expr\AssignOp\Coalesce) {
1799: $specifiedExprs[] = $expr->var;
1800: } else {
1801: $specifiedExprs[] = $expr;
1802: }
1803:
1804: $types = null;
1805:
1806: foreach ($specifiedExprs as $specifiedExpr) {
1807: $newTypes = $this->createForExpr($specifiedExpr, $type, $context, $scope);
1808:
1809: if ($types === null) {
1810: $types = $newTypes;
1811: } else {
1812: $types = $types->unionWith($newTypes);
1813: }
1814: }
1815:
1816: return $types;
1817: }
1818:
1819: private function createForExpr(
1820: Expr $expr,
1821: Type $type,
1822: TypeSpecifierContext $context,
1823: Scope $scope,
1824: ): SpecifiedTypes
1825: {
1826: if ($context->true()) {
1827: $containsNull = !$type->isNull()->no() && !$scope->getType($expr)->isNull()->no();
1828: } elseif ($context->false()) {
1829: $containsNull = !TypeCombinator::containsNull($type) && !$scope->getType($expr)->isNull()->no();
1830: }
1831:
1832: $originalExpr = $expr;
1833: if (isset($containsNull) && !$containsNull) {
1834: $expr = NullsafeOperatorHelper::getNullsafeShortcircuitedExpr($expr);
1835: }
1836:
1837: if (
1838: !$context->null()
1839: && $expr instanceof Expr\BinaryOp\Coalesce
1840: ) {
1841: $rightIsSuperType = $type->isSuperTypeOf($scope->getType($expr->right));
1842: if (($context->true() && $rightIsSuperType->no()) || ($context->false() && $rightIsSuperType->yes())) {
1843: $expr = $expr->left;
1844: }
1845: }
1846:
1847: if (
1848: $expr instanceof FuncCall
1849: && $expr->name instanceof Name
1850: ) {
1851: $has = $this->reflectionProvider->hasFunction($expr->name, $scope);
1852: if (!$has) {
1853: // backwards compatibility with previous behaviour
1854: return new SpecifiedTypes([], []);
1855: }
1856:
1857: $functionReflection = $this->reflectionProvider->getFunction($expr->name, $scope);
1858: $hasSideEffects = $functionReflection->hasSideEffects();
1859: if ($hasSideEffects->yes()) {
1860: return new SpecifiedTypes([], []);
1861: }
1862:
1863: if (!$this->rememberPossiblyImpureFunctionValues && !$hasSideEffects->no()) {
1864: return new SpecifiedTypes([], []);
1865: }
1866: }
1867:
1868: if (
1869: $expr instanceof MethodCall
1870: && $expr->name instanceof Node\Identifier
1871: ) {
1872: $methodName = $expr->name->toString();
1873: $calledOnType = $scope->getType($expr->var);
1874: $methodReflection = $scope->getMethodReflection($calledOnType, $methodName);
1875: if (
1876: $methodReflection === null
1877: || $methodReflection->hasSideEffects()->yes()
1878: || (!$this->rememberPossiblyImpureFunctionValues && !$methodReflection->hasSideEffects()->no())
1879: ) {
1880: if (isset($containsNull) && !$containsNull) {
1881: return $this->createNullsafeTypes($originalExpr, $scope, $context, $type);
1882: }
1883:
1884: return new SpecifiedTypes([], []);
1885: }
1886: }
1887:
1888: if (
1889: $expr instanceof StaticCall
1890: && $expr->name instanceof Node\Identifier
1891: ) {
1892: $methodName = $expr->name->toString();
1893: if ($expr->class instanceof Name) {
1894: $calledOnType = $scope->resolveTypeByName($expr->class);
1895: } else {
1896: $calledOnType = $scope->getType($expr->class);
1897: }
1898:
1899: $methodReflection = $scope->getMethodReflection($calledOnType, $methodName);
1900: if (
1901: $methodReflection === null
1902: || $methodReflection->hasSideEffects()->yes()
1903: || (!$this->rememberPossiblyImpureFunctionValues && !$methodReflection->hasSideEffects()->no())
1904: ) {
1905: if (isset($containsNull) && !$containsNull) {
1906: return $this->createNullsafeTypes($originalExpr, $scope, $context, $type);
1907: }
1908:
1909: return new SpecifiedTypes([], []);
1910: }
1911: }
1912:
1913: $sureTypes = [];
1914: $sureNotTypes = [];
1915: $exprString = $this->exprPrinter->printExpr($expr);
1916: $originalExprString = $this->exprPrinter->printExpr($originalExpr);
1917: if ($context->false()) {
1918: $sureNotTypes[$exprString] = [$expr, $type];
1919: if ($exprString !== $originalExprString) {
1920: $sureNotTypes[$originalExprString] = [$originalExpr, $type];
1921: }
1922: } elseif ($context->true()) {
1923: $sureTypes[$exprString] = [$expr, $type];
1924: if ($exprString !== $originalExprString) {
1925: $sureTypes[$originalExprString] = [$originalExpr, $type];
1926: }
1927: }
1928:
1929: $types = new SpecifiedTypes($sureTypes, $sureNotTypes);
1930: if (isset($containsNull) && !$containsNull) {
1931: return $this->createNullsafeTypes($originalExpr, $scope, $context, $type)->unionWith($types);
1932: }
1933:
1934: return $types;
1935: }
1936:
1937: private function createNullsafeTypes(Expr $expr, Scope $scope, TypeSpecifierContext $context, ?Type $type): SpecifiedTypes
1938: {
1939: if ($expr instanceof Expr\NullsafePropertyFetch) {
1940: if ($type !== null) {
1941: $propertyFetchTypes = $this->create(new PropertyFetch($expr->var, $expr->name), $type, $context, $scope);
1942: } else {
1943: $propertyFetchTypes = $this->create(new PropertyFetch($expr->var, $expr->name), new NullType(), TypeSpecifierContext::createFalse(), $scope);
1944: }
1945:
1946: return $propertyFetchTypes->unionWith(
1947: $this->create($expr->var, new NullType(), TypeSpecifierContext::createFalse(), $scope),
1948: );
1949: }
1950:
1951: if ($expr instanceof Expr\NullsafeMethodCall) {
1952: if ($type !== null) {
1953: $methodCallTypes = $this->create(new MethodCall($expr->var, $expr->name, $expr->args), $type, $context, $scope);
1954: } else {
1955: $methodCallTypes = $this->create(new MethodCall($expr->var, $expr->name, $expr->args), new NullType(), TypeSpecifierContext::createFalse(), $scope);
1956: }
1957:
1958: return $methodCallTypes->unionWith(
1959: $this->create($expr->var, new NullType(), TypeSpecifierContext::createFalse(), $scope),
1960: );
1961: }
1962:
1963: if ($expr instanceof Expr\PropertyFetch) {
1964: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
1965: }
1966:
1967: if ($expr instanceof Expr\MethodCall) {
1968: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
1969: }
1970:
1971: if ($expr instanceof Expr\ArrayDimFetch) {
1972: return $this->createNullsafeTypes($expr->var, $scope, $context, null);
1973: }
1974:
1975: if ($expr instanceof Expr\StaticPropertyFetch && $expr->class instanceof Expr) {
1976: return $this->createNullsafeTypes($expr->class, $scope, $context, null);
1977: }
1978:
1979: if ($expr instanceof Expr\StaticCall && $expr->class instanceof Expr) {
1980: return $this->createNullsafeTypes($expr->class, $scope, $context, null);
1981: }
1982:
1983: return new SpecifiedTypes([], []);
1984: }
1985:
1986: private function createRangeTypes(?Expr $rootExpr, Expr $expr, Type $type, TypeSpecifierContext $context): SpecifiedTypes
1987: {
1988: $sureNotTypes = [];
1989:
1990: if ($type instanceof IntegerRangeType || $type instanceof ConstantIntegerType) {
1991: $exprString = $this->exprPrinter->printExpr($expr);
1992: if ($context->false()) {
1993: $sureNotTypes[$exprString] = [$expr, $type];
1994: } elseif ($context->true()) {
1995: $inverted = TypeCombinator::remove(new IntegerType(), $type);
1996: $sureNotTypes[$exprString] = [$expr, $inverted];
1997: }
1998: }
1999:
2000: return (new SpecifiedTypes(sureNotTypes: $sureNotTypes))->setRootExpr($rootExpr);
2001: }
2002:
2003: /**
2004: * @return FunctionTypeSpecifyingExtension[]
2005: */
2006: private function getFunctionTypeSpecifyingExtensions(): array
2007: {
2008: return $this->functionTypeSpecifyingExtensions;
2009: }
2010:
2011: /**
2012: * @return MethodTypeSpecifyingExtension[]
2013: */
2014: private function getMethodTypeSpecifyingExtensionsForClass(string $className): array
2015: {
2016: if ($this->methodTypeSpecifyingExtensionsByClass === null) {
2017: $byClass = [];
2018: foreach ($this->methodTypeSpecifyingExtensions as $extension) {
2019: $byClass[$extension->getClass()][] = $extension;
2020: }
2021:
2022: $this->methodTypeSpecifyingExtensionsByClass = $byClass;
2023: }
2024: return $this->getTypeSpecifyingExtensionsForType($this->methodTypeSpecifyingExtensionsByClass, $className);
2025: }
2026:
2027: /**
2028: * @return StaticMethodTypeSpecifyingExtension[]
2029: */
2030: private function getStaticMethodTypeSpecifyingExtensionsForClass(string $className): array
2031: {
2032: if ($this->staticMethodTypeSpecifyingExtensionsByClass === null) {
2033: $byClass = [];
2034: foreach ($this->staticMethodTypeSpecifyingExtensions as $extension) {
2035: $byClass[$extension->getClass()][] = $extension;
2036: }
2037:
2038: $this->staticMethodTypeSpecifyingExtensionsByClass = $byClass;
2039: }
2040: return $this->getTypeSpecifyingExtensionsForType($this->staticMethodTypeSpecifyingExtensionsByClass, $className);
2041: }
2042:
2043: /**
2044: * @param MethodTypeSpecifyingExtension[][]|StaticMethodTypeSpecifyingExtension[][] $extensions
2045: * @return mixed[]
2046: */
2047: private function getTypeSpecifyingExtensionsForType(array $extensions, string $className): array
2048: {
2049: $extensionsForClass = [[]];
2050: $class = $this->reflectionProvider->getClass($className);
2051: foreach (array_merge([$className], $class->getParentClassesNames(), $class->getNativeReflection()->getInterfaceNames()) as $extensionClassName) {
2052: if (!isset($extensions[$extensionClassName])) {
2053: continue;
2054: }
2055:
2056: $extensionsForClass[] = $extensions[$extensionClassName];
2057: }
2058:
2059: return array_merge(...$extensionsForClass);
2060: }
2061:
2062: public function resolveEqual(Expr\BinaryOp\Equal $expr, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
2063: {
2064: $expressions = $this->findTypeExpressionsFromBinaryOperation($scope, $expr);
2065: if ($expressions !== null) {
2066: $exprNode = $expressions[0];
2067: $constantType = $expressions[1];
2068: $otherType = $expressions[2];
2069:
2070: if (!$context->null() && $constantType->getValue() === null) {
2071: $trueTypes = [
2072: new NullType(),
2073: new ConstantBooleanType(false),
2074: new ConstantIntegerType(0),
2075: new ConstantFloatType(0.0),
2076: new ConstantStringType(''),
2077: new ConstantArrayType([], []),
2078: ];
2079: return $this->create($exprNode, new UnionType($trueTypes), $context, $scope)->setRootExpr($expr);
2080: }
2081:
2082: if (!$context->null() && $constantType->getValue() === false) {
2083: return $this->specifyTypesInCondition(
2084: $scope,
2085: $exprNode,
2086: $context->true() ? TypeSpecifierContext::createFalsey() : TypeSpecifierContext::createFalsey()->negate(),
2087: )->setRootExpr($expr);
2088: }
2089:
2090: if (!$context->null() && $constantType->getValue() === true) {
2091: return $this->specifyTypesInCondition(
2092: $scope,
2093: $exprNode,
2094: $context->true() ? TypeSpecifierContext::createTruthy() : TypeSpecifierContext::createTruthy()->negate(),
2095: )->setRootExpr($expr);
2096: }
2097:
2098: if (!$context->null() && $constantType->getValue() === 0 && !$otherType->isInteger()->yes() && !$otherType->isBoolean()->yes()) {
2099: /* There is a difference between php 7.x and 8.x on the equality
2100: * behavior between zero and the empty string, so to be conservative
2101: * we leave it untouched regardless of the language version */
2102: if ($context->true()) {
2103: $trueTypes = [
2104: new NullType(),
2105: new ConstantBooleanType(false),
2106: new ConstantIntegerType(0),
2107: new ConstantFloatType(0.0),
2108: new StringType(),
2109: ];
2110: } else {
2111: $trueTypes = [
2112: new NullType(),
2113: new ConstantBooleanType(false),
2114: new ConstantIntegerType(0),
2115: new ConstantFloatType(0.0),
2116: new ConstantStringType('0'),
2117: ];
2118: }
2119: return $this->create($exprNode, new UnionType($trueTypes), $context, $scope)->setRootExpr($expr);
2120: }
2121:
2122: if (!$context->null() && $constantType->getValue() === '') {
2123: /* There is a difference between php 7.x and 8.x on the equality
2124: * behavior between zero and the empty string, so to be conservative
2125: * we leave it untouched regardless of the language version */
2126: if ($context->true()) {
2127: $trueTypes = [
2128: new NullType(),
2129: new ConstantBooleanType(false),
2130: new ConstantIntegerType(0),
2131: new ConstantFloatType(0.0),
2132: new ConstantStringType(''),
2133: ];
2134: } else {
2135: $trueTypes = [
2136: new NullType(),
2137: new ConstantBooleanType(false),
2138: new ConstantStringType(''),
2139: ];
2140: }
2141: return $this->create($exprNode, new UnionType($trueTypes), $context, $scope)->setRootExpr($expr);
2142: }
2143:
2144: if (
2145: $exprNode instanceof FuncCall
2146: && $exprNode->name instanceof Name
2147: && in_array(strtolower($exprNode->name->toString()), ['gettype', 'get_class', 'get_debug_type'], true)
2148: && isset($exprNode->getArgs()[0])
2149: && $constantType->isString()->yes()
2150: ) {
2151: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
2152: }
2153:
2154: if (
2155: $context->true()
2156: && $exprNode instanceof FuncCall
2157: && $exprNode->name instanceof Name
2158: && $exprNode->name->toLowerString() === 'preg_match'
2159: && (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()
2160: ) {
2161: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
2162: }
2163:
2164: if (
2165: $context->true()
2166: && $exprNode instanceof ClassConstFetch
2167: && $exprNode->name instanceof Node\Identifier
2168: && strtolower($exprNode->name->toString()) === 'class'
2169: && $constantType->isString()->yes()
2170: ) {
2171: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
2172: }
2173: }
2174:
2175: $leftType = $scope->getType($expr->left);
2176: $rightType = $scope->getType($expr->right);
2177:
2178: $leftBooleanType = $leftType->toBoolean();
2179: if ($leftBooleanType instanceof ConstantBooleanType && $rightType->isBoolean()->yes()) {
2180: return $this->specifyTypesInCondition(
2181: $scope,
2182: new Expr\BinaryOp\Identical(
2183: new ConstFetch(new Name($leftBooleanType->getValue() ? 'true' : 'false')),
2184: $expr->right,
2185: ),
2186: $context,
2187: )->setRootExpr($expr);
2188: }
2189:
2190: $rightBooleanType = $rightType->toBoolean();
2191: if ($rightBooleanType instanceof ConstantBooleanType && $leftType->isBoolean()->yes()) {
2192: return $this->specifyTypesInCondition(
2193: $scope,
2194: new Expr\BinaryOp\Identical(
2195: $expr->left,
2196: new ConstFetch(new Name($rightBooleanType->getValue() ? 'true' : 'false')),
2197: ),
2198: $context,
2199: )->setRootExpr($expr);
2200: }
2201:
2202: if (
2203: !$context->null()
2204: && $rightType->isArray()->yes()
2205: && $leftType->isConstantArray()->yes() && $leftType->isIterableAtLeastOnce()->no()
2206: ) {
2207: return $this->create($expr->right, new NonEmptyArrayType(), $context->negate(), $scope)->setRootExpr($expr);
2208: }
2209:
2210: if (
2211: !$context->null()
2212: && $leftType->isArray()->yes()
2213: && $rightType->isConstantArray()->yes() && $rightType->isIterableAtLeastOnce()->no()
2214: ) {
2215: return $this->create($expr->left, new NonEmptyArrayType(), $context->negate(), $scope)->setRootExpr($expr);
2216: }
2217:
2218: if (
2219: ($leftType->isString()->yes() && $rightType->isString()->yes())
2220: || ($leftType->isInteger()->yes() && $rightType->isInteger()->yes())
2221: || ($leftType->isFloat()->yes() && $rightType->isFloat()->yes())
2222: || ($leftType->isEnum()->yes() && $rightType->isEnum()->yes())
2223: ) {
2224: return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
2225: }
2226:
2227: $leftExprString = $this->exprPrinter->printExpr($expr->left);
2228: $rightExprString = $this->exprPrinter->printExpr($expr->right);
2229: if ($leftExprString === $rightExprString) {
2230: if (!$expr->left instanceof Expr\Variable || !$expr->right instanceof Expr\Variable) {
2231: return (new SpecifiedTypes([], []))->setRootExpr($expr);
2232: }
2233: }
2234:
2235: $leftTypes = $this->create($expr->left, $leftType, $context, $scope)->setRootExpr($expr);
2236: $rightTypes = $this->create($expr->right, $rightType, $context, $scope)->setRootExpr($expr);
2237:
2238: return $context->true()
2239: ? $leftTypes->unionWith($rightTypes)
2240: : $leftTypes->normalize($scope)->intersectWith($rightTypes->normalize($scope));
2241: }
2242:
2243: public function resolveIdentical(Expr\BinaryOp\Identical $expr, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
2244: {
2245: // Normalize to: fn() === expr
2246: $leftExpr = $expr->left;
2247: $rightExpr = $expr->right;
2248: if ($rightExpr instanceof FuncCall && !$leftExpr instanceof FuncCall) {
2249: [$leftExpr, $rightExpr] = [$rightExpr, $leftExpr];
2250: }
2251:
2252: $unwrappedLeftExpr = $leftExpr;
2253: if ($leftExpr instanceof AlwaysRememberedExpr) {
2254: $unwrappedLeftExpr = $leftExpr->getExpr();
2255: }
2256: $unwrappedRightExpr = $rightExpr;
2257: if ($rightExpr instanceof AlwaysRememberedExpr) {
2258: $unwrappedRightExpr = $rightExpr->getExpr();
2259: }
2260:
2261: $rightType = $scope->getType($rightExpr);
2262:
2263: // (count($a) === $b)
2264: if (
2265: !$context->null()
2266: && $unwrappedLeftExpr instanceof FuncCall
2267: && count($unwrappedLeftExpr->getArgs()) >= 1
2268: && $unwrappedLeftExpr->name instanceof Name
2269: && in_array(strtolower((string) $unwrappedLeftExpr->name), ['count', 'sizeof'], true)
2270: && $rightType->isInteger()->yes()
2271: ) {
2272: if (IntegerRangeType::fromInterval(null, -1)->isSuperTypeOf($rightType)->yes()) {
2273: return $this->create($unwrappedLeftExpr->getArgs()[0]->value, new NeverType(), $context, $scope)->setRootExpr($expr);
2274: }
2275:
2276: $argType = $scope->getType($unwrappedLeftExpr->getArgs()[0]->value);
2277: $isZero = (new ConstantIntegerType(0))->isSuperTypeOf($rightType);
2278: if ($isZero->yes()) {
2279: $funcTypes = $this->create($unwrappedLeftExpr, $rightType, $context, $scope)->setRootExpr($expr);
2280:
2281: if ($context->truthy() && !$argType->isArray()->yes()) {
2282: $newArgType = new UnionType([
2283: new ObjectType(Countable::class),
2284: new ConstantArrayType([], []),
2285: ]);
2286: } else {
2287: $newArgType = new ConstantArrayType([], []);
2288: }
2289:
2290: return $funcTypes->unionWith(
2291: $this->create($unwrappedLeftExpr->getArgs()[0]->value, $newArgType, $context, $scope)->setRootExpr($expr),
2292: );
2293: }
2294:
2295: $specifiedTypes = $this->specifyTypesForCountFuncCall($unwrappedLeftExpr, $argType, $rightType, $context, $scope, $expr);
2296: if ($specifiedTypes !== null) {
2297: return $specifiedTypes;
2298: }
2299:
2300: if ($context->truthy() && $argType->isArray()->yes()) {
2301: $funcTypes = $this->create($unwrappedLeftExpr, $rightType, $context, $scope)->setRootExpr($expr);
2302: if (IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($rightType)->yes()) {
2303: return $funcTypes->unionWith(
2304: $this->create($unwrappedLeftExpr->getArgs()[0]->value, new NonEmptyArrayType(), $context, $scope)->setRootExpr($expr),
2305: );
2306: }
2307:
2308: return $funcTypes;
2309: }
2310: }
2311:
2312: // strlen($a) === $b
2313: if (
2314: !$context->null()
2315: && $unwrappedLeftExpr instanceof FuncCall
2316: && count($unwrappedLeftExpr->getArgs()) === 1
2317: && $unwrappedLeftExpr->name instanceof Name
2318: && in_array(strtolower((string) $unwrappedLeftExpr->name), ['strlen', 'mb_strlen'], true)
2319: && $rightType->isInteger()->yes()
2320: ) {
2321: if (IntegerRangeType::fromInterval(null, -1)->isSuperTypeOf($rightType)->yes()) {
2322: return $this->create($unwrappedLeftExpr->getArgs()[0]->value, new NeverType(), $context, $scope)->setRootExpr($expr);
2323: }
2324:
2325: $isZero = (new ConstantIntegerType(0))->isSuperTypeOf($rightType);
2326: if ($isZero->yes()) {
2327: $funcTypes = $this->create($unwrappedLeftExpr, $rightType, $context, $scope)->setRootExpr($expr);
2328: return $funcTypes->unionWith(
2329: $this->create($unwrappedLeftExpr->getArgs()[0]->value, new ConstantStringType(''), $context, $scope)->setRootExpr($expr),
2330: );
2331: }
2332:
2333: if ($context->truthy() && IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($rightType)->yes()) {
2334: $argType = $scope->getType($unwrappedLeftExpr->getArgs()[0]->value);
2335: if ($argType->isString()->yes()) {
2336: $funcTypes = $this->create($unwrappedLeftExpr, $rightType, $context, $scope)->setRootExpr($expr);
2337:
2338: $accessory = new AccessoryNonEmptyStringType();
2339: if (IntegerRangeType::fromInterval(2, null)->isSuperTypeOf($rightType)->yes()) {
2340: $accessory = new AccessoryNonFalsyStringType();
2341: }
2342: $valueTypes = $this->create($unwrappedLeftExpr->getArgs()[0]->value, $accessory, $context, $scope)->setRootExpr($expr);
2343:
2344: return $funcTypes->unionWith($valueTypes);
2345: }
2346: }
2347: }
2348:
2349: // preg_match($a) === $b
2350: if (
2351: $context->true()
2352: && $unwrappedLeftExpr instanceof FuncCall
2353: && $unwrappedLeftExpr->name instanceof Name
2354: && $unwrappedLeftExpr->name->toLowerString() === 'preg_match'
2355: && (new ConstantIntegerType(1))->isSuperTypeOf($rightType)->yes()
2356: ) {
2357: return $this->specifyTypesInCondition(
2358: $scope,
2359: $leftExpr,
2360: $context,
2361: )->setRootExpr($expr);
2362: }
2363:
2364: // get_class($a) === 'Foo'
2365: if (
2366: $context->true()
2367: && $unwrappedLeftExpr instanceof FuncCall
2368: && $unwrappedLeftExpr->name instanceof Name
2369: && in_array(strtolower($unwrappedLeftExpr->name->toString()), ['get_class', 'get_debug_type'], true)
2370: && isset($unwrappedLeftExpr->getArgs()[0])
2371: ) {
2372: if ($rightType instanceof ConstantStringType && $this->reflectionProvider->hasClass($rightType->getValue())) {
2373: return $this->create(
2374: $unwrappedLeftExpr->getArgs()[0]->value,
2375: new ObjectType($rightType->getValue(), classReflection: $this->reflectionProvider->getClass($rightType->getValue())->asFinal()),
2376: $context,
2377: $scope,
2378: )->unionWith($this->create($leftExpr, $rightType, $context, $scope))->setRootExpr($expr);
2379: }
2380: if ($rightType->getClassStringObjectType()->isObject()->yes()) {
2381: return $this->create(
2382: $unwrappedLeftExpr->getArgs()[0]->value,
2383: $rightType->getClassStringObjectType(),
2384: $context,
2385: $scope,
2386: )->unionWith($this->create($leftExpr, $rightType, $context, $scope))->setRootExpr($expr);
2387: }
2388: }
2389:
2390: if (
2391: $context->truthy()
2392: && $unwrappedLeftExpr instanceof FuncCall
2393: && $unwrappedLeftExpr->name instanceof Name
2394: && in_array(strtolower($unwrappedLeftExpr->name->toString()), [
2395: 'substr', 'strstr', 'stristr', 'strchr', 'strrchr', 'strtolower', 'strtoupper', 'ucfirst', 'lcfirst',
2396: 'mb_substr', 'mb_strstr', 'mb_stristr', 'mb_strchr', 'mb_strrchr', 'mb_strtolower', 'mb_strtoupper', 'mb_ucfirst', 'mb_lcfirst',
2397: 'ucwords', 'mb_convert_case', 'mb_convert_kana',
2398: ], true)
2399: && isset($unwrappedLeftExpr->getArgs()[0])
2400: && $rightType->isNonEmptyString()->yes()
2401: ) {
2402: $argType = $scope->getType($unwrappedLeftExpr->getArgs()[0]->value);
2403:
2404: if ($argType->isString()->yes()) {
2405: if ($rightType->isNonFalsyString()->yes()) {
2406: return $this->create(
2407: $unwrappedLeftExpr->getArgs()[0]->value,
2408: TypeCombinator::intersect($argType, new AccessoryNonFalsyStringType()),
2409: $context,
2410: $scope,
2411: )->setRootExpr($expr);
2412: }
2413:
2414: return $this->create(
2415: $unwrappedLeftExpr->getArgs()[0]->value,
2416: TypeCombinator::intersect($argType, new AccessoryNonEmptyStringType()),
2417: $context,
2418: $scope,
2419: )->setRootExpr($expr);
2420: }
2421: }
2422:
2423: if ($rightType->isString()->yes()) {
2424: $types = null;
2425: foreach ($rightType->getConstantStrings() as $constantString) {
2426: $specifiedType = $this->specifyTypesForConstantStringBinaryExpression($unwrappedLeftExpr, $constantString, $context, $scope, $expr);
2427:
2428: if ($specifiedType === null) {
2429: continue;
2430: }
2431: if ($types === null) {
2432: $types = $specifiedType;
2433: continue;
2434: }
2435:
2436: $types = $types->intersectWith($specifiedType);
2437: }
2438:
2439: if ($types !== null) {
2440: if ($leftExpr !== $unwrappedLeftExpr) {
2441: $types = $types->unionWith($this->create($leftExpr, $rightType, $context, $scope)->setRootExpr($expr));
2442: }
2443: return $types;
2444: }
2445: }
2446:
2447: $expressions = $this->findTypeExpressionsFromBinaryOperation($scope, $expr);
2448: if ($expressions !== null) {
2449: $exprNode = $expressions[0];
2450: $constantType = $expressions[1];
2451:
2452: $unwrappedExprNode = $exprNode;
2453: if ($exprNode instanceof AlwaysRememberedExpr) {
2454: $unwrappedExprNode = $exprNode->getExpr();
2455: }
2456:
2457: $specifiedType = $this->specifyTypesForConstantBinaryExpression($unwrappedExprNode, $constantType, $context, $scope, $expr);
2458: if ($specifiedType !== null) {
2459: if ($exprNode !== $unwrappedExprNode) {
2460: $specifiedType = $specifiedType->unionWith(
2461: $this->create($exprNode, $constantType, $context, $scope)->setRootExpr($expr),
2462: );
2463: }
2464: return $specifiedType;
2465: }
2466: }
2467:
2468: // $a::class === 'Foo'
2469: if (
2470: $context->true() &&
2471: $unwrappedLeftExpr instanceof ClassConstFetch &&
2472: $unwrappedLeftExpr->class instanceof Expr &&
2473: $unwrappedLeftExpr->name instanceof Node\Identifier &&
2474: $unwrappedRightExpr instanceof ClassConstFetch &&
2475: $rightType instanceof ConstantStringType &&
2476: $rightType->getValue() !== '' &&
2477: strtolower($unwrappedLeftExpr->name->toString()) === 'class'
2478: ) {
2479: if ($this->reflectionProvider->hasClass($rightType->getValue())) {
2480: return $this->create(
2481: $unwrappedLeftExpr->class,
2482: new ObjectType($rightType->getValue(), classReflection: $this->reflectionProvider->getClass($rightType->getValue())->asFinal()),
2483: $context,
2484: $scope,
2485: )->unionWith($this->create($leftExpr, $rightType, $context, $scope))->setRootExpr($expr);
2486: }
2487: return $this->specifyTypesInCondition(
2488: $scope,
2489: new Instanceof_(
2490: $unwrappedLeftExpr->class,
2491: new Name($rightType->getValue()),
2492: ),
2493: $context,
2494: )->unionWith($this->create($leftExpr, $rightType, $context, $scope))->setRootExpr($expr);
2495: }
2496:
2497: $leftType = $scope->getType($leftExpr);
2498:
2499: // 'Foo' === $a::class
2500: if (
2501: $context->true() &&
2502: $unwrappedRightExpr instanceof ClassConstFetch &&
2503: $unwrappedRightExpr->class instanceof Expr &&
2504: $unwrappedRightExpr->name instanceof Node\Identifier &&
2505: $unwrappedLeftExpr instanceof ClassConstFetch &&
2506: $leftType instanceof ConstantStringType &&
2507: $leftType->getValue() !== '' &&
2508: strtolower($unwrappedRightExpr->name->toString()) === 'class'
2509: ) {
2510: if ($this->reflectionProvider->hasClass($leftType->getValue())) {
2511: return $this->create(
2512: $unwrappedRightExpr->class,
2513: new ObjectType($leftType->getValue(), classReflection: $this->reflectionProvider->getClass($leftType->getValue())->asFinal()),
2514: $context,
2515: $scope,
2516: )->unionWith($this->create($rightExpr, $leftType, $context, $scope)->setRootExpr($expr));
2517: }
2518:
2519: return $this->specifyTypesInCondition(
2520: $scope,
2521: new Instanceof_(
2522: $unwrappedRightExpr->class,
2523: new Name($leftType->getValue()),
2524: ),
2525: $context,
2526: )->unionWith($this->create($rightExpr, $leftType, $context, $scope)->setRootExpr($expr));
2527: }
2528:
2529: if ($context->false()) {
2530: $identicalType = $scope->getType($expr);
2531: if ($identicalType instanceof ConstantBooleanType) {
2532: $never = new NeverType();
2533: $contextForTypes = $identicalType->getValue() ? $context->negate() : $context;
2534: $leftTypes = $this->create($leftExpr, $never, $contextForTypes, $scope)->setRootExpr($expr);
2535: $rightTypes = $this->create($rightExpr, $never, $contextForTypes, $scope)->setRootExpr($expr);
2536: if ($leftExpr instanceof AlwaysRememberedExpr) {
2537: $leftTypes = $leftTypes->unionWith(
2538: $this->create($unwrappedLeftExpr, $never, $contextForTypes, $scope)->setRootExpr($expr),
2539: );
2540: }
2541: if ($rightExpr instanceof AlwaysRememberedExpr) {
2542: $rightTypes = $rightTypes->unionWith(
2543: $this->create($unwrappedRightExpr, $never, $contextForTypes, $scope)->setRootExpr($expr),
2544: );
2545: }
2546: return $leftTypes->unionWith($rightTypes);
2547: }
2548: }
2549:
2550: $types = null;
2551: if (
2552: count($leftType->getFiniteTypes()) === 1
2553: || (
2554: $context->true()
2555: && $leftType->isConstantValue()->yes()
2556: && !$rightType->equals($leftType)
2557: && $rightType->isSuperTypeOf($leftType)->yes())
2558: ) {
2559: $types = $this->create(
2560: $rightExpr,
2561: $leftType,
2562: $context,
2563: $scope,
2564: )->setRootExpr($expr);
2565: if ($rightExpr instanceof AlwaysRememberedExpr) {
2566: $types = $types->unionWith($this->create(
2567: $unwrappedRightExpr,
2568: $leftType,
2569: $context,
2570: $scope,
2571: ))->setRootExpr($expr);
2572: }
2573: }
2574: if (
2575: count($rightType->getFiniteTypes()) === 1
2576: || (
2577: $context->true()
2578: && $rightType->isConstantValue()->yes()
2579: && !$leftType->equals($rightType)
2580: && $leftType->isSuperTypeOf($rightType)->yes()
2581: )
2582: ) {
2583: $leftTypes = $this->create(
2584: $leftExpr,
2585: $rightType,
2586: $context,
2587: $scope,
2588: )->setRootExpr($expr);
2589: if ($leftExpr instanceof AlwaysRememberedExpr) {
2590: $leftTypes = $leftTypes->unionWith($this->create(
2591: $unwrappedLeftExpr,
2592: $rightType,
2593: $context,
2594: $scope,
2595: ))->setRootExpr($expr);
2596: }
2597: if ($types !== null) {
2598: $types = $types->unionWith($leftTypes);
2599: } else {
2600: $types = $leftTypes;
2601: }
2602: }
2603:
2604: if ($types !== null) {
2605: return $types;
2606: }
2607:
2608: $leftExprString = $this->exprPrinter->printExpr($unwrappedLeftExpr);
2609: $rightExprString = $this->exprPrinter->printExpr($unwrappedRightExpr);
2610: if ($leftExprString === $rightExprString) {
2611: if (!$unwrappedLeftExpr instanceof Expr\Variable || !$unwrappedRightExpr instanceof Expr\Variable) {
2612: return (new SpecifiedTypes([], []))->setRootExpr($expr);
2613: }
2614: }
2615:
2616: if ($context->true()) {
2617: $leftTypes = $this->create($leftExpr, $rightType, $context, $scope)->setRootExpr($expr);
2618: $rightTypes = $this->create($rightExpr, $leftType, $context, $scope)->setRootExpr($expr);
2619: if ($leftExpr instanceof AlwaysRememberedExpr) {
2620: $leftTypes = $leftTypes->unionWith(
2621: $this->create($unwrappedLeftExpr, $rightType, $context, $scope)->setRootExpr($expr),
2622: );
2623: }
2624: if ($rightExpr instanceof AlwaysRememberedExpr) {
2625: $rightTypes = $rightTypes->unionWith(
2626: $this->create($unwrappedRightExpr, $leftType, $context, $scope)->setRootExpr($expr),
2627: );
2628: }
2629: return $leftTypes->unionWith($rightTypes);
2630: } elseif ($context->false()) {
2631: return $this->create($leftExpr, $leftType, $context, $scope)->setRootExpr($expr)->normalize($scope)
2632: ->intersectWith($this->create($rightExpr, $rightType, $context, $scope)->setRootExpr($expr)->normalize($scope));
2633: }
2634:
2635: return (new SpecifiedTypes([], []))->setRootExpr($expr);
2636: }
2637:
2638: }
2639: