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