1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Reflection;
4:
5: use Closure;
6: use PhpParser\Node\Arg;
7: use PhpParser\Node\ArgPlaceholder;
8: use PhpParser\Node\ComplexType;
9: use PhpParser\Node\Expr;
10: use PhpParser\Node\Expr\BinaryOp;
11: use PhpParser\Node\Expr\Cast\Array_;
12: use PhpParser\Node\Expr\Cast\Bool_;
13: use PhpParser\Node\Expr\Cast\Double;
14: use PhpParser\Node\Expr\Cast\Object_;
15: use PhpParser\Node\Expr\ClassConstFetch;
16: use PhpParser\Node\Expr\ConstFetch;
17: use PhpParser\Node\Expr\FuncCall;
18: use PhpParser\Node\Expr\New_;
19: use PhpParser\Node\Expr\PropertyFetch;
20: use PhpParser\Node\Expr\Variable;
21: use PhpParser\Node\Identifier;
22: use PhpParser\Node\Name;
23: use PhpParser\Node\Param;
24: use PhpParser\Node\Scalar\Float_;
25: use PhpParser\Node\Scalar\Int_;
26: use PhpParser\Node\Scalar\MagicConst;
27: use PhpParser\Node\Scalar\MagicConst\Dir;
28: use PhpParser\Node\Scalar\MagicConst\File;
29: use PhpParser\Node\Scalar\MagicConst\Line;
30: use PhpParser\Node\Scalar\String_;
31: use PhpParser\Node\VariadicPlaceholder;
32: use PHPStan\Analyser\ConstantResolver;
33: use PHPStan\Analyser\OutOfClassScope;
34: use PHPStan\Analyser\ValueDependencyCollector;
35: use PHPStan\DependencyInjection\AutowiredParameter;
36: use PHPStan\DependencyInjection\AutowiredService;
37: use PHPStan\Node\Expr\TypeExpr;
38: use PHPStan\Php\PhpVersion;
39: use PHPStan\Php\PhpVersions;
40: use PHPStan\PhpDoc\Tag\TemplateTag;
41: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
42: use PHPStan\Reflection\Callables\SimpleImpurePoint;
43: use PHPStan\Reflection\Callables\SimpleThrowPoint;
44: use PHPStan\Reflection\Native\NativeParameterReflection;
45: use PHPStan\Reflection\Php\ExtendedDummyParameter;
46: use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider;
47: use PHPStan\ShouldNotHappenException;
48: use PHPStan\TrinaryLogic;
49: use PHPStan\Turbo\ShadowedByTurboExtension;
50: use PHPStan\Type\Accessory\AccessoryArrayListType;
51: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
52: use PHPStan\Type\Accessory\HasOffsetValueType;
53: use PHPStan\Type\ArrayType;
54: use PHPStan\Type\BooleanType;
55: use PHPStan\Type\CallableAssertionsHelper;
56: use PHPStan\Type\ClassStringType;
57: use PHPStan\Type\ClosureOrigin;
58: use PHPStan\Type\ClosureType;
59: use PHPStan\Type\Constant\ConstantArrayType;
60: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
61: use PHPStan\Type\Constant\ConstantBooleanType;
62: use PHPStan\Type\Constant\ConstantFloatType;
63: use PHPStan\Type\Constant\ConstantIntegerType;
64: use PHPStan\Type\Constant\ConstantStringType;
65: use PHPStan\Type\Constant\OversizedArrayBuilder;
66: use PHPStan\Type\ConstantScalarType;
67: use PHPStan\Type\Enum\EnumCaseObjectType;
68: use PHPStan\Type\ErrorType;
69: use PHPStan\Type\FloatType;
70: use PHPStan\Type\GeneralizePrecision;
71: use PHPStan\Type\Generic\GenericClassStringType;
72: use PHPStan\Type\Generic\GenericStaticType;
73: use PHPStan\Type\Generic\TemplateType;
74: use PHPStan\Type\Generic\TemplateTypeMap;
75: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
76: use PHPStan\Type\IntegerRangeType;
77: use PHPStan\Type\IntegerType;
78: use PHPStan\Type\IntersectionType;
79: use PHPStan\Type\MixedType;
80: use PHPStan\Type\NeverType;
81: use PHPStan\Type\NonexistentParentClassType;
82: use PHPStan\Type\NullType;
83: use PHPStan\Type\ObjectShapeType;
84: use PHPStan\Type\ObjectType;
85: use PHPStan\Type\ObjectWithoutClassType;
86: use PHPStan\Type\OperatorTypeSpecifyingExtensionRegistry;
87: use PHPStan\Type\ParserNodeTypeToPHPStanType;
88: use PHPStan\Type\StaticType;
89: use PHPStan\Type\StringSet;
90: use PHPStan\Type\StringType;
91: use PHPStan\Type\ThisType;
92: use PHPStan\Type\Type;
93: use PHPStan\Type\TypeCombinator;
94: use PHPStan\Type\TypehintHelper;
95: use PHPStan\Type\TypeResult;
96: use PHPStan\Type\TypeTraverser;
97: use PHPStan\Type\TypeWithClassName;
98: use PHPStan\Type\UnaryOperatorTypeSpecifyingExtensionRegistry;
99: use PHPStan\Type\UnionType;
100: use PHPStan\Type\ValueSet;
101: use stdClass;
102: use Throwable;
103: use function array_key_exists;
104: use function array_keys;
105: use function array_map;
106: use function array_merge;
107: use function array_slice;
108: use function array_values;
109: use function count;
110: use function dirname;
111: use function in_array;
112: use function is_string;
113: use function sprintf;
114: use function strtolower;
115:
116: #[AutowiredService]
117: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/InitializerExprTypeResolver.cpp')]
118: final class InitializerExprTypeResolver
119: {
120:
121: public const CALCULATE_SCALARS_LIMIT = 128;
122:
123: /** @var array<string, true> */
124: private array $currentlyResolvingClassConstant = [];
125:
126: /** @var array<string, Type> */
127: private array $classConstantValueTypeCache = [];
128:
129: public function __construct(
130: private ConstantResolver $constantResolver,
131: private ReflectionProviderProvider $reflectionProviderProvider,
132: private PhpVersion $phpVersion,
133: private OperatorTypeSpecifyingExtensionRegistry $operatorTypeSpecifyingExtensionRegistry,
134: private UnaryOperatorTypeSpecifyingExtensionRegistry $unaryOperatorTypeSpecifyingExtensionRegistry,
135: private OversizedArrayBuilder $oversizedArrayBuilder,
136: #[AutowiredParameter]
137: private bool $usePathConstantsAsConstantString,
138: private ValueDependencyCollector $valueDependencyCollector,
139: )
140: {
141: }
142:
143: /** @api */
144: public function getType(Expr $expr, InitializerExprContext $context): Type
145: {
146: if ($expr instanceof TypeExpr) {
147: return $expr->getExprType();
148: }
149: if ($expr instanceof Int_) {
150: return new ConstantIntegerType($expr->value);
151: }
152: if ($expr instanceof Float_) {
153: return new ConstantFloatType($expr->value);
154: }
155: if ($expr instanceof String_) {
156: return new ConstantStringType($expr->value);
157: }
158: if ($expr instanceof ConstFetch) {
159: $constName = (string) $expr->name;
160: $loweredConstName = strtolower($constName);
161: if ($loweredConstName === 'true') {
162: return new ConstantBooleanType(true);
163: } elseif ($loweredConstName === 'false') {
164: return new ConstantBooleanType(false);
165: } elseif ($loweredConstName === 'null') {
166: return new NullType();
167: }
168:
169: $constant = $this->constantResolver->resolveConstant($expr->name, $context);
170: if ($constant !== null) {
171: return $constant;
172: }
173:
174: return new ErrorType();
175: }
176: if ($expr instanceof File) {
177: $file = $context->getFile();
178: if ($file === null) {
179: return new StringType();
180: }
181: $stringType = new ConstantStringType($file);
182: return $this->usePathConstantsAsConstantString ? $stringType : $stringType->generalize(GeneralizePrecision::moreSpecific());
183: }
184: if ($expr instanceof Dir) {
185: $file = $context->getFile();
186: if ($file === null) {
187: return new StringType();
188: }
189: $stringType = new ConstantStringType(dirname($file));
190: return $this->usePathConstantsAsConstantString ? $stringType : $stringType->generalize(GeneralizePrecision::moreSpecific());
191: }
192: if ($expr instanceof Line) {
193: return new ConstantIntegerType($expr->getStartLine());
194: }
195: if ($expr instanceof Expr\New_) {
196: if ($expr->class instanceof Name) {
197: return new ObjectType((string) $expr->class);
198: }
199:
200: return new ObjectWithoutClassType();
201: }
202: if ($expr instanceof Expr\Array_) {
203: return $this->getArrayType($expr, fn (Expr $expr): Type => $this->getType($expr, $context));
204: }
205: if ($expr instanceof Expr\Cast) {
206: return $this->getCastType($expr, fn (Expr $expr): Type => $this->getType($expr, $context));
207: }
208: if ($expr instanceof Expr\CallLike && $expr->isPartialFunctionApplication()) {
209: return $this->getFirstClassCallableType($expr, $context, false);
210: }
211: if ($expr instanceof Expr\Closure && $expr->static) {
212: $parameters = [];
213: $isVariadic = false;
214: $firstOptionalParameterIndex = null;
215: foreach ($expr->params as $i => $param) {
216: $isOptionalCandidate = $param->default !== null || $param->variadic;
217:
218: if ($isOptionalCandidate) {
219: if ($firstOptionalParameterIndex === null) {
220: $firstOptionalParameterIndex = $i;
221: }
222: } else {
223: $firstOptionalParameterIndex = null;
224: }
225: }
226:
227: foreach ($expr->params as $i => $param) {
228: if ($param->variadic) {
229: $isVariadic = true;
230: }
231: if (!$param->var instanceof Variable || !is_string($param->var->name)) {
232: throw new ShouldNotHappenException();
233: }
234: $parameters[] = new NativeParameterReflection(
235: $param->var->name,
236: $firstOptionalParameterIndex !== null && $i >= $firstOptionalParameterIndex,
237: $this->getFunctionType($param->type, $this->isParameterValueNullable($param), false, $context),
238: $param->byRef
239: ? PassedByReference::createCreatesNewVariable()
240: : PassedByReference::createNo(),
241: $param->variadic,
242: $param->default !== null ? $this->getType($param->default, $context) : null,
243: );
244: }
245:
246: $returnType = new MixedType(false);
247: if ($expr->returnType !== null) {
248: $returnType = $this->getFunctionType($expr->returnType, false, false, $context);
249: }
250:
251: return new ClosureType(
252: $parameters,
253: $returnType,
254: $isVariadic,
255: TemplateTypeMap::createEmpty(),
256: TemplateTypeMap::createEmpty(),
257: TemplateTypeVarianceMap::createEmpty(),
258: acceptsNamedArguments: TrinaryLogic::createYes(),
259: isStatic: TrinaryLogic::createYes(),
260: );
261: }
262: if ($expr instanceof Expr\ArrayDimFetch && $expr->dim !== null) {
263: $var = $this->getType($expr->var, $context);
264: $dim = $this->getType($expr->dim, $context);
265: return $var->getOffsetValueType($dim);
266: }
267: if ($expr instanceof ClassConstFetch && $expr->name instanceof Identifier) {
268: return $this->getClassConstFetchType($expr->class, $expr->name->toString(), $context->getClassName(), fn (Expr $expr): Type => $this->getType($expr, $context));
269: }
270: if ($expr instanceof Expr\UnaryPlus) {
271: return $this->getUnaryPlusType($expr->expr, fn (Expr $expr): Type => $this->getType($expr, $context));
272: }
273: if ($expr instanceof Expr\UnaryMinus) {
274: return $this->getUnaryMinusType($expr->expr, fn (Expr $expr): Type => $this->getType($expr, $context));
275: }
276: if ($expr instanceof Expr\BinaryOp\Coalesce) {
277: $leftType = $this->getType($expr->left, $context);
278: $rightType = $this->getType($expr->right, $context);
279:
280: return TypeCombinator::union(TypeCombinator::removeNull($leftType), $rightType);
281: }
282:
283: if ($expr instanceof Expr\Ternary) {
284: $elseType = $this->getType($expr->else, $context);
285: if ($expr->if === null) {
286: $condType = $this->getType($expr->cond, $context);
287:
288: return TypeCombinator::union(
289: TypeCombinator::removeFalsey($condType),
290: $elseType,
291: );
292: }
293:
294: $ifType = $this->getType($expr->if, $context);
295:
296: return TypeCombinator::union(
297: TypeCombinator::removeFalsey($ifType),
298: $elseType,
299: );
300: }
301:
302: if ($expr instanceof Expr\FuncCall && $expr->name instanceof Name && $expr->name->toLowerString() === 'constant') {
303: $firstArg = $expr->args[0] ?? null;
304: if ($firstArg instanceof Arg && $firstArg->value instanceof String_) {
305: $constant = $this->constantResolver->resolvePredefinedConstant($firstArg->value->value);
306: if ($constant !== null) {
307: return $constant;
308: }
309: }
310: }
311:
312: if ($expr instanceof Expr\BooleanNot) {
313: $exprBooleanType = $this->getType($expr->expr, $context)->toBoolean();
314:
315: if ($exprBooleanType instanceof ConstantBooleanType) {
316: return new ConstantBooleanType(!$exprBooleanType->getValue());
317: }
318:
319: return new BooleanType();
320: }
321:
322: if ($expr instanceof Expr\BitwiseNot) {
323: return $this->getBitwiseNotType($expr->expr, fn (Expr $expr): Type => $this->getType($expr, $context));
324: }
325:
326: if ($expr instanceof Expr\BinaryOp\Concat) {
327: return $this->getConcatType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
328: }
329:
330: if ($expr instanceof Expr\BinaryOp\BitwiseAnd) {
331: return $this->getBitwiseAndType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
332: }
333:
334: if ($expr instanceof Expr\BinaryOp\BitwiseOr) {
335: return $this->getBitwiseOrType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
336: }
337:
338: if ($expr instanceof Expr\BinaryOp\BitwiseXor) {
339: return $this->getBitwiseXorType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
340: }
341:
342: if ($expr instanceof Expr\BinaryOp\Spaceship) {
343: return $this->getSpaceshipType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
344: }
345:
346: if (
347: $expr instanceof Expr\BinaryOp\BooleanAnd
348: || $expr instanceof Expr\BinaryOp\LogicalAnd
349: || $expr instanceof Expr\BinaryOp\BooleanOr
350: || $expr instanceof Expr\BinaryOp\LogicalOr
351: ) {
352: return new BooleanType();
353: }
354:
355: if ($expr instanceof Expr\BinaryOp\Div) {
356: return $this->getDivType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
357: }
358:
359: if ($expr instanceof Expr\BinaryOp\Mod) {
360: return $this->getModType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
361: }
362:
363: if ($expr instanceof Expr\BinaryOp\Plus) {
364: return $this->getPlusType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
365: }
366:
367: if ($expr instanceof Expr\BinaryOp\Minus) {
368: return $this->getMinusType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
369: }
370:
371: if ($expr instanceof Expr\BinaryOp\Mul) {
372: return $this->getMulType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
373: }
374:
375: if ($expr instanceof Expr\BinaryOp\Pow) {
376: return $this->getPowType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
377: }
378:
379: if ($expr instanceof Expr\BinaryOp\ShiftLeft) {
380: return $this->getShiftLeftType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
381: }
382:
383: if ($expr instanceof Expr\BinaryOp\ShiftRight) {
384: return $this->getShiftRightType($expr->left, $expr->right, fn (Expr $expr): Type => $this->getType($expr, $context));
385: }
386:
387: if ($expr instanceof BinaryOp\Identical) {
388: return $this->resolveIdenticalType(
389: $this->getType($expr->left, $context),
390: $this->getType($expr->right, $context),
391: )->type;
392: }
393:
394: if ($expr instanceof BinaryOp\NotIdentical) {
395: return $this->getType(new Expr\BooleanNot(new BinaryOp\Identical($expr->left, $expr->right)), $context);
396: }
397:
398: if ($expr instanceof BinaryOp\Equal) {
399: return $this->resolveEqualType(
400: $this->getType($expr->left, $context),
401: $this->getType($expr->right, $context),
402: )->type;
403: }
404:
405: if ($expr instanceof BinaryOp\NotEqual) {
406: return $this->getType(new Expr\BooleanNot(new BinaryOp\Equal($expr->left, $expr->right)), $context);
407: }
408:
409: if ($expr instanceof Expr\BinaryOp\Smaller) {
410: return $this->getType($expr->left, $context)->isSmallerThan($this->getType($expr->right, $context), $this->phpVersion)->toBooleanType();
411: }
412:
413: if ($expr instanceof Expr\BinaryOp\SmallerOrEqual) {
414: return $this->getType($expr->left, $context)->isSmallerThanOrEqual($this->getType($expr->right, $context), $this->phpVersion)->toBooleanType();
415: }
416:
417: if ($expr instanceof Expr\BinaryOp\Greater) {
418: return $this->getType($expr->right, $context)->isSmallerThan($this->getType($expr->left, $context), $this->phpVersion)->toBooleanType();
419: }
420:
421: if ($expr instanceof Expr\BinaryOp\GreaterOrEqual) {
422: return $this->getType($expr->right, $context)->isSmallerThanOrEqual($this->getType($expr->left, $context), $this->phpVersion)->toBooleanType();
423: }
424:
425: if ($expr instanceof Expr\BinaryOp\LogicalXor) {
426: $leftBooleanType = $this->getType($expr->left, $context)->toBoolean();
427: $rightBooleanType = $this->getType($expr->right, $context)->toBoolean();
428:
429: if (
430: $leftBooleanType instanceof ConstantBooleanType
431: && $rightBooleanType instanceof ConstantBooleanType
432: ) {
433: return new ConstantBooleanType(
434: $leftBooleanType->getValue() xor $rightBooleanType->getValue(),
435: );
436: }
437:
438: return new BooleanType();
439: }
440:
441: if ($expr instanceof MagicConst\Class_) {
442: if ($context->getTraitName() !== null) {
443: return new IntersectionType([
444: new ClassStringType(),
445: new AccessoryLiteralStringType(),
446: ]);
447: }
448:
449: if ($context->getClassName() === null) {
450: return new ConstantStringType('');
451: }
452:
453: return new ConstantStringType($context->getClassName(), true);
454: }
455:
456: if ($expr instanceof MagicConst\Namespace_) {
457: if ($context->getTraitName() !== null) {
458: return new IntersectionType([
459: new StringType(),
460: new AccessoryLiteralStringType(),
461: ]);
462: }
463:
464: return new ConstantStringType($context->getNamespace() ?? '');
465: }
466:
467: if ($expr instanceof MagicConst\Method) {
468: return new ConstantStringType($context->getMethod() ?? '');
469: }
470:
471: if ($expr instanceof MagicConst\Function_) {
472: return new ConstantStringType($context->getFunction() ?? '');
473: }
474:
475: if ($expr instanceof MagicConst\Trait_) {
476: if ($context->getTraitName() === null) {
477: return new ConstantStringType('');
478: }
479:
480: return new ConstantStringType($context->getTraitName(), true);
481: }
482:
483: if ($expr instanceof MagicConst\Property) {
484: $contextProperty = $context->getProperty();
485: if ($contextProperty === null) {
486: return new ConstantStringType('');
487: }
488:
489: return new ConstantStringType($contextProperty);
490: }
491:
492: if ($expr instanceof PropertyFetch && $expr->name instanceof Identifier) {
493: $fetchedOnType = $this->getType($expr->var, $context);
494: if (!$fetchedOnType->hasInstanceProperty($expr->name->name)->yes()) {
495: return new ErrorType();
496: }
497:
498: return $fetchedOnType->getInstanceProperty($expr->name->name, new OutOfClassScope())->getReadableType();
499: }
500:
501: return new MixedType();
502: }
503:
504: /**
505: * Resolves the backing value of an enum case. A read of the case while
506: * its value is being resolved gives mixed - like a class constant does - to prevent endless recursions.
507: */
508: public function getEnumCaseValueType(string $className, string $caseName, Expr $valueExpr, InitializerExprContext $context): Type
509: {
510: $resolvingName = sprintf('%s::%s', $className, $caseName);
511: if (array_key_exists($resolvingName, $this->currentlyResolvingClassConstant)) {
512: return new MixedType();
513: }
514:
515: $this->currentlyResolvingClassConstant[$resolvingName] = true;
516: try {
517: return $this->getType($valueExpr, $context);
518: } finally {
519: unset($this->currentlyResolvingClassConstant[$resolvingName]);
520: }
521: }
522:
523: /**
524: * @param callable(Expr): Type $getTypeCallback
525: */
526: public function getConcatType(Expr $left, Expr $right, callable $getTypeCallback): Type
527: {
528: $leftType = $getTypeCallback($left);
529: $rightType = $getTypeCallback($right);
530:
531: return $this->resolveConcatType($leftType, $rightType);
532: }
533:
534: public function resolveConcatType(Type $left, Type $right): Type
535: {
536: return $left->stringConcatenate($right, $this->phpVersion);
537: }
538:
539: /**
540: * @param callable(Expr): Type $getTypeCallback
541: * @param PhpVersions|null $phpVersions the analysed scope's versions, the configured version when null
542: */
543: public function getArrayType(Expr\Array_ $expr, callable $getTypeCallback, ?PhpVersions $phpVersions = null): Type
544: {
545: // unpacking an array with string keys is an Error below PHP 8.1, so the
546: // string keys are kept whenever any analysed version supports it
547: $keepStringKeys = $phpVersions !== null
548: ? !$phpVersions->supportsArrayUnpackingWithStringKeys()->no()
549: : $this->phpVersion->supportsArrayUnpackingWithStringKeys();
550:
551: if (count($expr->items) > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
552: return $this->oversizedArrayBuilder->build($expr, $getTypeCallback);
553: }
554:
555: $arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
556: $arrayBuilder->makeKeyOrderKnown();
557: $isList = null;
558: $hasOffsetValueTypes = [];
559: foreach ($expr->items as $arrayItem) {
560: $valueType = $getTypeCallback($arrayItem->value);
561: if ($arrayItem->unpack) {
562: $constantArrays = $valueType->getConstantArrays();
563: if (count($constantArrays) > 0) {
564: $totalArrays = count($constantArrays);
565:
566: // Unpacking merges string keys by name, while integer keys are always
567: // renumbered, so they're merged by their position among integer keys.
568: // A slot missing from some of the unpacked arrays becomes optional.
569: /** @var array<string, array{keyType: ConstantStringType|null, valueTypes: list<Type>, presentCount: int, anyOptional: bool}> $slots */
570: $slots = [];
571: /** @var list<string> $slotOrder */
572: $slotOrder = [];
573:
574: foreach ($constantArrays as $constantArrayType) {
575: // the integer keys are renumbered in the order the array has them,
576: // and so are the string keys where they are not kept
577: $constantArrayType = $keepStringKeys
578: ? $constantArrayType->inRenumberingOrder()
579: : $constantArrayType->getValuesInKeyOrder();
580: if (!$constantArrayType->isKeyOrderKnown()) {
581: $arrayBuilder->forgetKeyOrder();
582: }
583: $nextIntegerSlot = 0;
584: foreach ($constantArrayType->getKeyTypes() as $i => $keyType) {
585: if ($keepStringKeys && $keyType->isString()->yes()) {
586: $slotKey = 's' . $keyType->getValue();
587: $slotKeyType = $keyType;
588: } else {
589: $slotKey = 'i' . $nextIntegerSlot;
590: $slotKeyType = null;
591: $nextIntegerSlot++;
592: }
593:
594: if (!isset($slots[$slotKey])) {
595: $slots[$slotKey] = [
596: 'keyType' => $slotKeyType,
597: 'valueTypes' => [],
598: 'presentCount' => 0,
599: 'anyOptional' => false,
600: ];
601: $slotOrder[] = $slotKey;
602: }
603:
604: $slots[$slotKey]['valueTypes'][] = $constantArrayType->getValueTypes()[$i];
605: $slots[$slotKey]['presentCount']++;
606: if (!$constantArrayType->isOptionalKey($i)) {
607: continue;
608: }
609:
610: $slots[$slotKey]['anyOptional'] = true;
611: }
612: }
613:
614: foreach ($slotOrder as $slotKey) {
615: $slot = $slots[$slotKey];
616: $mergedValueType = TypeCombinator::union(...$slot['valueTypes']);
617: $isOptional = $slot['anyOptional'] || $slot['presentCount'] < $totalArrays;
618: $slotKeyType = $slot['keyType'];
619: $arrayBuilder->setOffsetValueType($slotKeyType, $mergedValueType, $isOptional);
620:
621: if ($slotKeyType === null) {
622: continue;
623: }
624:
625: $keyValue = $slotKeyType->getValue();
626: if (isset($hasOffsetValueTypes[$keyValue])) {
627: $hasOffsetValueTypes[$keyValue] = new HasOffsetValueType(
628: $slotKeyType,
629: $isOptional
630: ? TypeCombinator::union($hasOffsetValueTypes[$keyValue]->getValueType(), $mergedValueType)
631: : $mergedValueType,
632: );
633: } elseif (!$isOptional) {
634: $hasOffsetValueTypes[$keyValue] = new HasOffsetValueType($slotKeyType, $mergedValueType);
635: }
636: }
637: } else {
638: $arrayBuilder->degradeToGeneralArray();
639:
640: if ($keepStringKeys && !$valueType->getIterableKeyType()->isString()->no()) {
641: $isList = false;
642: $offsetType = $valueType->getIterableKeyType();
643:
644: foreach ($hasOffsetValueTypes as $key => $hasOffsetValueType) {
645: if (!$offsetType->isSuperTypeOf($hasOffsetValueType->getOffsetType())->yes()) {
646: continue;
647: }
648:
649: unset($hasOffsetValueTypes[$key]);
650: }
651: } else {
652: $isList ??= $arrayBuilder->isList();
653: $offsetType = new IntegerType();
654: }
655:
656: $arrayBuilder->setOffsetValueType($offsetType, $valueType->getIterableValueType(), !$valueType->isIterableAtLeastOnce()->yes());
657: }
658: } else {
659: $arrayBuilder->setOffsetValueType(
660: $arrayItem->key !== null ? $getTypeCallback($arrayItem->key) : null,
661: $valueType,
662: );
663: }
664: }
665:
666: $arrayType = $arrayBuilder->getArray();
667: if ($isList === true) {
668: $arrayType = TypeCombinator::intersect($arrayType, new AccessoryArrayListType());
669: }
670:
671: if (count($hasOffsetValueTypes) > 0 && !$arrayType->isConstantArray()->yes()) {
672: $arrayType = TypeCombinator::intersect($arrayType, ...array_values($hasOffsetValueTypes));
673: }
674:
675: return $arrayType;
676: }
677:
678: /**
679: * @param callable(Expr): Type $getTypeCallback
680: */
681: public function getCastType(Expr\Cast $expr, callable $getTypeCallback): Type
682: {
683: if ($expr instanceof \PhpParser\Node\Expr\Cast\Int_) {
684: return $getTypeCallback($expr->expr)->toInteger();
685: }
686: if ($expr instanceof Bool_) {
687: return $getTypeCallback($expr->expr)->toBoolean();
688: }
689: if ($expr instanceof Double) {
690: return $getTypeCallback($expr->expr)->toFloat();
691: }
692: if ($expr instanceof \PhpParser\Node\Expr\Cast\String_) {
693: return $getTypeCallback($expr->expr)->toString();
694: }
695: if ($expr instanceof Array_) {
696: return $getTypeCallback($expr->expr)->toArray();
697: }
698: if ($expr instanceof Object_) {
699: return $this->getCastObjectType($getTypeCallback($expr->expr));
700: }
701:
702: return new MixedType();
703: }
704:
705: public function getCastObjectType(Type $exprType): Type
706: {
707: $castToObject = static function (Type $type): Type {
708: $constantArrays = $type->getConstantArrays();
709: if (count($constantArrays) > 0) {
710: $objects = [];
711: foreach ($constantArrays as $constantArray) {
712: $properties = [];
713: $optionalProperties = [];
714: foreach ($constantArray->getKeyTypes() as $i => $keyType) {
715: $valueType = $constantArray->getValueTypes()[$i];
716: $optional = $constantArray->isOptionalKey($i);
717: if ($optional) {
718: $optionalProperties[] = $keyType->getValue();
719: }
720: $properties[$keyType->getValue()] = $valueType;
721: }
722:
723: $objects[] = new IntersectionType([new ObjectShapeType($properties, $optionalProperties), new ObjectType(stdClass::class)]);
724: }
725:
726: return TypeCombinator::union(...$objects);
727: }
728: if ($type->isObject()->yes()) {
729: return $type;
730: }
731:
732: return new ObjectType('stdClass');
733: };
734:
735: if ($exprType instanceof UnionType) {
736: return TypeCombinator::union(...array_map($castToObject, $exprType->getTypes()));
737: }
738:
739: return $castToObject($exprType);
740: }
741:
742: /**
743: * @param Name|Identifier|ComplexType|null $type
744: */
745: public function getFunctionType($type, bool $isNullable, bool $isVariadic, InitializerExprContext $context): Type
746: {
747: if ($isNullable) {
748: return TypeCombinator::addNull(
749: $this->getFunctionType($type, false, $isVariadic, $context),
750: );
751: }
752: if ($isVariadic) {
753: if ($this->phpVersion->supportsNamedArguments()) {
754: return new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $this->getFunctionType(
755: $type,
756: false,
757: false,
758: $context,
759: ));
760: }
761:
762: return new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $this->getFunctionType(
763: $type,
764: false,
765: false,
766: $context,
767: )), new AccessoryArrayListType()]);
768: }
769:
770: if ($type instanceof Name) {
771: $className = (string) $type;
772: $lowercasedClassName = strtolower($className);
773: if ($lowercasedClassName === 'parent') {
774: $classReflection = null;
775: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
776: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
777: }
778: if ($classReflection !== null && $classReflection->getParentClass() !== null) {
779: return new ObjectType($classReflection->getParentClass()->getName());
780: }
781:
782: return new NonexistentParentClassType();
783: }
784: }
785:
786: $classReflection = null;
787: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
788: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
789: }
790:
791: return ParserNodeTypeToPHPStanType::resolve($type, $classReflection);
792: }
793:
794: private function isParameterValueNullable(Param $parameter): bool
795: {
796: if ($parameter->default instanceof ConstFetch) {
797: return strtolower((string) $parameter->default->name) === 'null';
798: }
799:
800: return false;
801: }
802:
803: /**
804: * @param array<int, Type>|null $boundArgTypes the types of the bound arguments of a partial function application,
805: * keyed like its raw arguments; null to resolve them as constant expressions
806: */
807: public function getFirstClassCallableType(Expr\CallLike $expr, InitializerExprContext $context, bool $nativeTypesPromoted, ?array $boundArgTypes = null): Type
808: {
809: $partialApplicationArgs = null;
810: if (!$expr->isFirstClassCallable()) {
811: $partialApplicationArgs = $expr->getRawArgs();
812: if ($boundArgTypes === null) {
813: $boundArgTypes = [];
814: foreach ($partialApplicationArgs as $i => $arg) {
815: if (!$arg instanceof Arg) {
816: continue;
817: }
818: $boundArgTypes[$i] = $this->getType($arg->value, $context);
819: }
820: }
821: }
822:
823: if ($expr instanceof FuncCall) {
824: if ($expr->name instanceof Name) {
825: if ($this->getReflectionProvider()->hasFunction($expr->name, $context)) {
826: $function = $this->getReflectionProvider()->getFunction($expr->name, $context);
827: return $this->createFirstClassCallable(
828: $function,
829: $function->getVariants(),
830: $nativeTypesPromoted,
831: $partialApplicationArgs,
832: $boundArgTypes ?? [],
833: ClosureOrigin::forFunction($function->getName()),
834: );
835: }
836:
837: return new ObjectType(Closure::class);
838: }
839: }
840:
841: if ($expr instanceof Expr\StaticCall) {
842: if (!$expr->class instanceof Name) {
843: return new ObjectType(Closure::class);
844: }
845:
846: if (!$expr->name instanceof Identifier) {
847: return new ObjectType(Closure::class);
848: }
849:
850: $classReflection = null;
851: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
852: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
853: }
854:
855: $classType = $this->resolveTypeByName($expr->class, $classReflection);
856: $methodName = $expr->name->toString();
857: if (!$classType->hasMethod($methodName)->yes()) {
858: return new ObjectType(Closure::class);
859: }
860:
861: $method = $classType->getMethod($methodName, new OutOfClassScope());
862: $classType = $this->resolveTypeByNameWithLateStaticBinding($expr->class, $classType, $method);
863: if (!$classType->hasMethod($methodName)->yes()) {
864: return new ObjectType(Closure::class);
865: }
866: $method = $classType->getMethod($methodName, new OutOfClassScope());
867:
868: return $this->createFirstClassCallable(
869: $method,
870: $method->getVariants(),
871: $nativeTypesPromoted,
872: $partialApplicationArgs,
873: $boundArgTypes ?? [],
874: ClosureOrigin::forMethod($classType, $methodName, true),
875: );
876: }
877:
878: if ($expr instanceof New_) {
879: return new ErrorType();
880: }
881:
882: throw new ShouldNotHappenException();
883: }
884:
885: /**
886: * @param ParametersAcceptor[] $variants
887: * @param array<Arg|ArgPlaceholder|VariadicPlaceholder>|null $partialApplicationArgs the arguments of a partial function application, null for a first-class callable
888: * @param array<int, Type> $boundArgTypes the types of the bound arguments of a partial function application, keyed like $partialApplicationArgs
889: * @param ClosureOrigin|null $origin the callee, whose call a call of the closure replays
890: */
891: public function createFirstClassCallable(
892: FunctionReflection|ExtendedMethodReflection|null $function,
893: array $variants,
894: bool $nativeTypesPromoted,
895: ?array $partialApplicationArgs = null,
896: array $boundArgTypes = [],
897: ?ClosureOrigin $origin = null,
898: ): Type
899: {
900: if ($origin !== null && $partialApplicationArgs !== null) {
901: $origin = $origin->withPartialApplication($partialApplicationArgs, $boundArgTypes);
902: }
903:
904: if ($partialApplicationArgs !== null && PartialFunctionApplicationParameters::leavesUnknownDefaultValue($variants, $partialApplicationArgs)) {
905: // creating the closure throws
906: return new ObjectType(Closure::class);
907: }
908:
909: // variants of multi-variant built-ins carry functionMap parameter names,
910: // but the closure accepts the native names as named arguments
911: $namedArgumentNames = [];
912: if ($function !== null) {
913: foreach ($function->getNamedArgumentsVariants() ?? [] as $namedArgumentsVariant) {
914: foreach ($namedArgumentsVariant->getParameters() as $i => $parameter) {
915: $namedArgumentNames[$i] = $parameter->getName();
916: }
917: }
918: }
919:
920: $closureTypes = [];
921:
922: foreach ($variants as $variant) {
923: $returnType = $variant->getReturnType();
924: if ($variant instanceof ExtendedParametersAcceptor) {
925: $returnType = $nativeTypesPromoted ? $variant->getNativeReturnType() : $returnType;
926: }
927:
928: $throwPoints = [];
929: $impurePoints = [];
930: $acceptsNamedArguments = TrinaryLogic::createYes();
931: $mustUseReturnValue = TrinaryLogic::createMaybe();
932: $isStaticClosure = TrinaryLogic::createMaybe();
933: if ($variant instanceof CallableParametersAcceptor) {
934: $throwPoints = $variant->getThrowPoints();
935: $impurePoints = $variant->getImpurePoints();
936: $acceptsNamedArguments = $variant->acceptsNamedArguments();
937: $mustUseReturnValue = $variant->mustUseReturnValue();
938: $isStaticClosure = $variant->isStaticClosure();
939: } elseif ($function !== null) {
940: $returnTypeForThrow = $variant->getReturnType();
941: $throwType = $function->getThrowType();
942: if ($throwType === null) {
943: if ($returnTypeForThrow instanceof NeverType && $returnTypeForThrow->isExplicit()) {
944: $throwType = new ObjectType(Throwable::class);
945: }
946: }
947:
948: if ($throwType !== null) {
949: if (!$throwType->isVoid()->yes()) {
950: $throwPoints[] = SimpleThrowPoint::createExplicit($throwType, true);
951: }
952: } else {
953: if (!(new ObjectType(Throwable::class))->isSuperTypeOf($returnTypeForThrow)->yes()) {
954: $throwPoints[] = SimpleThrowPoint::createImplicit();
955: }
956: }
957:
958: $impurePoint = SimpleImpurePoint::createFromVariant($function, $variant);
959: if ($impurePoint !== null) {
960: $impurePoints[] = $impurePoint;
961: }
962:
963: $acceptsNamedArguments = $function->acceptsNamedArguments();
964: $mustUseReturnValue = $function->mustUseReturnValue();
965: // binding an object to the closure of a static method, or to a partial
966: // application of a function, fails; a function's first-class callable can be bound
967: if ($function instanceof ExtendedMethodReflection ? $function->isStatic() : $partialApplicationArgs !== null) {
968: $isStaticClosure = TrinaryLogic::createYes();
969: }
970: }
971:
972: $parameters = $variant->getParameters();
973: if (count($namedArgumentNames) > 0) {
974: $parameters = self::renameParameters($parameters, $namedArgumentNames);
975: }
976: $isVariadic = $variant->isVariadic();
977: $templateTypeMap = $variant->getTemplateTypeMap();
978: $variantOrigin = $origin;
979: if ($partialApplicationArgs !== null) {
980: $partialApplication = PartialFunctionApplicationParameters::apply($parameters, $isVariadic, $partialApplicationArgs, $boundArgTypes, $returnType, $templateTypeMap);
981: if ($partialApplication === null) {
982: // creating the closure from this variant throws
983: continue;
984: }
985: [$parameters, $isVariadic, $returnType, $templateTypeMap, $boundParameterNames] = $partialApplication;
986: $magicMethodParameterNames = PartialFunctionApplicationParameters::getMagicMethodParameterNames($function, $partialApplicationArgs);
987: if ($magicMethodParameterNames === null) {
988: continue;
989: }
990: $parameters = self::renameParameters($parameters, $magicMethodParameterNames);
991: if ($variantOrigin !== null) {
992: $variantOrigin = $variantOrigin->withBoundParameterNames($boundParameterNames);
993: }
994: }
995:
996: $templateTags = [];
997: foreach ($templateTypeMap->getTypes() as $templateType) {
998: if (!$templateType instanceof TemplateType) {
999: continue;
1000: }
1001: $templateTags[$templateType->getName()] = new TemplateTag(
1002: $templateType->getName(),
1003: $templateType->getBound(),
1004: $templateType->getDefault(),
1005: $templateType->getVariance(),
1006: );
1007: }
1008: if ($function !== null) {
1009: $assertions = $function->getAsserts();
1010: } elseif ($variant instanceof CallableParametersAcceptor) {
1011: $assertions = $variant->getAsserts();
1012: } else {
1013: $assertions = Assertions::createEmpty();
1014: }
1015:
1016: // a conditional return type referencing the function's own parameter,
1017: // like @return ($value is int ? true : false) on is_int(),
1018: // also becomes a type predicate of the resulting Closure
1019: $assertions = CallableAssertionsHelper::withConditionalReturnPredicate($assertions, $variant);
1020: $closureTypes[] = new ClosureType(
1021: $parameters,
1022: $returnType,
1023: $isVariadic,
1024: $templateTypeMap,
1025: $variant->getResolvedTemplateTypeMap(),
1026: $variant instanceof ExtendedParametersAcceptor ? $variant->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
1027: $templateTags,
1028: $throwPoints,
1029: $impurePoints,
1030: acceptsNamedArguments: $acceptsNamedArguments,
1031: mustUseReturnValue: $mustUseReturnValue,
1032: assertions: $assertions,
1033: isStatic: $isStaticClosure,
1034: origin: $variantOrigin,
1035: );
1036: }
1037:
1038: if ($partialApplicationArgs !== null && count($closureTypes) === 0) {
1039: return new ObjectType(Closure::class);
1040: }
1041:
1042: return TypeCombinator::union(...$closureTypes);
1043: }
1044:
1045: /**
1046: * @param list<ParameterReflection> $parameters
1047: * @param array<int, string> $names
1048: * @return list<ParameterReflection>
1049: */
1050: private static function renameParameters(array $parameters, array $names): array
1051: {
1052: $renamed = [];
1053: foreach ($parameters as $i => $parameter) {
1054: if (
1055: !isset($names[$i])
1056: || $names[$i] === $parameter->getName()
1057: || !$parameter instanceof ExtendedParameterReflection
1058: ) {
1059: $renamed[] = $parameter;
1060: continue;
1061: }
1062:
1063: $renamed[] = new ExtendedDummyParameter(
1064: $names[$i],
1065: $parameter->getType(),
1066: $parameter->isOptional(),
1067: $parameter->passedByReference(),
1068: $parameter->isVariadic(),
1069: $parameter->getDefaultValue(),
1070: $parameter->getNativeType(),
1071: $parameter->getPhpDocType(),
1072: $parameter->getOutType(),
1073: $parameter->isImmediatelyInvokedCallable(),
1074: $parameter->getClosureThisType(),
1075: $parameter->getAttributes(),
1076: $parameter->getAllowedConstants(),
1077: $parameter->isPureUnlessCallableIsImpureParameter(),
1078: $parameter->isPureUnlessParameterPassedParameter(),
1079: );
1080: }
1081:
1082: return $renamed;
1083: }
1084:
1085: /**
1086: * @param callable(Expr): Type $getTypeCallback
1087: */
1088: public function getBitwiseAndType(Expr $left, Expr $right, callable $getTypeCallback): Type
1089: {
1090: $leftType = $getTypeCallback($left);
1091: $rightType = $getTypeCallback($right);
1092:
1093: return $this->operatorTypeSpecifyingExtensionRegistry
1094: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseAnd($left, $right), $leftType, $rightType)
1095: ?? $leftType->bitwiseAnd($rightType, $this->phpVersion);
1096: }
1097:
1098: /**
1099: * @param callable(Expr): Type $getTypeCallback
1100: */
1101: public function getBitwiseOrType(Expr $left, Expr $right, callable $getTypeCallback): Type
1102: {
1103: $leftType = $getTypeCallback($left);
1104: $rightType = $getTypeCallback($right);
1105:
1106: return $this->operatorTypeSpecifyingExtensionRegistry
1107: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseOr($left, $right), $leftType, $rightType)
1108: ?? $leftType->bitwiseOr($rightType, $this->phpVersion);
1109: }
1110:
1111: /**
1112: * @param callable(Expr): Type $getTypeCallback
1113: */
1114: public function getBitwiseXorType(Expr $left, Expr $right, callable $getTypeCallback): Type
1115: {
1116: $leftType = $getTypeCallback($left);
1117: $rightType = $getTypeCallback($right);
1118:
1119: return $this->operatorTypeSpecifyingExtensionRegistry
1120: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseXor($left, $right), $leftType, $rightType)
1121: ?? $leftType->bitwiseXor($rightType, $this->phpVersion);
1122: }
1123:
1124: /**
1125: * @param callable(Expr): Type $getTypeCallback
1126: */
1127: public function getSpaceshipType(Expr $left, Expr $right, callable $getTypeCallback): Type
1128: {
1129: $leftTypes = $getTypeCallback($left);
1130: $rightTypes = $getTypeCallback($right);
1131:
1132: if ($leftTypes instanceof NeverType || $rightTypes instanceof NeverType) {
1133: return $this->getNeverType($leftTypes, $rightTypes);
1134: }
1135:
1136: $leftValues = $leftTypes->getConstantScalarValues();
1137: $rightValues = $rightTypes->getConstantScalarValues();
1138:
1139: $leftValuesCount = count($leftValues);
1140: $rightValuesCount = count($rightValues);
1141: if ($leftValuesCount > 0 && $rightValuesCount > 0 && $leftValuesCount * $rightValuesCount <= self::CALCULATE_SCALARS_LIMIT) {
1142: $resultTypes = [];
1143: foreach ($leftValues as $leftValue) {
1144: foreach ($rightValues as $rightValue) {
1145: $resultType = new ConstantIntegerType(ValueSet::compareScalarValues($leftValue, $rightValue, $this->phpVersion) ?? 1);
1146: $resultTypes[] = $resultType;
1147: }
1148: }
1149: return TypeCombinator::union(...$resultTypes);
1150: }
1151:
1152: return IntegerRangeType::fromInterval(-1, 1);
1153: }
1154:
1155: /**
1156: * @param callable(Expr): Type $getTypeCallback
1157: */
1158: public function getDivType(Expr $left, Expr $right, callable $getTypeCallback): Type
1159: {
1160: $leftType = $getTypeCallback($left);
1161: $rightType = $getTypeCallback($right);
1162:
1163: $specifiedTypes = $this->operatorTypeSpecifyingExtensionRegistry
1164: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Div($left, $right), $leftType, $rightType);
1165: if ($specifiedTypes !== null) {
1166: return $specifiedTypes;
1167: }
1168:
1169: $result = $leftType->arithmeticDivide($rightType, $this->phpVersion);
1170:
1171: // the remainder can be narrowed in the scope, e.g. by `$a % $b === 0`
1172: if ($leftType->isInteger()->yes() && $rightType->isInteger()->yes()) {
1173: $modType = $getTypeCallback(new BinaryOp\Mod($left, $right));
1174: if ($modType->isInteger()->yes() && (new ConstantIntegerType(0))->isSuperTypeOf($modType)->yes()) {
1175: $withoutFloat = TypeCombinator::remove($result, new FloatType());
1176:
1177: // PHP_INT_MIN / -1 divides without a remainder but still overflows to a float
1178: if (!$withoutFloat instanceof NeverType) {
1179: return $withoutFloat;
1180: }
1181: }
1182: }
1183:
1184: return $result;
1185: }
1186:
1187: /**
1188: * @param callable(Expr): Type $getTypeCallback
1189: */
1190: public function getModType(Expr $left, Expr $right, callable $getTypeCallback): Type
1191: {
1192: $leftType = $getTypeCallback($left);
1193: $rightType = $getTypeCallback($right);
1194:
1195: return $this->operatorTypeSpecifyingExtensionRegistry
1196: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mod($left, $right), $leftType, $rightType)
1197: ?? $leftType->arithmeticModulo($rightType, $this->phpVersion);
1198: }
1199:
1200: /**
1201: * @param callable(Expr): Type $getTypeCallback
1202: */
1203: public function getPlusType(Expr $left, Expr $right, callable $getTypeCallback): Type
1204: {
1205: $leftType = $getTypeCallback($left);
1206: $rightType = $getTypeCallback($right);
1207:
1208: return $this->operatorTypeSpecifyingExtensionRegistry
1209: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Plus($left, $right), $leftType, $rightType)
1210: ?? $leftType->arithmeticAdd($rightType, $this->phpVersion);
1211: }
1212:
1213: /**
1214: * @param callable(Expr): Type $getTypeCallback
1215: */
1216: public function getMinusType(Expr $left, Expr $right, callable $getTypeCallback): Type
1217: {
1218: $leftType = $getTypeCallback($left);
1219: $rightType = $getTypeCallback($right);
1220:
1221: return $this->operatorTypeSpecifyingExtensionRegistry
1222: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Minus($left, $right), $leftType, $rightType)
1223: ?? $leftType->arithmeticSubtract($rightType, $this->phpVersion);
1224: }
1225:
1226: /**
1227: * @param callable(Expr): Type $getTypeCallback
1228: */
1229: public function getMulType(Expr $left, Expr $right, callable $getTypeCallback): Type
1230: {
1231: $leftType = $getTypeCallback($left);
1232: $rightType = $getTypeCallback($right);
1233:
1234: return $this->operatorTypeSpecifyingExtensionRegistry
1235: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mul($left, $right), $leftType, $rightType)
1236: ?? $leftType->arithmeticMultiply($rightType, $this->phpVersion);
1237: }
1238:
1239: /**
1240: * @param callable(Expr): Type $getTypeCallback
1241: */
1242: public function getPowType(Expr $left, Expr $right, callable $getTypeCallback): Type
1243: {
1244: $leftType = $getTypeCallback($left);
1245: $rightType = $getTypeCallback($right);
1246:
1247: return $this->operatorTypeSpecifyingExtensionRegistry
1248: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Pow($left, $right), $leftType, $rightType)
1249: ?? $leftType->arithmeticPower($rightType, $this->phpVersion);
1250: }
1251:
1252: /**
1253: * @param callable(Expr): Type $getTypeCallback
1254: */
1255: public function getShiftLeftType(Expr $left, Expr $right, callable $getTypeCallback): Type
1256: {
1257: $leftType = $getTypeCallback($left);
1258: $rightType = $getTypeCallback($right);
1259:
1260: return $this->operatorTypeSpecifyingExtensionRegistry
1261: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\ShiftLeft($left, $right), $leftType, $rightType)
1262: ?? $leftType->bitwiseShiftLeft($rightType, $this->phpVersion);
1263: }
1264:
1265: /**
1266: * @param callable(Expr): Type $getTypeCallback
1267: */
1268: public function getShiftRightType(Expr $left, Expr $right, callable $getTypeCallback): Type
1269: {
1270: $leftType = $getTypeCallback($left);
1271: $rightType = $getTypeCallback($right);
1272:
1273: return $this->operatorTypeSpecifyingExtensionRegistry
1274: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\ShiftRight($left, $right), $leftType, $rightType)
1275: ?? $leftType->bitwiseShiftRight($rightType, $this->phpVersion);
1276: }
1277:
1278: /**
1279: * @return TypeResult<BooleanType>
1280: */
1281: public function resolveIdenticalType(Type $leftType, Type $rightType): TypeResult
1282: {
1283: if ($leftType instanceof NeverType || $rightType instanceof NeverType) {
1284: return new TypeResult(new ConstantBooleanType(false), []);
1285: }
1286:
1287: if ($leftType instanceof ConstantScalarType && $rightType instanceof ConstantScalarType) {
1288: return new TypeResult(new ConstantBooleanType($leftType->getValue() === $rightType->getValue()), []);
1289: }
1290:
1291: $leftTypeFiniteTypes = $leftType->getFiniteTypes();
1292: $rightTypeFiniteType = $rightType->getFiniteTypes();
1293: if (count($leftTypeFiniteTypes) === 1 && count($rightTypeFiniteType) === 1) {
1294: return new TypeResult(new ConstantBooleanType($leftTypeFiniteTypes[0]->equals($rightTypeFiniteType[0])), []);
1295: }
1296:
1297: $leftIsSuperTypeOfRight = $leftType->isSuperTypeOf($rightType);
1298: $rightIsSuperTypeOfLeft = $rightType->isSuperTypeOf($leftType);
1299: if ($leftIsSuperTypeOfRight->no() && $rightIsSuperTypeOfLeft->no()) {
1300: return new TypeResult(new ConstantBooleanType(false), array_merge($leftIsSuperTypeOfRight->getReasons(), $rightIsSuperTypeOfLeft->getReasons()));
1301: }
1302:
1303: if ($leftType instanceof ConstantArrayType && $rightType instanceof ConstantArrayType) {
1304: return $this->resolveConstantArrayTypeComparison($leftType, $rightType, fn ($leftValueType, $rightValueType): TypeResult => $this->resolveIdenticalType($leftValueType, $rightValueType));
1305: }
1306:
1307: return new TypeResult(new BooleanType(), []);
1308: }
1309:
1310: /**
1311: * @return TypeResult<BooleanType>
1312: */
1313: public function resolveEqualType(Type $leftType, Type $rightType, ?PhpVersions $phpVersions = null): TypeResult
1314: {
1315: if ($leftType instanceof NeverType || $rightType instanceof NeverType) {
1316: return new TypeResult(new ConstantBooleanType(false), []);
1317: }
1318:
1319: if (
1320: ($leftType->isEnum()->yes() && $rightType->isTrue()->no())
1321: || ($rightType->isEnum()->yes() && $leftType->isTrue()->no())
1322: ) {
1323: return $this->resolveIdenticalType($leftType, $rightType);
1324: }
1325:
1326: $versions = $phpVersions !== null ? $phpVersions->getLooseComparisonVersions() : [$this->phpVersion];
1327:
1328: // same-type sides cannot coerce - loose equals strict, except for
1329: // two numeric strings, which compare as numbers
1330: if (
1331: ($leftType->isString()->yes() && $rightType->isString()->yes() && (self::isNonNumericString($leftType, $versions) || self::isNonNumericString($rightType, $versions)))
1332: || ($leftType->isInteger()->yes() && $rightType->isInteger()->yes())
1333: ) {
1334: return $this->resolveIdenticalType($leftType, $rightType);
1335: }
1336:
1337: if ($leftType instanceof ConstantArrayType && $rightType instanceof ConstantArrayType) {
1338: return $this->resolveConstantArrayTypeComparison($leftType, $rightType, fn ($leftValueType, $rightValueType): TypeResult => $this->resolveEqualType($leftValueType, $rightValueType, $phpVersions));
1339: }
1340:
1341: // constant only when every PHP version agrees
1342: $result = $leftType->looseCompare($rightType, $versions[0]);
1343: foreach (array_slice($versions, 1) as $version) {
1344: if (!$result->equals($leftType->looseCompare($rightType, $version))) {
1345: $result = new BooleanType();
1346: break;
1347: }
1348: }
1349: if ($result->isTrue()->yes() || $result->isFalse()->yes()) {
1350: return new TypeResult($result, []);
1351: }
1352:
1353: // either side's possibly loosely equal type in any version rules the other side out
1354: foreach ([[$leftType, $rightType], [$rightType, $leftType]] as [$type, $otherType]) {
1355: $possiblyEqualTypes = [];
1356: foreach ($versions as $version) {
1357: $possiblyEqualTypes[] = $type->getPossiblyLooselyEqualType($version);
1358: }
1359: if (TypeCombinator::union(...$possiblyEqualTypes)->isSuperTypeOf($otherType)->no()) {
1360: return new TypeResult(new ConstantBooleanType(false), []);
1361: }
1362: }
1363:
1364: // either side's always loosely equal type in every version holds the other side
1365: foreach ([[$leftType, $rightType], [$rightType, $leftType]] as [$type, $otherType]) {
1366: $alwaysEqualTypes = [];
1367: foreach ($versions as $version) {
1368: $alwaysEqualTypes[] = $type->getAlwaysLooselyEqualType($version);
1369: }
1370: if (TypeCombinator::intersect(...$alwaysEqualTypes)->isSuperTypeOf($otherType)->yes()) {
1371: return new TypeResult(new ConstantBooleanType(true), []);
1372: }
1373: }
1374:
1375: return new TypeResult($result, []);
1376: }
1377:
1378: /**
1379: * Whether the strings are numeric in none of the PHP versions. A constant
1380: * string's isNumericString() follows the PHP version running PHPStan,
1381: * while '1 ' is numeric since PHP 8.0 only.
1382: *
1383: * @param non-empty-list<PhpVersion> $phpVersions
1384: */
1385: private static function isNonNumericString(Type $type, array $phpVersions): bool
1386: {
1387: if (!$type->isNumericString()->no()) {
1388: return false;
1389: }
1390:
1391: foreach ($type->getConstantStrings() as $constantString) {
1392: foreach ($phpVersions as $phpVersion) {
1393: if (StringSet::parseNumericString($constantString->getValue(), $phpVersion) !== null) {
1394: return false;
1395: }
1396: }
1397: }
1398:
1399: return true;
1400: }
1401:
1402: /**
1403: * @param callable(Type, Type): TypeResult<BooleanType> $valueComparisonCallback
1404: * @return TypeResult<BooleanType>
1405: */
1406: private function resolveConstantArrayTypeComparison(ConstantArrayType $leftType, ConstantArrayType $rightType, callable $valueComparisonCallback): TypeResult
1407: {
1408: $leftKeyTypes = $leftType->getKeyTypes();
1409: $rightKeyTypes = $rightType->getKeyTypes();
1410: $leftValueTypes = $leftType->getValueTypes();
1411: $rightValueTypes = $rightType->getValueTypes();
1412:
1413: if (!$leftType->isKeyOrderKnown() || !$rightType->isKeyOrderKnown()) {
1414: // a shape that does not know its key order is compared key by key,
1415: // and it is never certainly identical to another array
1416: $rightKeyIndexes = [];
1417: foreach ($rightKeyTypes as $j => $rightKeyType) {
1418: $rightKeyIndexes[$rightKeyType->getValue()] = $j;
1419: }
1420:
1421: foreach ($leftKeyTypes as $i => $leftKeyType) {
1422: $j = $rightKeyIndexes[$leftKeyType->getValue()] ?? null;
1423: if ($j === null) {
1424: if (!$leftType->isOptionalKey($i)) {
1425: return new TypeResult(new ConstantBooleanType(false), []);
1426: }
1427: continue;
1428: }
1429:
1430: unset($rightKeyIndexes[$leftKeyType->getValue()]);
1431: if ($leftType->isOptionalKey($i) && $rightType->isOptionalKey($j)) {
1432: continue;
1433: }
1434:
1435: $leftIdenticalToRightResult = $valueComparisonCallback($leftValueTypes[$i], $rightValueTypes[$j]);
1436: if ($leftIdenticalToRightResult->type->toBoolean()->isFalse()->yes()) {
1437: return $leftIdenticalToRightResult;
1438: }
1439: }
1440:
1441: foreach ($rightKeyIndexes as $j) {
1442: if (!$rightType->isOptionalKey($j)) {
1443: return new TypeResult(new ConstantBooleanType(false), []);
1444: }
1445: }
1446:
1447: return new TypeResult(new BooleanType(), []);
1448: }
1449:
1450: $resultType = new ConstantBooleanType(true);
1451:
1452: foreach ($leftKeyTypes as $i => $leftKeyType) {
1453: $leftOptional = $leftType->isOptionalKey($i);
1454: if ($leftOptional) {
1455: $resultType = new BooleanType();
1456: }
1457:
1458: if (count($rightKeyTypes) === 0) {
1459: if (!$leftOptional) {
1460: return new TypeResult(new ConstantBooleanType(false), []);
1461: }
1462: continue;
1463: }
1464:
1465: $found = false;
1466: foreach ($rightKeyTypes as $j => $rightKeyType) {
1467: unset($rightKeyTypes[$j]);
1468:
1469: if ($leftKeyType->equals($rightKeyType)) {
1470: $found = true;
1471: break;
1472: } elseif (!$rightType->isOptionalKey($j)) {
1473: return new TypeResult(new ConstantBooleanType(false), []);
1474: }
1475: }
1476:
1477: if (!$found) {
1478: if (!$leftOptional) {
1479: return new TypeResult(new ConstantBooleanType(false), []);
1480: }
1481: continue;
1482: }
1483:
1484: if (!isset($j)) {
1485: throw new ShouldNotHappenException();
1486: }
1487:
1488: $rightOptional = $rightType->isOptionalKey($j);
1489: if ($rightOptional) {
1490: $resultType = new BooleanType();
1491: if ($leftOptional) {
1492: continue;
1493: }
1494: }
1495:
1496: $leftIdenticalToRightResult = $valueComparisonCallback($leftValueTypes[$i], $rightValueTypes[$j]);
1497: $leftIdenticalToRight = $leftIdenticalToRightResult->type;
1498: if ($leftIdenticalToRight->isFalse()->yes()) {
1499: return $leftIdenticalToRightResult;
1500: }
1501: $resultType = TypeCombinator::union($resultType, $leftIdenticalToRight);
1502: }
1503:
1504: foreach (array_keys($rightKeyTypes) as $j) {
1505: if (!$rightType->isOptionalKey($j)) {
1506: return new TypeResult(new ConstantBooleanType(false), []);
1507: }
1508: $resultType = new BooleanType();
1509: }
1510:
1511: return new TypeResult($resultType->toBoolean(), []);
1512: }
1513:
1514: /**
1515: * With $nativeTypesPromoted, PHPDoc types of the constants are ignored:
1516: * a constant that can be overridden in a child class resolves only to its native type.
1517: *
1518: * @param callable(Expr): Type $getTypeCallback
1519: */
1520: public function getClassConstFetchTypeByReflection(Name|Expr $class, string $constantName, ?ClassReflection $classReflection, callable $getTypeCallback, bool $nativeTypesPromoted = false): Type
1521: {
1522: $isObject = false;
1523: if ($class instanceof Name) {
1524: $constantClass = (string) $class;
1525: $constantClassType = new ObjectType($constantClass);
1526: $namesToResolve = [
1527: 'self',
1528: 'parent',
1529: ];
1530: if ($classReflection !== null) {
1531: if ($classReflection->isFinal()) {
1532: $namesToResolve[] = 'static';
1533: } elseif (strtolower($constantClass) === 'static') {
1534: if (strtolower($constantName) === 'class') {
1535: return new GenericClassStringType(new StaticType($classReflection));
1536: }
1537:
1538: $namesToResolve[] = 'static';
1539: $isObject = true;
1540: }
1541: }
1542: if (in_array(strtolower($constantClass), $namesToResolve, true)) {
1543: $resolvedName = $this->resolveName($class, $classReflection);
1544: if (strtolower($resolvedName) === 'parent' && strtolower($constantName) === 'class') {
1545: return new ClassStringType();
1546: }
1547: $constantClassType = $this->resolveTypeByName($class, $classReflection);
1548: }
1549:
1550: if (strtolower($constantName) === 'class') {
1551: return new ConstantStringType($constantClassType->getClassName(), true);
1552: }
1553: } elseif ($class instanceof String_ && strtolower($constantName) === 'class') {
1554: return new ConstantStringType($class->value, true);
1555: } else {
1556: $constantClassType = $getTypeCallback($class);
1557: $isObject = true;
1558: }
1559:
1560: if (strtolower($constantName) === 'class') {
1561: return $constantClassType->toClassConstantType($this->getReflectionProvider());
1562: }
1563:
1564: if ($constantClassType->isClassString()->yes()) {
1565: if ($constantClassType->isConstantScalarValue()->yes()) {
1566: $isObject = false;
1567: }
1568: $constantClassType = $constantClassType->getClassStringObjectType();
1569: }
1570:
1571: $types = [];
1572: $referencedClasses = $constantClassType->getObjectClassNames();
1573: foreach ($referencedClasses as $referencedClass) {
1574: if (!$this->getReflectionProvider()->hasClass($referencedClass)) {
1575: continue;
1576: }
1577: $fetchedOnType = count($referencedClasses) === 1 ? $constantClassType : new ObjectType($referencedClass);
1578:
1579: $constantClassReflection = $this->getReflectionProvider()->getClass($referencedClass);
1580: if (!$constantClassReflection->hasConstant($constantName)) {
1581: if ($constantClassReflection->getName() === 'Attribute' && $constantName === 'TARGET_CONSTANT') {
1582: return new ConstantIntegerType(1 << 16);
1583: }
1584: continue;
1585: }
1586:
1587: if ($constantClassReflection->isEnum() && $constantClassReflection->hasEnumCase($constantName)) {
1588: $types[] = new EnumCaseObjectType($constantClassReflection->getName(), $constantName);
1589: continue;
1590: }
1591:
1592: $resolvingName = sprintf('%s::%s', $constantClassReflection->getName(), $constantName);
1593: if (array_key_exists($resolvingName, $this->currentlyResolvingClassConstant)) {
1594: $types[] = new MixedType();
1595: continue;
1596: }
1597:
1598: $cacheKey = $nativeTypesPromoted ? $resolvingName . '#native' : $resolvingName;
1599: if (!$isObject && array_key_exists($cacheKey, $this->classConstantValueTypeCache)) {
1600: $types[] = $this->classConstantValueTypeCache[$cacheKey];
1601: continue;
1602: }
1603:
1604: $this->currentlyResolvingClassConstant[$resolvingName] = true;
1605:
1606: if (!$isObject) {
1607: $reflectionConstant = $constantClassReflection->getNativeReflection()->getReflectionConstant($constantName);
1608: if ($reflectionConstant === false) {
1609: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1610: continue;
1611: }
1612: $reflectionConstantDeclaringClass = $reflectionConstant->getDeclaringClass();
1613: // the resolved type is cached: a class it names that does not exist is what the
1614: // declaring class declares depends on
1615: $this->valueDependencyCollector->enterDeclaration($reflectionConstantDeclaringClass->getFileName() ?: null, $reflectionConstantDeclaringClass->getName());
1616: try {
1617: $constantType = $this->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($reflectionConstantDeclaringClass->getName(), $reflectionConstantDeclaringClass->getFileName() ?: null));
1618: } finally {
1619: $this->valueDependencyCollector->leaveDeclaration();
1620: }
1621: $nativeType = null;
1622: if ($reflectionConstant->getType() !== null) {
1623: $nativeType = TypehintHelper::decideTypeFromReflection($reflectionConstant->getType(), selfClass: $constantClassReflection);
1624: }
1625: $phpDocType = $constantClassReflection->getConstantPhpDocType($constantName);
1626: $resolvedType = $this->transformStaticType($this->constantResolver->resolveClassConstantType(
1627: $constantClassReflection->getName(),
1628: $constantName,
1629: $constantType,
1630: $nativeType,
1631: $nativeTypesPromoted ? null : $phpDocType,
1632: ), $fetchedOnType);
1633: if ($phpDocType === null) {
1634: // the PHPDoc type is the only input that differs, so both variants share the resolved type
1635: $this->classConstantValueTypeCache[$resolvingName] = $resolvedType;
1636: $this->classConstantValueTypeCache[$resolvingName . '#native'] = $resolvedType;
1637: } else {
1638: $this->classConstantValueTypeCache[$cacheKey] = $resolvedType;
1639: }
1640: $types[] = $resolvedType;
1641: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1642: continue;
1643: }
1644:
1645: $constantReflection = $constantClassReflection->getConstant($constantName);
1646: if (
1647: !$constantClassReflection->isFinal()
1648: && !$constantReflection->isFinal()
1649: && ($nativeTypesPromoted || !$constantReflection->hasPhpDocType())
1650: && !$constantReflection->hasNativeType()
1651: ) {
1652: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1653: return new MixedType();
1654: }
1655:
1656: $nativeType = $constantReflection->getNativeType();
1657: if ($constantClassReflection->isFinal() || ($nativeTypesPromoted && $constantReflection->isFinal())) {
1658: $constantType = $this->getType($constantReflection->getValueExpr(), InitializerExprContext::fromClassReflection($constantReflection->getDeclaringClass()));
1659: } elseif ($nativeTypesPromoted && $nativeType !== null) {
1660: $constantType = $nativeType;
1661: } else {
1662: $constantType = $constantReflection->getValueType();
1663: }
1664:
1665: $constantType = $this->transformStaticType($this->constantResolver->resolveClassConstantType(
1666: $constantClassReflection->getName(),
1667: $constantName,
1668: $constantType,
1669: $nativeType,
1670: $nativeTypesPromoted ? null : $constantClassReflection->getConstantPhpDocType($constantName),
1671: ), $fetchedOnType);
1672: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1673: $types[] = $constantType;
1674: }
1675:
1676: if (count($types) > 0) {
1677: return TypeCombinator::union(...$types);
1678: }
1679:
1680: if (!$constantClassType->hasConstant($constantName)->yes()) {
1681: return new ErrorType();
1682: }
1683:
1684: return $this->transformStaticType($constantClassType->getConstant($constantName)->getValueType(), $constantClassType);
1685: }
1686:
1687: /**
1688: * Resolves `static` in the type of a class constant against the class
1689: * the constant is fetched on.
1690: */
1691: private function transformStaticType(Type $type, Type $fetchedOnType): Type
1692: {
1693: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($fetchedOnType): Type {
1694: if (!$type instanceof StaticType) {
1695: return $traverse($type);
1696: }
1697: if ($fetchedOnType instanceof StaticType) {
1698: return $traverse($type->changeBaseClass($fetchedOnType->getClassReflection()));
1699: }
1700: if ($type instanceof GenericStaticType) {
1701: $fetchedOnTypeReflections = $fetchedOnType->getObjectClassReflections();
1702: if (count($fetchedOnTypeReflections) === 1) {
1703: return $traverse($type->changeBaseClass($fetchedOnTypeReflections[0])->getStaticObjectType());
1704: }
1705: }
1706:
1707: return $fetchedOnType;
1708: });
1709: }
1710:
1711: /**
1712: * @param callable(Expr): Type $getTypeCallback
1713: */
1714: public function getClassConstFetchType(Name|Expr $class, string $constantName, ?string $className, callable $getTypeCallback): Type
1715: {
1716: $classReflection = null;
1717: if ($className !== null && $this->getReflectionProvider()->hasClass($className)) {
1718: $classReflection = $this->getReflectionProvider()->getClass($className);
1719: }
1720:
1721: return $this->getClassConstFetchTypeByReflection($class, $constantName, $classReflection, $getTypeCallback);
1722: }
1723:
1724: /**
1725: * @param callable(Expr): Type $getTypeCallback
1726: */
1727: public function getUnaryPlusType(Expr $expr, callable $getTypeCallback): Type
1728: {
1729: $type = $getTypeCallback($expr);
1730:
1731: $specifiedTypes = $this->unaryOperatorTypeSpecifyingExtensionRegistry
1732: ->callUnaryOperatorTypeSpecifyingExtensions('+', $type);
1733: if ($specifiedTypes !== null) {
1734: return $specifiedTypes;
1735: }
1736:
1737: return $type->toNumber();
1738: }
1739:
1740: /**
1741: * @param callable(Expr): Type $getTypeCallback
1742: */
1743: public function getUnaryMinusType(Expr $expr, callable $getTypeCallback): Type
1744: {
1745: $type = $getTypeCallback($expr);
1746:
1747: return $this->unaryOperatorTypeSpecifyingExtensionRegistry
1748: ->callUnaryOperatorTypeSpecifyingExtensions('-', $type)
1749: ?? $type->arithmeticNegate($this->phpVersion);
1750: }
1751:
1752: /**
1753: * @param callable(Expr): Type $getTypeCallback
1754: */
1755: public function getBitwiseNotType(Expr $expr, callable $getTypeCallback): Type
1756: {
1757: $exprType = $getTypeCallback($expr);
1758:
1759: $specifiedTypes = $this->unaryOperatorTypeSpecifyingExtensionRegistry
1760: ->callUnaryOperatorTypeSpecifyingExtensions('~', $exprType);
1761: if ($specifiedTypes !== null) {
1762: return $specifiedTypes;
1763: }
1764:
1765: return $this->getBitwiseNotTypeFromType($exprType);
1766: }
1767:
1768: public function getBitwiseNotTypeFromType(Type $exprType): Type
1769: {
1770: return $exprType->toBitwiseNotType();
1771: }
1772:
1773: private function resolveName(Name $name, ?ClassReflection $classReflection): string
1774: {
1775: $originalClass = (string) $name;
1776: if ($classReflection !== null) {
1777: $lowerClass = strtolower($originalClass);
1778:
1779: if (in_array($lowerClass, [
1780: 'self',
1781: 'static',
1782: ], true)) {
1783: return $classReflection->getName();
1784: } elseif ($lowerClass === 'parent') {
1785: if ($classReflection->getParentClass() !== null) {
1786: return $classReflection->getParentClass()->getName();
1787: }
1788: }
1789: }
1790:
1791: return $originalClass;
1792: }
1793:
1794: private function resolveTypeByName(Name $name, ?ClassReflection $classReflection): TypeWithClassName
1795: {
1796: if ($name->toLowerString() === 'static' && $classReflection !== null) {
1797: return new StaticType($classReflection);
1798: }
1799:
1800: $originalClass = $this->resolveName($name, $classReflection);
1801: if ($classReflection !== null) {
1802: $thisType = new ThisType($classReflection);
1803: $ancestor = $thisType->getAncestorWithClassName($originalClass);
1804: if ($ancestor !== null) {
1805: return $ancestor;
1806: }
1807: }
1808:
1809: return new ObjectType($originalClass);
1810: }
1811:
1812: private function resolveTypeByNameWithLateStaticBinding(Name $class, Type $classType, MethodReflection $methodReflectionCandidate): Type
1813: {
1814: if (
1815: $classType instanceof StaticType
1816: && !in_array($class->toLowerString(), ['self', 'static', 'parent'], true)
1817: ) {
1818: if ($methodReflectionCandidate->isStatic()) {
1819: $classType = $classType->getStaticObjectType();
1820: }
1821: }
1822:
1823: return $classType;
1824: }
1825:
1826: private function getReflectionProvider(): ReflectionProvider
1827: {
1828: return $this->reflectionProviderProvider->getReflectionProvider();
1829: }
1830:
1831: private function getNeverType(Type $leftType, Type $rightType): Type
1832: {
1833: // make sure we don't lose the explicit flag in the process
1834: if ($leftType instanceof NeverType && $leftType->isExplicit()) {
1835: return $leftType;
1836: }
1837: if ($rightType instanceof NeverType && $rightType->isExplicit()) {
1838: return $rightType;
1839: }
1840: return new NeverType();
1841: }
1842:
1843: }
1844: