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: $isList = null;
557: $hasOffsetValueTypes = [];
558: foreach ($expr->items as $arrayItem) {
559: $valueType = $getTypeCallback($arrayItem->value);
560: if ($arrayItem->unpack) {
561: $constantArrays = $valueType->getConstantArrays();
562: if (count($constantArrays) > 0) {
563: $totalArrays = count($constantArrays);
564:
565: // Unpacking merges string keys by name, while integer keys are always
566: // renumbered, so they're merged by their position among integer keys.
567: // A slot missing from some of the unpacked arrays becomes optional.
568: /** @var array<string, array{keyType: ConstantStringType|null, valueTypes: list<Type>, presentCount: int, anyOptional: bool}> $slots */
569: $slots = [];
570: /** @var list<string> $slotOrder */
571: $slotOrder = [];
572:
573: foreach ($constantArrays as $constantArrayType) {
574: $nextIntegerSlot = 0;
575: foreach ($constantArrayType->getKeyTypes() as $i => $keyType) {
576: if ($keepStringKeys && $keyType->isString()->yes()) {
577: $slotKey = 's' . $keyType->getValue();
578: $slotKeyType = $keyType;
579: } else {
580: $slotKey = 'i' . $nextIntegerSlot;
581: $slotKeyType = null;
582: $nextIntegerSlot++;
583: }
584:
585: if (!isset($slots[$slotKey])) {
586: $slots[$slotKey] = [
587: 'keyType' => $slotKeyType,
588: 'valueTypes' => [],
589: 'presentCount' => 0,
590: 'anyOptional' => false,
591: ];
592: $slotOrder[] = $slotKey;
593: }
594:
595: $slots[$slotKey]['valueTypes'][] = $constantArrayType->getValueTypes()[$i];
596: $slots[$slotKey]['presentCount']++;
597: if (!$constantArrayType->isOptionalKey($i)) {
598: continue;
599: }
600:
601: $slots[$slotKey]['anyOptional'] = true;
602: }
603: }
604:
605: foreach ($slotOrder as $slotKey) {
606: $slot = $slots[$slotKey];
607: $mergedValueType = TypeCombinator::union(...$slot['valueTypes']);
608: $isOptional = $slot['anyOptional'] || $slot['presentCount'] < $totalArrays;
609: $slotKeyType = $slot['keyType'];
610: $arrayBuilder->setOffsetValueType($slotKeyType, $mergedValueType, $isOptional);
611:
612: if ($slotKeyType === null) {
613: continue;
614: }
615:
616: $keyValue = $slotKeyType->getValue();
617: if (isset($hasOffsetValueTypes[$keyValue])) {
618: $hasOffsetValueTypes[$keyValue] = new HasOffsetValueType(
619: $slotKeyType,
620: $isOptional
621: ? TypeCombinator::union($hasOffsetValueTypes[$keyValue]->getValueType(), $mergedValueType)
622: : $mergedValueType,
623: );
624: } elseif (!$isOptional) {
625: $hasOffsetValueTypes[$keyValue] = new HasOffsetValueType($slotKeyType, $mergedValueType);
626: }
627: }
628: } else {
629: $arrayBuilder->degradeToGeneralArray();
630:
631: if ($keepStringKeys && !$valueType->getIterableKeyType()->isString()->no()) {
632: $isList = false;
633: $offsetType = $valueType->getIterableKeyType();
634:
635: foreach ($hasOffsetValueTypes as $key => $hasOffsetValueType) {
636: if (!$offsetType->isSuperTypeOf($hasOffsetValueType->getOffsetType())->yes()) {
637: continue;
638: }
639:
640: unset($hasOffsetValueTypes[$key]);
641: }
642: } else {
643: $isList ??= $arrayBuilder->isList();
644: $offsetType = new IntegerType();
645: }
646:
647: $arrayBuilder->setOffsetValueType($offsetType, $valueType->getIterableValueType(), !$valueType->isIterableAtLeastOnce()->yes());
648: }
649: } else {
650: $arrayBuilder->setOffsetValueType(
651: $arrayItem->key !== null ? $getTypeCallback($arrayItem->key) : null,
652: $valueType,
653: );
654: }
655: }
656:
657: $arrayType = $arrayBuilder->getArray();
658: if ($isList === true) {
659: $arrayType = TypeCombinator::intersect($arrayType, new AccessoryArrayListType());
660: }
661:
662: if (count($hasOffsetValueTypes) > 0 && !$arrayType->isConstantArray()->yes()) {
663: $arrayType = TypeCombinator::intersect($arrayType, ...array_values($hasOffsetValueTypes));
664: }
665:
666: return $arrayType;
667: }
668:
669: /**
670: * @param callable(Expr): Type $getTypeCallback
671: */
672: public function getCastType(Expr\Cast $expr, callable $getTypeCallback): Type
673: {
674: if ($expr instanceof \PhpParser\Node\Expr\Cast\Int_) {
675: return $getTypeCallback($expr->expr)->toInteger();
676: }
677: if ($expr instanceof Bool_) {
678: return $getTypeCallback($expr->expr)->toBoolean();
679: }
680: if ($expr instanceof Double) {
681: return $getTypeCallback($expr->expr)->toFloat();
682: }
683: if ($expr instanceof \PhpParser\Node\Expr\Cast\String_) {
684: return $getTypeCallback($expr->expr)->toString();
685: }
686: if ($expr instanceof Array_) {
687: return $getTypeCallback($expr->expr)->toArray();
688: }
689: if ($expr instanceof Object_) {
690: return $this->getCastObjectType($getTypeCallback($expr->expr));
691: }
692:
693: return new MixedType();
694: }
695:
696: public function getCastObjectType(Type $exprType): Type
697: {
698: $castToObject = static function (Type $type): Type {
699: $constantArrays = $type->getConstantArrays();
700: if (count($constantArrays) > 0) {
701: $objects = [];
702: foreach ($constantArrays as $constantArray) {
703: $properties = [];
704: $optionalProperties = [];
705: foreach ($constantArray->getKeyTypes() as $i => $keyType) {
706: $valueType = $constantArray->getValueTypes()[$i];
707: $optional = $constantArray->isOptionalKey($i);
708: if ($optional) {
709: $optionalProperties[] = $keyType->getValue();
710: }
711: $properties[$keyType->getValue()] = $valueType;
712: }
713:
714: $objects[] = new IntersectionType([new ObjectShapeType($properties, $optionalProperties), new ObjectType(stdClass::class)]);
715: }
716:
717: return TypeCombinator::union(...$objects);
718: }
719: if ($type->isObject()->yes()) {
720: return $type;
721: }
722:
723: return new ObjectType('stdClass');
724: };
725:
726: if ($exprType instanceof UnionType) {
727: return TypeCombinator::union(...array_map($castToObject, $exprType->getTypes()));
728: }
729:
730: return $castToObject($exprType);
731: }
732:
733: /**
734: * @param Name|Identifier|ComplexType|null $type
735: */
736: public function getFunctionType($type, bool $isNullable, bool $isVariadic, InitializerExprContext $context): Type
737: {
738: if ($isNullable) {
739: return TypeCombinator::addNull(
740: $this->getFunctionType($type, false, $isVariadic, $context),
741: );
742: }
743: if ($isVariadic) {
744: if ($this->phpVersion->supportsNamedArguments()) {
745: return new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $this->getFunctionType(
746: $type,
747: false,
748: false,
749: $context,
750: ));
751: }
752:
753: return new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $this->getFunctionType(
754: $type,
755: false,
756: false,
757: $context,
758: )), new AccessoryArrayListType()]);
759: }
760:
761: if ($type instanceof Name) {
762: $className = (string) $type;
763: $lowercasedClassName = strtolower($className);
764: if ($lowercasedClassName === 'parent') {
765: $classReflection = null;
766: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
767: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
768: }
769: if ($classReflection !== null && $classReflection->getParentClass() !== null) {
770: return new ObjectType($classReflection->getParentClass()->getName());
771: }
772:
773: return new NonexistentParentClassType();
774: }
775: }
776:
777: $classReflection = null;
778: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
779: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
780: }
781:
782: return ParserNodeTypeToPHPStanType::resolve($type, $classReflection);
783: }
784:
785: private function isParameterValueNullable(Param $parameter): bool
786: {
787: if ($parameter->default instanceof ConstFetch) {
788: return strtolower((string) $parameter->default->name) === 'null';
789: }
790:
791: return false;
792: }
793:
794: /**
795: * @param array<int, Type>|null $boundArgTypes the types of the bound arguments of a partial function application,
796: * keyed like its raw arguments; null to resolve them as constant expressions
797: */
798: public function getFirstClassCallableType(Expr\CallLike $expr, InitializerExprContext $context, bool $nativeTypesPromoted, ?array $boundArgTypes = null): Type
799: {
800: $partialApplicationArgs = null;
801: if (!$expr->isFirstClassCallable()) {
802: $partialApplicationArgs = $expr->getRawArgs();
803: if ($boundArgTypes === null) {
804: $boundArgTypes = [];
805: foreach ($partialApplicationArgs as $i => $arg) {
806: if (!$arg instanceof Arg) {
807: continue;
808: }
809: $boundArgTypes[$i] = $this->getType($arg->value, $context);
810: }
811: }
812: }
813:
814: if ($expr instanceof FuncCall) {
815: if ($expr->name instanceof Name) {
816: if ($this->getReflectionProvider()->hasFunction($expr->name, $context)) {
817: $function = $this->getReflectionProvider()->getFunction($expr->name, $context);
818: return $this->createFirstClassCallable(
819: $function,
820: $function->getVariants(),
821: $nativeTypesPromoted,
822: $partialApplicationArgs,
823: $boundArgTypes ?? [],
824: ClosureOrigin::forFunction($function->getName()),
825: );
826: }
827:
828: return new ObjectType(Closure::class);
829: }
830: }
831:
832: if ($expr instanceof Expr\StaticCall) {
833: if (!$expr->class instanceof Name) {
834: return new ObjectType(Closure::class);
835: }
836:
837: if (!$expr->name instanceof Identifier) {
838: return new ObjectType(Closure::class);
839: }
840:
841: $classReflection = null;
842: if ($context->getClassName() !== null && $this->getReflectionProvider()->hasClass($context->getClassName())) {
843: $classReflection = $this->getReflectionProvider()->getClass($context->getClassName());
844: }
845:
846: $classType = $this->resolveTypeByName($expr->class, $classReflection);
847: $methodName = $expr->name->toString();
848: if (!$classType->hasMethod($methodName)->yes()) {
849: return new ObjectType(Closure::class);
850: }
851:
852: $method = $classType->getMethod($methodName, new OutOfClassScope());
853: $classType = $this->resolveTypeByNameWithLateStaticBinding($expr->class, $classType, $method);
854: if (!$classType->hasMethod($methodName)->yes()) {
855: return new ObjectType(Closure::class);
856: }
857: $method = $classType->getMethod($methodName, new OutOfClassScope());
858:
859: return $this->createFirstClassCallable(
860: $method,
861: $method->getVariants(),
862: $nativeTypesPromoted,
863: $partialApplicationArgs,
864: $boundArgTypes ?? [],
865: ClosureOrigin::forMethod($classType, $methodName, true),
866: );
867: }
868:
869: if ($expr instanceof New_) {
870: return new ErrorType();
871: }
872:
873: throw new ShouldNotHappenException();
874: }
875:
876: /**
877: * @param ParametersAcceptor[] $variants
878: * @param array<Arg|ArgPlaceholder|VariadicPlaceholder>|null $partialApplicationArgs the arguments of a partial function application, null for a first-class callable
879: * @param array<int, Type> $boundArgTypes the types of the bound arguments of a partial function application, keyed like $partialApplicationArgs
880: * @param ClosureOrigin|null $origin the callee, whose call a call of the closure replays
881: */
882: public function createFirstClassCallable(
883: FunctionReflection|ExtendedMethodReflection|null $function,
884: array $variants,
885: bool $nativeTypesPromoted,
886: ?array $partialApplicationArgs = null,
887: array $boundArgTypes = [],
888: ?ClosureOrigin $origin = null,
889: ): Type
890: {
891: if ($origin !== null && $partialApplicationArgs !== null) {
892: $origin = $origin->withPartialApplication($partialApplicationArgs, $boundArgTypes);
893: }
894:
895: if ($partialApplicationArgs !== null && PartialFunctionApplicationParameters::leavesUnknownDefaultValue($variants, $partialApplicationArgs)) {
896: // creating the closure throws
897: return new ObjectType(Closure::class);
898: }
899:
900: // variants of multi-variant built-ins carry functionMap parameter names,
901: // but the closure accepts the native names as named arguments
902: $namedArgumentNames = [];
903: if ($function !== null) {
904: foreach ($function->getNamedArgumentsVariants() ?? [] as $namedArgumentsVariant) {
905: foreach ($namedArgumentsVariant->getParameters() as $i => $parameter) {
906: $namedArgumentNames[$i] = $parameter->getName();
907: }
908: }
909: }
910:
911: $closureTypes = [];
912:
913: foreach ($variants as $variant) {
914: $returnType = $variant->getReturnType();
915: if ($variant instanceof ExtendedParametersAcceptor) {
916: $returnType = $nativeTypesPromoted ? $variant->getNativeReturnType() : $returnType;
917: }
918:
919: $throwPoints = [];
920: $impurePoints = [];
921: $acceptsNamedArguments = TrinaryLogic::createYes();
922: $mustUseReturnValue = TrinaryLogic::createMaybe();
923: $isStaticClosure = TrinaryLogic::createMaybe();
924: if ($variant instanceof CallableParametersAcceptor) {
925: $throwPoints = $variant->getThrowPoints();
926: $impurePoints = $variant->getImpurePoints();
927: $acceptsNamedArguments = $variant->acceptsNamedArguments();
928: $mustUseReturnValue = $variant->mustUseReturnValue();
929: $isStaticClosure = $variant->isStaticClosure();
930: } elseif ($function !== null) {
931: $returnTypeForThrow = $variant->getReturnType();
932: $throwType = $function->getThrowType();
933: if ($throwType === null) {
934: if ($returnTypeForThrow instanceof NeverType && $returnTypeForThrow->isExplicit()) {
935: $throwType = new ObjectType(Throwable::class);
936: }
937: }
938:
939: if ($throwType !== null) {
940: if (!$throwType->isVoid()->yes()) {
941: $throwPoints[] = SimpleThrowPoint::createExplicit($throwType, true);
942: }
943: } else {
944: if (!(new ObjectType(Throwable::class))->isSuperTypeOf($returnTypeForThrow)->yes()) {
945: $throwPoints[] = SimpleThrowPoint::createImplicit();
946: }
947: }
948:
949: $impurePoint = SimpleImpurePoint::createFromVariant($function, $variant);
950: if ($impurePoint !== null) {
951: $impurePoints[] = $impurePoint;
952: }
953:
954: $acceptsNamedArguments = $function->acceptsNamedArguments();
955: $mustUseReturnValue = $function->mustUseReturnValue();
956: // binding an object to the closure of a static method, or to a partial
957: // application of a function, fails; a function's first-class callable can be bound
958: if ($function instanceof ExtendedMethodReflection ? $function->isStatic() : $partialApplicationArgs !== null) {
959: $isStaticClosure = TrinaryLogic::createYes();
960: }
961: }
962:
963: $parameters = $variant->getParameters();
964: if (count($namedArgumentNames) > 0) {
965: $parameters = self::renameParameters($parameters, $namedArgumentNames);
966: }
967: $isVariadic = $variant->isVariadic();
968: $templateTypeMap = $variant->getTemplateTypeMap();
969: $variantOrigin = $origin;
970: if ($partialApplicationArgs !== null) {
971: $partialApplication = PartialFunctionApplicationParameters::apply($parameters, $isVariadic, $partialApplicationArgs, $boundArgTypes, $returnType, $templateTypeMap);
972: if ($partialApplication === null) {
973: // creating the closure from this variant throws
974: continue;
975: }
976: [$parameters, $isVariadic, $returnType, $templateTypeMap, $boundParameterNames] = $partialApplication;
977: $magicMethodParameterNames = PartialFunctionApplicationParameters::getMagicMethodParameterNames($function, $partialApplicationArgs);
978: if ($magicMethodParameterNames === null) {
979: continue;
980: }
981: $parameters = self::renameParameters($parameters, $magicMethodParameterNames);
982: if ($variantOrigin !== null) {
983: $variantOrigin = $variantOrigin->withBoundParameterNames($boundParameterNames);
984: }
985: }
986:
987: $templateTags = [];
988: foreach ($templateTypeMap->getTypes() as $templateType) {
989: if (!$templateType instanceof TemplateType) {
990: continue;
991: }
992: $templateTags[$templateType->getName()] = new TemplateTag(
993: $templateType->getName(),
994: $templateType->getBound(),
995: $templateType->getDefault(),
996: $templateType->getVariance(),
997: );
998: }
999: if ($function !== null) {
1000: $assertions = $function->getAsserts();
1001: } elseif ($variant instanceof CallableParametersAcceptor) {
1002: $assertions = $variant->getAsserts();
1003: } else {
1004: $assertions = Assertions::createEmpty();
1005: }
1006:
1007: // a conditional return type referencing the function's own parameter,
1008: // like @return ($value is int ? true : false) on is_int(),
1009: // also becomes a type predicate of the resulting Closure
1010: $assertions = CallableAssertionsHelper::withConditionalReturnPredicate($assertions, $variant);
1011: $closureTypes[] = new ClosureType(
1012: $parameters,
1013: $returnType,
1014: $isVariadic,
1015: $templateTypeMap,
1016: $variant->getResolvedTemplateTypeMap(),
1017: $variant instanceof ExtendedParametersAcceptor ? $variant->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
1018: $templateTags,
1019: $throwPoints,
1020: $impurePoints,
1021: acceptsNamedArguments: $acceptsNamedArguments,
1022: mustUseReturnValue: $mustUseReturnValue,
1023: assertions: $assertions,
1024: isStatic: $isStaticClosure,
1025: origin: $variantOrigin,
1026: );
1027: }
1028:
1029: if ($partialApplicationArgs !== null && count($closureTypes) === 0) {
1030: return new ObjectType(Closure::class);
1031: }
1032:
1033: return TypeCombinator::union(...$closureTypes);
1034: }
1035:
1036: /**
1037: * @param list<ParameterReflection> $parameters
1038: * @param array<int, string> $names
1039: * @return list<ParameterReflection>
1040: */
1041: private static function renameParameters(array $parameters, array $names): array
1042: {
1043: $renamed = [];
1044: foreach ($parameters as $i => $parameter) {
1045: if (
1046: !isset($names[$i])
1047: || $names[$i] === $parameter->getName()
1048: || !$parameter instanceof ExtendedParameterReflection
1049: ) {
1050: $renamed[] = $parameter;
1051: continue;
1052: }
1053:
1054: $renamed[] = new ExtendedDummyParameter(
1055: $names[$i],
1056: $parameter->getType(),
1057: $parameter->isOptional(),
1058: $parameter->passedByReference(),
1059: $parameter->isVariadic(),
1060: $parameter->getDefaultValue(),
1061: $parameter->getNativeType(),
1062: $parameter->getPhpDocType(),
1063: $parameter->getOutType(),
1064: $parameter->isImmediatelyInvokedCallable(),
1065: $parameter->getClosureThisType(),
1066: $parameter->getAttributes(),
1067: $parameter->getAllowedConstants(),
1068: $parameter->isPureUnlessCallableIsImpureParameter(),
1069: $parameter->isPureUnlessParameterPassedParameter(),
1070: );
1071: }
1072:
1073: return $renamed;
1074: }
1075:
1076: /**
1077: * @param callable(Expr): Type $getTypeCallback
1078: */
1079: public function getBitwiseAndType(Expr $left, Expr $right, callable $getTypeCallback): Type
1080: {
1081: $leftType = $getTypeCallback($left);
1082: $rightType = $getTypeCallback($right);
1083:
1084: return $this->operatorTypeSpecifyingExtensionRegistry
1085: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseAnd($left, $right), $leftType, $rightType)
1086: ?? $leftType->bitwiseAnd($rightType, $this->phpVersion);
1087: }
1088:
1089: /**
1090: * @param callable(Expr): Type $getTypeCallback
1091: */
1092: public function getBitwiseOrType(Expr $left, Expr $right, callable $getTypeCallback): Type
1093: {
1094: $leftType = $getTypeCallback($left);
1095: $rightType = $getTypeCallback($right);
1096:
1097: return $this->operatorTypeSpecifyingExtensionRegistry
1098: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseOr($left, $right), $leftType, $rightType)
1099: ?? $leftType->bitwiseOr($rightType, $this->phpVersion);
1100: }
1101:
1102: /**
1103: * @param callable(Expr): Type $getTypeCallback
1104: */
1105: public function getBitwiseXorType(Expr $left, Expr $right, callable $getTypeCallback): Type
1106: {
1107: $leftType = $getTypeCallback($left);
1108: $rightType = $getTypeCallback($right);
1109:
1110: return $this->operatorTypeSpecifyingExtensionRegistry
1111: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\BitwiseXor($left, $right), $leftType, $rightType)
1112: ?? $leftType->bitwiseXor($rightType, $this->phpVersion);
1113: }
1114:
1115: /**
1116: * @param callable(Expr): Type $getTypeCallback
1117: */
1118: public function getSpaceshipType(Expr $left, Expr $right, callable $getTypeCallback): Type
1119: {
1120: $leftTypes = $getTypeCallback($left);
1121: $rightTypes = $getTypeCallback($right);
1122:
1123: if ($leftTypes instanceof NeverType || $rightTypes instanceof NeverType) {
1124: return $this->getNeverType($leftTypes, $rightTypes);
1125: }
1126:
1127: $leftValues = $leftTypes->getConstantScalarValues();
1128: $rightValues = $rightTypes->getConstantScalarValues();
1129:
1130: $leftValuesCount = count($leftValues);
1131: $rightValuesCount = count($rightValues);
1132: if ($leftValuesCount > 0 && $rightValuesCount > 0 && $leftValuesCount * $rightValuesCount <= self::CALCULATE_SCALARS_LIMIT) {
1133: $resultTypes = [];
1134: foreach ($leftValues as $leftValue) {
1135: foreach ($rightValues as $rightValue) {
1136: $resultType = new ConstantIntegerType(ValueSet::compareScalarValues($leftValue, $rightValue, $this->phpVersion) ?? 1);
1137: $resultTypes[] = $resultType;
1138: }
1139: }
1140: return TypeCombinator::union(...$resultTypes);
1141: }
1142:
1143: return IntegerRangeType::fromInterval(-1, 1);
1144: }
1145:
1146: /**
1147: * @param callable(Expr): Type $getTypeCallback
1148: */
1149: public function getDivType(Expr $left, Expr $right, callable $getTypeCallback): Type
1150: {
1151: $leftType = $getTypeCallback($left);
1152: $rightType = $getTypeCallback($right);
1153:
1154: $specifiedTypes = $this->operatorTypeSpecifyingExtensionRegistry
1155: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Div($left, $right), $leftType, $rightType);
1156: if ($specifiedTypes !== null) {
1157: return $specifiedTypes;
1158: }
1159:
1160: $result = $leftType->arithmeticDivide($rightType, $this->phpVersion);
1161:
1162: // the remainder can be narrowed in the scope, e.g. by `$a % $b === 0`
1163: if ($leftType->isInteger()->yes() && $rightType->isInteger()->yes()) {
1164: $modType = $getTypeCallback(new BinaryOp\Mod($left, $right));
1165: if ($modType->isInteger()->yes() && (new ConstantIntegerType(0))->isSuperTypeOf($modType)->yes()) {
1166: $withoutFloat = TypeCombinator::remove($result, new FloatType());
1167:
1168: // PHP_INT_MIN / -1 divides without a remainder but still overflows to a float
1169: if (!$withoutFloat instanceof NeverType) {
1170: return $withoutFloat;
1171: }
1172: }
1173: }
1174:
1175: return $result;
1176: }
1177:
1178: /**
1179: * @param callable(Expr): Type $getTypeCallback
1180: */
1181: public function getModType(Expr $left, Expr $right, callable $getTypeCallback): Type
1182: {
1183: $leftType = $getTypeCallback($left);
1184: $rightType = $getTypeCallback($right);
1185:
1186: return $this->operatorTypeSpecifyingExtensionRegistry
1187: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mod($left, $right), $leftType, $rightType)
1188: ?? $leftType->arithmeticModulo($rightType, $this->phpVersion);
1189: }
1190:
1191: /**
1192: * @param callable(Expr): Type $getTypeCallback
1193: */
1194: public function getPlusType(Expr $left, Expr $right, callable $getTypeCallback): Type
1195: {
1196: $leftType = $getTypeCallback($left);
1197: $rightType = $getTypeCallback($right);
1198:
1199: return $this->operatorTypeSpecifyingExtensionRegistry
1200: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Plus($left, $right), $leftType, $rightType)
1201: ?? $leftType->arithmeticAdd($rightType, $this->phpVersion);
1202: }
1203:
1204: /**
1205: * @param callable(Expr): Type $getTypeCallback
1206: */
1207: public function getMinusType(Expr $left, Expr $right, callable $getTypeCallback): Type
1208: {
1209: $leftType = $getTypeCallback($left);
1210: $rightType = $getTypeCallback($right);
1211:
1212: return $this->operatorTypeSpecifyingExtensionRegistry
1213: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Minus($left, $right), $leftType, $rightType)
1214: ?? $leftType->arithmeticSubtract($rightType, $this->phpVersion);
1215: }
1216:
1217: /**
1218: * @param callable(Expr): Type $getTypeCallback
1219: */
1220: public function getMulType(Expr $left, Expr $right, callable $getTypeCallback): Type
1221: {
1222: $leftType = $getTypeCallback($left);
1223: $rightType = $getTypeCallback($right);
1224:
1225: return $this->operatorTypeSpecifyingExtensionRegistry
1226: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Mul($left, $right), $leftType, $rightType)
1227: ?? $leftType->arithmeticMultiply($rightType, $this->phpVersion);
1228: }
1229:
1230: /**
1231: * @param callable(Expr): Type $getTypeCallback
1232: */
1233: public function getPowType(Expr $left, Expr $right, callable $getTypeCallback): Type
1234: {
1235: $leftType = $getTypeCallback($left);
1236: $rightType = $getTypeCallback($right);
1237:
1238: return $this->operatorTypeSpecifyingExtensionRegistry
1239: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\Pow($left, $right), $leftType, $rightType)
1240: ?? $leftType->arithmeticPower($rightType, $this->phpVersion);
1241: }
1242:
1243: /**
1244: * @param callable(Expr): Type $getTypeCallback
1245: */
1246: public function getShiftLeftType(Expr $left, Expr $right, callable $getTypeCallback): Type
1247: {
1248: $leftType = $getTypeCallback($left);
1249: $rightType = $getTypeCallback($right);
1250:
1251: return $this->operatorTypeSpecifyingExtensionRegistry
1252: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\ShiftLeft($left, $right), $leftType, $rightType)
1253: ?? $leftType->bitwiseShiftLeft($rightType, $this->phpVersion);
1254: }
1255:
1256: /**
1257: * @param callable(Expr): Type $getTypeCallback
1258: */
1259: public function getShiftRightType(Expr $left, Expr $right, callable $getTypeCallback): Type
1260: {
1261: $leftType = $getTypeCallback($left);
1262: $rightType = $getTypeCallback($right);
1263:
1264: return $this->operatorTypeSpecifyingExtensionRegistry
1265: ->callOperatorTypeSpecifyingExtensions(new BinaryOp\ShiftRight($left, $right), $leftType, $rightType)
1266: ?? $leftType->bitwiseShiftRight($rightType, $this->phpVersion);
1267: }
1268:
1269: /**
1270: * @return TypeResult<BooleanType>
1271: */
1272: public function resolveIdenticalType(Type $leftType, Type $rightType): TypeResult
1273: {
1274: if ($leftType instanceof NeverType || $rightType instanceof NeverType) {
1275: return new TypeResult(new ConstantBooleanType(false), []);
1276: }
1277:
1278: if ($leftType instanceof ConstantScalarType && $rightType instanceof ConstantScalarType) {
1279: return new TypeResult(new ConstantBooleanType($leftType->getValue() === $rightType->getValue()), []);
1280: }
1281:
1282: $leftTypeFiniteTypes = $leftType->getFiniteTypes();
1283: $rightTypeFiniteType = $rightType->getFiniteTypes();
1284: if (count($leftTypeFiniteTypes) === 1 && count($rightTypeFiniteType) === 1) {
1285: return new TypeResult(new ConstantBooleanType($leftTypeFiniteTypes[0]->equals($rightTypeFiniteType[0])), []);
1286: }
1287:
1288: $leftIsSuperTypeOfRight = $leftType->isSuperTypeOf($rightType);
1289: $rightIsSuperTypeOfLeft = $rightType->isSuperTypeOf($leftType);
1290: if ($leftIsSuperTypeOfRight->no() && $rightIsSuperTypeOfLeft->no()) {
1291: return new TypeResult(new ConstantBooleanType(false), array_merge($leftIsSuperTypeOfRight->getReasons(), $rightIsSuperTypeOfLeft->getReasons()));
1292: }
1293:
1294: if ($leftType instanceof ConstantArrayType && $rightType instanceof ConstantArrayType) {
1295: return $this->resolveConstantArrayTypeComparison($leftType, $rightType, fn ($leftValueType, $rightValueType): TypeResult => $this->resolveIdenticalType($leftValueType, $rightValueType));
1296: }
1297:
1298: return new TypeResult(new BooleanType(), []);
1299: }
1300:
1301: /**
1302: * @return TypeResult<BooleanType>
1303: */
1304: public function resolveEqualType(Type $leftType, Type $rightType, ?PhpVersions $phpVersions = null): TypeResult
1305: {
1306: if ($leftType instanceof NeverType || $rightType instanceof NeverType) {
1307: return new TypeResult(new ConstantBooleanType(false), []);
1308: }
1309:
1310: if (
1311: ($leftType->isEnum()->yes() && $rightType->isTrue()->no())
1312: || ($rightType->isEnum()->yes() && $leftType->isTrue()->no())
1313: ) {
1314: return $this->resolveIdenticalType($leftType, $rightType);
1315: }
1316:
1317: $versions = $phpVersions !== null ? $phpVersions->getLooseComparisonVersions() : [$this->phpVersion];
1318:
1319: // same-type sides cannot coerce - loose equals strict, except for
1320: // two numeric strings, which compare as numbers
1321: if (
1322: ($leftType->isString()->yes() && $rightType->isString()->yes() && (self::isNonNumericString($leftType, $versions) || self::isNonNumericString($rightType, $versions)))
1323: || ($leftType->isInteger()->yes() && $rightType->isInteger()->yes())
1324: ) {
1325: return $this->resolveIdenticalType($leftType, $rightType);
1326: }
1327:
1328: if ($leftType instanceof ConstantArrayType && $rightType instanceof ConstantArrayType) {
1329: return $this->resolveConstantArrayTypeComparison($leftType, $rightType, fn ($leftValueType, $rightValueType): TypeResult => $this->resolveEqualType($leftValueType, $rightValueType, $phpVersions));
1330: }
1331:
1332: // constant only when every PHP version agrees
1333: $result = $leftType->looseCompare($rightType, $versions[0]);
1334: foreach (array_slice($versions, 1) as $version) {
1335: if (!$result->equals($leftType->looseCompare($rightType, $version))) {
1336: $result = new BooleanType();
1337: break;
1338: }
1339: }
1340: if ($result->isTrue()->yes() || $result->isFalse()->yes()) {
1341: return new TypeResult($result, []);
1342: }
1343:
1344: // either side's possibly loosely equal type in any version rules the other side out
1345: foreach ([[$leftType, $rightType], [$rightType, $leftType]] as [$type, $otherType]) {
1346: $possiblyEqualTypes = [];
1347: foreach ($versions as $version) {
1348: $possiblyEqualTypes[] = $type->getPossiblyLooselyEqualType($version);
1349: }
1350: if (TypeCombinator::union(...$possiblyEqualTypes)->isSuperTypeOf($otherType)->no()) {
1351: return new TypeResult(new ConstantBooleanType(false), []);
1352: }
1353: }
1354:
1355: // either side's always loosely equal type in every version holds the other side
1356: foreach ([[$leftType, $rightType], [$rightType, $leftType]] as [$type, $otherType]) {
1357: $alwaysEqualTypes = [];
1358: foreach ($versions as $version) {
1359: $alwaysEqualTypes[] = $type->getAlwaysLooselyEqualType($version);
1360: }
1361: if (TypeCombinator::intersect(...$alwaysEqualTypes)->isSuperTypeOf($otherType)->yes()) {
1362: return new TypeResult(new ConstantBooleanType(true), []);
1363: }
1364: }
1365:
1366: return new TypeResult($result, []);
1367: }
1368:
1369: /**
1370: * Whether the strings are numeric in none of the PHP versions. A constant
1371: * string's isNumericString() follows the PHP version running PHPStan,
1372: * while '1 ' is numeric since PHP 8.0 only.
1373: *
1374: * @param non-empty-list<PhpVersion> $phpVersions
1375: */
1376: private static function isNonNumericString(Type $type, array $phpVersions): bool
1377: {
1378: if (!$type->isNumericString()->no()) {
1379: return false;
1380: }
1381:
1382: foreach ($type->getConstantStrings() as $constantString) {
1383: foreach ($phpVersions as $phpVersion) {
1384: if (StringSet::parseNumericString($constantString->getValue(), $phpVersion) !== null) {
1385: return false;
1386: }
1387: }
1388: }
1389:
1390: return true;
1391: }
1392:
1393: /**
1394: * @param callable(Type, Type): TypeResult<BooleanType> $valueComparisonCallback
1395: * @return TypeResult<BooleanType>
1396: */
1397: private function resolveConstantArrayTypeComparison(ConstantArrayType $leftType, ConstantArrayType $rightType, callable $valueComparisonCallback): TypeResult
1398: {
1399: $leftKeyTypes = $leftType->getKeyTypes();
1400: $rightKeyTypes = $rightType->getKeyTypes();
1401: $leftValueTypes = $leftType->getValueTypes();
1402: $rightValueTypes = $rightType->getValueTypes();
1403:
1404: $resultType = new ConstantBooleanType(true);
1405:
1406: foreach ($leftKeyTypes as $i => $leftKeyType) {
1407: $leftOptional = $leftType->isOptionalKey($i);
1408: if ($leftOptional) {
1409: $resultType = new BooleanType();
1410: }
1411:
1412: if (count($rightKeyTypes) === 0) {
1413: if (!$leftOptional) {
1414: return new TypeResult(new ConstantBooleanType(false), []);
1415: }
1416: continue;
1417: }
1418:
1419: $found = false;
1420: foreach ($rightKeyTypes as $j => $rightKeyType) {
1421: unset($rightKeyTypes[$j]);
1422:
1423: if ($leftKeyType->equals($rightKeyType)) {
1424: $found = true;
1425: break;
1426: } elseif (!$rightType->isOptionalKey($j)) {
1427: return new TypeResult(new ConstantBooleanType(false), []);
1428: }
1429: }
1430:
1431: if (!$found) {
1432: if (!$leftOptional) {
1433: return new TypeResult(new ConstantBooleanType(false), []);
1434: }
1435: continue;
1436: }
1437:
1438: if (!isset($j)) {
1439: throw new ShouldNotHappenException();
1440: }
1441:
1442: $rightOptional = $rightType->isOptionalKey($j);
1443: if ($rightOptional) {
1444: $resultType = new BooleanType();
1445: if ($leftOptional) {
1446: continue;
1447: }
1448: }
1449:
1450: $leftIdenticalToRightResult = $valueComparisonCallback($leftValueTypes[$i], $rightValueTypes[$j]);
1451: $leftIdenticalToRight = $leftIdenticalToRightResult->type;
1452: if ($leftIdenticalToRight->isFalse()->yes()) {
1453: return $leftIdenticalToRightResult;
1454: }
1455: $resultType = TypeCombinator::union($resultType, $leftIdenticalToRight);
1456: }
1457:
1458: foreach (array_keys($rightKeyTypes) as $j) {
1459: if (!$rightType->isOptionalKey($j)) {
1460: return new TypeResult(new ConstantBooleanType(false), []);
1461: }
1462: $resultType = new BooleanType();
1463: }
1464:
1465: return new TypeResult($resultType->toBoolean(), []);
1466: }
1467:
1468: /**
1469: * With $nativeTypesPromoted, PHPDoc types of the constants are ignored:
1470: * a constant that can be overridden in a child class resolves only to its native type.
1471: *
1472: * @param callable(Expr): Type $getTypeCallback
1473: */
1474: public function getClassConstFetchTypeByReflection(Name|Expr $class, string $constantName, ?ClassReflection $classReflection, callable $getTypeCallback, bool $nativeTypesPromoted = false): Type
1475: {
1476: $isObject = false;
1477: if ($class instanceof Name) {
1478: $constantClass = (string) $class;
1479: $constantClassType = new ObjectType($constantClass);
1480: $namesToResolve = [
1481: 'self',
1482: 'parent',
1483: ];
1484: if ($classReflection !== null) {
1485: if ($classReflection->isFinal()) {
1486: $namesToResolve[] = 'static';
1487: } elseif (strtolower($constantClass) === 'static') {
1488: if (strtolower($constantName) === 'class') {
1489: return new GenericClassStringType(new StaticType($classReflection));
1490: }
1491:
1492: $namesToResolve[] = 'static';
1493: $isObject = true;
1494: }
1495: }
1496: if (in_array(strtolower($constantClass), $namesToResolve, true)) {
1497: $resolvedName = $this->resolveName($class, $classReflection);
1498: if (strtolower($resolvedName) === 'parent' && strtolower($constantName) === 'class') {
1499: return new ClassStringType();
1500: }
1501: $constantClassType = $this->resolveTypeByName($class, $classReflection);
1502: }
1503:
1504: if (strtolower($constantName) === 'class') {
1505: return new ConstantStringType($constantClassType->getClassName(), true);
1506: }
1507: } elseif ($class instanceof String_ && strtolower($constantName) === 'class') {
1508: return new ConstantStringType($class->value, true);
1509: } else {
1510: $constantClassType = $getTypeCallback($class);
1511: $isObject = true;
1512: }
1513:
1514: if (strtolower($constantName) === 'class') {
1515: return $constantClassType->toClassConstantType($this->getReflectionProvider());
1516: }
1517:
1518: if ($constantClassType->isClassString()->yes()) {
1519: if ($constantClassType->isConstantScalarValue()->yes()) {
1520: $isObject = false;
1521: }
1522: $constantClassType = $constantClassType->getClassStringObjectType();
1523: }
1524:
1525: $types = [];
1526: $referencedClasses = $constantClassType->getObjectClassNames();
1527: foreach ($referencedClasses as $referencedClass) {
1528: if (!$this->getReflectionProvider()->hasClass($referencedClass)) {
1529: continue;
1530: }
1531: $fetchedOnType = count($referencedClasses) === 1 ? $constantClassType : new ObjectType($referencedClass);
1532:
1533: $constantClassReflection = $this->getReflectionProvider()->getClass($referencedClass);
1534: if (!$constantClassReflection->hasConstant($constantName)) {
1535: if ($constantClassReflection->getName() === 'Attribute' && $constantName === 'TARGET_CONSTANT') {
1536: return new ConstantIntegerType(1 << 16);
1537: }
1538: continue;
1539: }
1540:
1541: if ($constantClassReflection->isEnum() && $constantClassReflection->hasEnumCase($constantName)) {
1542: $types[] = new EnumCaseObjectType($constantClassReflection->getName(), $constantName);
1543: continue;
1544: }
1545:
1546: $resolvingName = sprintf('%s::%s', $constantClassReflection->getName(), $constantName);
1547: if (array_key_exists($resolvingName, $this->currentlyResolvingClassConstant)) {
1548: $types[] = new MixedType();
1549: continue;
1550: }
1551:
1552: $cacheKey = $nativeTypesPromoted ? $resolvingName . '#native' : $resolvingName;
1553: if (!$isObject && array_key_exists($cacheKey, $this->classConstantValueTypeCache)) {
1554: $types[] = $this->classConstantValueTypeCache[$cacheKey];
1555: continue;
1556: }
1557:
1558: $this->currentlyResolvingClassConstant[$resolvingName] = true;
1559:
1560: if (!$isObject) {
1561: $reflectionConstant = $constantClassReflection->getNativeReflection()->getReflectionConstant($constantName);
1562: if ($reflectionConstant === false) {
1563: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1564: continue;
1565: }
1566: $reflectionConstantDeclaringClass = $reflectionConstant->getDeclaringClass();
1567: // the resolved type is cached: a class it names that does not exist is what the
1568: // declaring class declares depends on
1569: $this->valueDependencyCollector->enterDeclaration($reflectionConstantDeclaringClass->getFileName() ?: null, $reflectionConstantDeclaringClass->getName());
1570: try {
1571: $constantType = $this->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($reflectionConstantDeclaringClass->getName(), $reflectionConstantDeclaringClass->getFileName() ?: null));
1572: } finally {
1573: $this->valueDependencyCollector->leaveDeclaration();
1574: }
1575: $nativeType = null;
1576: if ($reflectionConstant->getType() !== null) {
1577: $nativeType = TypehintHelper::decideTypeFromReflection($reflectionConstant->getType(), selfClass: $constantClassReflection);
1578: }
1579: $phpDocType = $constantClassReflection->getConstantPhpDocType($constantName);
1580: $resolvedType = $this->transformStaticType($this->constantResolver->resolveClassConstantType(
1581: $constantClassReflection->getName(),
1582: $constantName,
1583: $constantType,
1584: $nativeType,
1585: $nativeTypesPromoted ? null : $phpDocType,
1586: ), $fetchedOnType);
1587: if ($phpDocType === null) {
1588: // the PHPDoc type is the only input that differs, so both variants share the resolved type
1589: $this->classConstantValueTypeCache[$resolvingName] = $resolvedType;
1590: $this->classConstantValueTypeCache[$resolvingName . '#native'] = $resolvedType;
1591: } else {
1592: $this->classConstantValueTypeCache[$cacheKey] = $resolvedType;
1593: }
1594: $types[] = $resolvedType;
1595: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1596: continue;
1597: }
1598:
1599: $constantReflection = $constantClassReflection->getConstant($constantName);
1600: if (
1601: !$constantClassReflection->isFinal()
1602: && !$constantReflection->isFinal()
1603: && ($nativeTypesPromoted || !$constantReflection->hasPhpDocType())
1604: && !$constantReflection->hasNativeType()
1605: ) {
1606: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1607: return new MixedType();
1608: }
1609:
1610: $nativeType = $constantReflection->getNativeType();
1611: if ($constantClassReflection->isFinal() || ($nativeTypesPromoted && $constantReflection->isFinal())) {
1612: $constantType = $this->getType($constantReflection->getValueExpr(), InitializerExprContext::fromClassReflection($constantReflection->getDeclaringClass()));
1613: } elseif ($nativeTypesPromoted && $nativeType !== null) {
1614: $constantType = $nativeType;
1615: } else {
1616: $constantType = $constantReflection->getValueType();
1617: }
1618:
1619: $constantType = $this->transformStaticType($this->constantResolver->resolveClassConstantType(
1620: $constantClassReflection->getName(),
1621: $constantName,
1622: $constantType,
1623: $nativeType,
1624: $nativeTypesPromoted ? null : $constantClassReflection->getConstantPhpDocType($constantName),
1625: ), $fetchedOnType);
1626: unset($this->currentlyResolvingClassConstant[$resolvingName]);
1627: $types[] = $constantType;
1628: }
1629:
1630: if (count($types) > 0) {
1631: return TypeCombinator::union(...$types);
1632: }
1633:
1634: if (!$constantClassType->hasConstant($constantName)->yes()) {
1635: return new ErrorType();
1636: }
1637:
1638: return $this->transformStaticType($constantClassType->getConstant($constantName)->getValueType(), $constantClassType);
1639: }
1640:
1641: /**
1642: * Resolves `static` in the type of a class constant against the class
1643: * the constant is fetched on.
1644: */
1645: private function transformStaticType(Type $type, Type $fetchedOnType): Type
1646: {
1647: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($fetchedOnType): Type {
1648: if (!$type instanceof StaticType) {
1649: return $traverse($type);
1650: }
1651: if ($fetchedOnType instanceof StaticType) {
1652: return $traverse($type->changeBaseClass($fetchedOnType->getClassReflection()));
1653: }
1654: if ($type instanceof GenericStaticType) {
1655: $fetchedOnTypeReflections = $fetchedOnType->getObjectClassReflections();
1656: if (count($fetchedOnTypeReflections) === 1) {
1657: return $traverse($type->changeBaseClass($fetchedOnTypeReflections[0])->getStaticObjectType());
1658: }
1659: }
1660:
1661: return $fetchedOnType;
1662: });
1663: }
1664:
1665: /**
1666: * @param callable(Expr): Type $getTypeCallback
1667: */
1668: public function getClassConstFetchType(Name|Expr $class, string $constantName, ?string $className, callable $getTypeCallback): Type
1669: {
1670: $classReflection = null;
1671: if ($className !== null && $this->getReflectionProvider()->hasClass($className)) {
1672: $classReflection = $this->getReflectionProvider()->getClass($className);
1673: }
1674:
1675: return $this->getClassConstFetchTypeByReflection($class, $constantName, $classReflection, $getTypeCallback);
1676: }
1677:
1678: /**
1679: * @param callable(Expr): Type $getTypeCallback
1680: */
1681: public function getUnaryPlusType(Expr $expr, callable $getTypeCallback): Type
1682: {
1683: $type = $getTypeCallback($expr);
1684:
1685: $specifiedTypes = $this->unaryOperatorTypeSpecifyingExtensionRegistry
1686: ->callUnaryOperatorTypeSpecifyingExtensions('+', $type);
1687: if ($specifiedTypes !== null) {
1688: return $specifiedTypes;
1689: }
1690:
1691: return $type->toNumber();
1692: }
1693:
1694: /**
1695: * @param callable(Expr): Type $getTypeCallback
1696: */
1697: public function getUnaryMinusType(Expr $expr, callable $getTypeCallback): Type
1698: {
1699: $type = $getTypeCallback($expr);
1700:
1701: return $this->unaryOperatorTypeSpecifyingExtensionRegistry
1702: ->callUnaryOperatorTypeSpecifyingExtensions('-', $type)
1703: ?? $type->arithmeticNegate($this->phpVersion);
1704: }
1705:
1706: /**
1707: * @param callable(Expr): Type $getTypeCallback
1708: */
1709: public function getBitwiseNotType(Expr $expr, callable $getTypeCallback): Type
1710: {
1711: $exprType = $getTypeCallback($expr);
1712:
1713: $specifiedTypes = $this->unaryOperatorTypeSpecifyingExtensionRegistry
1714: ->callUnaryOperatorTypeSpecifyingExtensions('~', $exprType);
1715: if ($specifiedTypes !== null) {
1716: return $specifiedTypes;
1717: }
1718:
1719: return $this->getBitwiseNotTypeFromType($exprType);
1720: }
1721:
1722: public function getBitwiseNotTypeFromType(Type $exprType): Type
1723: {
1724: return $exprType->toBitwiseNotType();
1725: }
1726:
1727: private function resolveName(Name $name, ?ClassReflection $classReflection): string
1728: {
1729: $originalClass = (string) $name;
1730: if ($classReflection !== null) {
1731: $lowerClass = strtolower($originalClass);
1732:
1733: if (in_array($lowerClass, [
1734: 'self',
1735: 'static',
1736: ], true)) {
1737: return $classReflection->getName();
1738: } elseif ($lowerClass === 'parent') {
1739: if ($classReflection->getParentClass() !== null) {
1740: return $classReflection->getParentClass()->getName();
1741: }
1742: }
1743: }
1744:
1745: return $originalClass;
1746: }
1747:
1748: private function resolveTypeByName(Name $name, ?ClassReflection $classReflection): TypeWithClassName
1749: {
1750: if ($name->toLowerString() === 'static' && $classReflection !== null) {
1751: return new StaticType($classReflection);
1752: }
1753:
1754: $originalClass = $this->resolveName($name, $classReflection);
1755: if ($classReflection !== null) {
1756: $thisType = new ThisType($classReflection);
1757: $ancestor = $thisType->getAncestorWithClassName($originalClass);
1758: if ($ancestor !== null) {
1759: return $ancestor;
1760: }
1761: }
1762:
1763: return new ObjectType($originalClass);
1764: }
1765:
1766: private function resolveTypeByNameWithLateStaticBinding(Name $class, Type $classType, MethodReflection $methodReflectionCandidate): Type
1767: {
1768: if (
1769: $classType instanceof StaticType
1770: && !in_array($class->toLowerString(), ['self', 'static', 'parent'], true)
1771: ) {
1772: if ($methodReflectionCandidate->isStatic()) {
1773: $classType = $classType->getStaticObjectType();
1774: }
1775: }
1776:
1777: return $classType;
1778: }
1779:
1780: private function getReflectionProvider(): ReflectionProvider
1781: {
1782: return $this->reflectionProviderProvider->getReflectionProvider();
1783: }
1784:
1785: private function getNeverType(Type $leftType, Type $rightType): Type
1786: {
1787: // make sure we don't lose the explicit flag in the process
1788: if ($leftType instanceof NeverType && $leftType->isExplicit()) {
1789: return $leftType;
1790: }
1791: if ($rightType instanceof NeverType && $rightType->isExplicit()) {
1792: return $rightType;
1793: }
1794: return new NeverType();
1795: }
1796:
1797: }
1798: