1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\PhpDoc;
4:
5: use Closure;
6: use Generator;
7: use Iterator;
8: use IteratorAggregate;
9: use Nette\Utils\Strings;
10: use PhpParser\Node\Name;
11: use PHPStan\Analyser\ConstantResolver;
12: use PHPStan\Analyser\NameScope;
13: use PHPStan\Analyser\ValueDependencyCollector;
14: use PHPStan\DependencyInjection\AutowiredParameter;
15: use PHPStan\DependencyInjection\AutowiredService;
16: use PHPStan\DependencyInjection\ReportUnsafeArrayStringKeyCastingToggle;
17: use PHPStan\PhpDoc\Tag\TemplateTag;
18: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprArrayNode;
19: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode;
20: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode;
21: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
22: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode;
23: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
24: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode;
25: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
26: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
27: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
28: use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
29: use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
30: use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
31: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
32: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
33: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
34: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
35: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
36: use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
37: use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode;
38: use PHPStan\PhpDocParser\Ast\Type\NameNode;
39: use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
40: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
41: use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
42: use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
43: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
44: use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
45: use PHPStan\Reflection\Assertions;
46: use PHPStan\Reflection\Callables\SimpleImpurePoint;
47: use PHPStan\Reflection\InitializerExprContext;
48: use PHPStan\Reflection\InitializerExprTypeResolver;
49: use PHPStan\Reflection\Native\NativeParameterReflection;
50: use PHPStan\Reflection\PassedByReference;
51: use PHPStan\Reflection\ReflectionProvider;
52: use PHPStan\ShouldNotHappenException;
53: use PHPStan\TrinaryLogic;
54: use PHPStan\Type\Accessory\AccessoryArrayListType;
55: use PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType;
56: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
57: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
58: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
59: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
60: use PHPStan\Type\Accessory\AccessoryNumericStringType;
61: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
62: use PHPStan\Type\Accessory\NonEmptyArrayType;
63: use PHPStan\Type\ArrayType;
64: use PHPStan\Type\BenevolentUnionType;
65: use PHPStan\Type\BooleanType;
66: use PHPStan\Type\CallableAssertionsHelper;
67: use PHPStan\Type\CallableType;
68: use PHPStan\Type\ClassConstantAccessType;
69: use PHPStan\Type\ClassStringType;
70: use PHPStan\Type\ClosureType;
71: use PHPStan\Type\ConditionalType;
72: use PHPStan\Type\ConditionalTypeForParameter;
73: use PHPStan\Type\Constant\ConstantArrayType;
74: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
75: use PHPStan\Type\Constant\ConstantBooleanType;
76: use PHPStan\Type\Constant\ConstantFloatType;
77: use PHPStan\Type\Constant\ConstantIntegerType;
78: use PHPStan\Type\Constant\ConstantStringType;
79: use PHPStan\Type\Enum\EnumCaseObjectType;
80: use PHPStan\Type\ErrorType;
81: use PHPStan\Type\FloatRangeType;
82: use PHPStan\Type\FloatType;
83: use PHPStan\Type\Generic\GenericClassStringType;
84: use PHPStan\Type\Generic\GenericObjectType;
85: use PHPStan\Type\Generic\GenericStaticType;
86: use PHPStan\Type\Generic\TemplateType;
87: use PHPStan\Type\Generic\TemplateTypeFactory;
88: use PHPStan\Type\Generic\TemplateTypeMap;
89: use PHPStan\Type\Generic\TemplateTypeScope;
90: use PHPStan\Type\Generic\TemplateTypeVariance;
91: use PHPStan\Type\Helper\GetTemplateTypeType;
92: use PHPStan\Type\IntegerRangeType;
93: use PHPStan\Type\IntegerType;
94: use PHPStan\Type\IntersectionType;
95: use PHPStan\Type\IterableType;
96: use PHPStan\Type\KeyOfType;
97: use PHPStan\Type\LateResolvableArrayShapeType;
98: use PHPStan\Type\LateResolvableObjectShapeType;
99: use PHPStan\Type\MixedType;
100: use PHPStan\Type\NewObjectType;
101: use PHPStan\Type\NonAcceptingNeverType;
102: use PHPStan\Type\NonexistentParentClassType;
103: use PHPStan\Type\NullType;
104: use PHPStan\Type\ObjectType;
105: use PHPStan\Type\ObjectWithoutClassType;
106: use PHPStan\Type\OffsetAccessType;
107: use PHPStan\Type\ResourceType;
108: use PHPStan\Type\StaticType;
109: use PHPStan\Type\StaticTypeFactory;
110: use PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType;
111: use PHPStan\Type\StringNeverAcceptingObjectWithToStringType;
112: use PHPStan\Type\StringType;
113: use PHPStan\Type\ThisType;
114: use PHPStan\Type\Type;
115: use PHPStan\Type\TypeAliasResolver;
116: use PHPStan\Type\TypeAliasResolverProvider;
117: use PHPStan\Type\TypeCombinator;
118: use PHPStan\Type\TypeTraverser;
119: use PHPStan\Type\TypeUtils;
120: use PHPStan\Type\UnionType;
121: use PHPStan\Type\ValueOfType;
122: use PHPStan\Type\VoidType;
123: use Traversable;
124: use function array_key_exists;
125: use function array_map;
126: use function array_values;
127: use function count;
128: use function explode;
129: use function get_class;
130: use function in_array;
131: use function is_nan;
132: use function max;
133: use function min;
134: use function preg_match;
135: use function preg_quote;
136: use function str_contains;
137: use function str_replace;
138: use function str_starts_with;
139: use function strtolower;
140: use function substr;
141: use const INF;
142: use const PHP_FLOAT_MAX;
143:
144: /**
145: * @phpstan-import-type Level from ReportUnsafeArrayStringKeyCastingToggle as ReportUnsafeArrayStringKeyCastingLevel
146: */
147: #[AutowiredService]
148: final class TypeNodeResolver
149: {
150:
151: /** @var array<string, true> */
152: private array $genericTypeResolvingStack = [];
153:
154: /**
155: * @param ReportUnsafeArrayStringKeyCastingLevel $reportUnsafeArrayStringKeyCasting
156: */
157: public function __construct(
158: private TypeNodeResolverExtensionRegistryProvider $extensionRegistryProvider,
159: private ReflectionProvider\ReflectionProviderProvider $reflectionProviderProvider,
160: private TypeAliasResolverProvider $typeAliasResolverProvider,
161: private ConstantResolver $constantResolver,
162: private InitializerExprTypeResolver $initializerExprTypeResolver,
163: #[AutowiredParameter]
164: private ?string $reportUnsafeArrayStringKeyCasting,
165: private ValueDependencyCollector $valueDependencyCollector,
166: )
167: {
168: }
169:
170: /** @api */
171: public function resolve(TypeNode $typeNode, NameScope $nameScope): Type
172: {
173: // The resolved type is remembered with the reflection of what the PHPDoc describes, so a name
174: // in it that is not a class yet is what it declares depends on.
175: $this->valueDependencyCollector->enterDeclaration($nameScope->getFileName(), $nameScope->getClassName(), $nameScope->getFunctionName());
176: try {
177: return $this->resolveType($typeNode, $nameScope);
178: } finally {
179: $this->valueDependencyCollector->leaveDeclaration();
180: }
181: }
182:
183: /** The nested nodes of a type are resolved in the declaration resolve() entered, with a name scope of the same declaration. */
184: private function resolveType(TypeNode $typeNode, NameScope $nameScope): Type
185: {
186: foreach ($this->extensionRegistryProvider->getRegistry()->getExtensions() as $extension) {
187: $type = $extension->resolve($typeNode, $nameScope);
188: if ($type !== null) {
189: return $type;
190: }
191: }
192:
193: if ($typeNode instanceof NameNode) {
194: return $this->resolveNameNode($typeNode, $nameScope);
195:
196: } elseif ($typeNode instanceof IdentifierTypeNode) {
197: return $this->resolveIdentifierTypeNode($typeNode, $nameScope);
198:
199: } elseif ($typeNode instanceof ThisTypeNode) {
200: return $this->resolveThisTypeNode($nameScope);
201:
202: } elseif ($typeNode instanceof NullableTypeNode) {
203: return $this->resolveNullableTypeNode($typeNode, $nameScope);
204:
205: } elseif ($typeNode instanceof UnionTypeNode) {
206: return $this->resolveUnionTypeNode($typeNode, $nameScope);
207:
208: } elseif ($typeNode instanceof IntersectionTypeNode) {
209: return $this->resolveIntersectionTypeNode($typeNode, $nameScope);
210:
211: } elseif ($typeNode instanceof ConditionalTypeNode) {
212: return $this->resolveConditionalTypeNode($typeNode, $nameScope);
213:
214: } elseif ($typeNode instanceof ConditionalTypeForParameterNode) {
215: return $this->resolveConditionalTypeForParameterNode($typeNode, $nameScope);
216:
217: } elseif ($typeNode instanceof ArrayTypeNode) {
218: return $this->resolveArrayTypeNode($typeNode, $nameScope);
219:
220: } elseif ($typeNode instanceof GenericTypeNode) {
221: return $this->resolveGenericTypeNode($typeNode, $nameScope);
222:
223: } elseif ($typeNode instanceof CallableTypeNode) {
224: return $this->resolveCallableTypeNode($typeNode, $nameScope);
225:
226: } elseif ($typeNode instanceof ArrayShapeNode) {
227: return $this->resolveArrayShapeNode($typeNode, $nameScope);
228: } elseif ($typeNode instanceof ObjectShapeNode) {
229: return $this->resolveObjectShapeNode($typeNode, $nameScope);
230: } elseif ($typeNode instanceof ConstTypeNode) {
231: return $this->resolveConstTypeNode($typeNode, $nameScope);
232: } elseif ($typeNode instanceof OffsetAccessTypeNode) {
233: return $this->resolveOffsetAccessNode($typeNode, $nameScope);
234: } elseif ($typeNode instanceof InvalidTypeNode) {
235: return new MixedType(true);
236: }
237:
238: return new ErrorType();
239: }
240:
241: /**
242: * A name node is always a class, even when it is named like a keyword or a template type.
243: */
244: private function resolveNameNode(NameNode $typeNode, NameScope $nameScope): Type
245: {
246: return new ObjectType($nameScope->resolveStringName($typeNode->toCodeString()));
247: }
248:
249: private function resolveIdentifierTypeNode(IdentifierTypeNode $typeNode, NameScope $nameScope): Type
250: {
251: switch (strtolower($typeNode->name)) {
252: case 'int':
253: return new IntegerType();
254:
255: case 'integer':
256: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
257:
258: if ($type !== null) {
259: return $type;
260: }
261:
262: return new IntegerType();
263:
264: case 'positive-int':
265: return IntegerRangeType::fromInterval(1, null);
266:
267: case 'negative-int':
268: return IntegerRangeType::fromInterval(null, -1);
269:
270: case 'non-positive-int':
271: return IntegerRangeType::fromInterval(null, 0);
272:
273: case 'non-negative-int':
274: return IntegerRangeType::fromInterval(0, null);
275:
276: case 'positive-float':
277: return FloatRangeType::fromInterval(5.0E-324, INF);
278:
279: case 'negative-float':
280: return FloatRangeType::fromInterval(-INF, -5.0E-324);
281:
282: case 'non-positive-float':
283: return FloatRangeType::fromInterval(-INF, 0.0);
284:
285: case 'non-negative-float':
286: return FloatRangeType::fromInterval(0.0, INF);
287:
288: case 'finite-float':
289: return FloatRangeType::fromInterval(-PHP_FLOAT_MAX, PHP_FLOAT_MAX);
290:
291: case 'non-zero-int':
292: return new UnionType([
293: IntegerRangeType::fromInterval(null, -1),
294: IntegerRangeType::fromInterval(1, null),
295: ]);
296:
297: case 'string':
298: return new StringType();
299:
300: case 'decimal-int-string':
301: return new IntersectionType([new StringType(), new AccessoryDecimalIntegerStringType()]);
302:
303: case 'non-decimal-int-string':
304: return new IntersectionType([
305: new StringType(),
306: new AccessoryDecimalIntegerStringType(inverse: true),
307: ]);
308:
309: case 'lowercase-string':
310: return new IntersectionType([new StringType(), new AccessoryLowercaseStringType()]);
311:
312: case 'uppercase-string':
313: return new IntersectionType([new StringType(), new AccessoryUppercaseStringType()]);
314:
315: case 'literal-string':
316: return new IntersectionType([new StringType(), new AccessoryLiteralStringType()]);
317:
318: case 'class-string':
319: case 'interface-string':
320: case 'trait-string':
321: return new ClassStringType();
322:
323: case 'enum-string':
324: return new GenericClassStringType(new ObjectType('UnitEnum'));
325:
326: case 'callable-string':
327: return new IntersectionType([new StringType(), new CallableType()]);
328:
329: case 'array-key':
330: return new BenevolentUnionType([new IntegerType(), new StringType()]);
331:
332: case 'scalar':
333: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
334:
335: if ($type !== null) {
336: return $type;
337: }
338:
339: return new UnionType([new IntegerType(), new FloatType(), new StringType(), new BooleanType()]);
340:
341: case 'empty-scalar':
342: return TypeCombinator::intersect(
343: new UnionType([new IntegerType(), new FloatType(), new StringType(), new BooleanType()]),
344: StaticTypeFactory::falsey(),
345: );
346:
347: case 'non-empty-scalar':
348: return TypeCombinator::remove(
349: new UnionType([new IntegerType(), new FloatType(), new StringType(), new BooleanType()]),
350: StaticTypeFactory::falsey(),
351: );
352:
353: case 'number':
354: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
355:
356: if ($type !== null) {
357: return $type;
358: }
359:
360: return new UnionType([new IntegerType(), new FloatType()]);
361:
362: case 'numeric':
363: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
364:
365: if ($type !== null) {
366: return $type;
367: }
368:
369: return new UnionType([
370: new IntegerType(),
371: new FloatType(),
372: new IntersectionType([
373: new StringType(),
374: new AccessoryNumericStringType(),
375: ]),
376: ]);
377:
378: case 'numeric-string':
379: return new IntersectionType([
380: new StringType(),
381: new AccessoryNumericStringType(),
382: ]);
383:
384: case 'non-empty-string':
385: return new IntersectionType([
386: new StringType(),
387: new AccessoryNonEmptyStringType(),
388: ]);
389:
390: case 'non-empty-lowercase-string':
391: return new IntersectionType([
392: new StringType(),
393: new AccessoryNonEmptyStringType(),
394: new AccessoryLowercaseStringType(),
395: ]);
396:
397: case 'non-empty-uppercase-string':
398: return new IntersectionType([
399: new StringType(),
400: new AccessoryNonEmptyStringType(),
401: new AccessoryUppercaseStringType(),
402: ]);
403:
404: case 'truthy-string':
405: case 'non-falsy-string':
406: return new IntersectionType([
407: new StringType(),
408: new AccessoryNonFalsyStringType(),
409: ]);
410:
411: case 'non-empty-literal-string':
412: return new IntersectionType([
413: new StringType(),
414: new AccessoryNonEmptyStringType(),
415: new AccessoryLiteralStringType(),
416: ]);
417:
418: case 'bool':
419: return new BooleanType();
420:
421: case 'boolean':
422: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
423:
424: if ($type !== null) {
425: return $type;
426: }
427:
428: return new BooleanType();
429:
430: case 'true':
431: return new ConstantBooleanType(true);
432:
433: case 'false':
434: return new ConstantBooleanType(false);
435:
436: case 'null':
437: return new NullType();
438:
439: case 'float':
440: return new FloatType();
441:
442: case 'double':
443: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
444:
445: if ($type !== null) {
446: return $type;
447: }
448:
449: return new FloatType();
450:
451: case 'array':
452: case 'associative-array':
453: return new ArrayType(new MixedType(), new MixedType());
454:
455: case 'non-empty-array':
456: return new IntersectionType([
457: new ArrayType(new MixedType(), new MixedType()),
458: new NonEmptyArrayType(),
459: ]);
460:
461: case 'iterable':
462: return new IterableType(new MixedType(), new MixedType());
463:
464: case 'callable':
465: return new CallableType();
466:
467: case 'pure-callable':
468: return new CallableType(isPure: TrinaryLogic::createYes());
469:
470: case 'pure-closure':
471: return ClosureType::createPure();
472:
473: case 'static-closure':
474: return new ClosureType(isStatic: TrinaryLogic::createYes());
475:
476: case 'static-pure-closure':
477: return new ClosureType(impurePoints: [], isStatic: TrinaryLogic::createYes());
478:
479: case 'resource':
480: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
481:
482: if ($type !== null) {
483: return $type;
484: }
485:
486: return new ResourceType();
487:
488: case 'open-resource':
489: case 'closed-resource':
490: return new ResourceType();
491:
492: case 'mixed':
493: return new MixedType(true);
494:
495: case 'non-empty-mixed':
496: return new MixedType(true, StaticTypeFactory::falsey());
497:
498: case 'void':
499: return new VoidType();
500:
501: case 'object':
502: return new ObjectWithoutClassType();
503:
504: case 'callable-object':
505: return new IntersectionType([new ObjectWithoutClassType(), new CallableType()]);
506:
507: case 'callable-array':
508: return new IntersectionType([new ArrayType(new MixedType(), new MixedType()), new CallableType()]);
509:
510: case 'never':
511: case 'noreturn':
512: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
513:
514: if ($type !== null) {
515: return $type;
516: }
517:
518: return new NonAcceptingNeverType();
519:
520: case 'never-return':
521: case 'never-returns':
522: case 'no-return':
523: return new NonAcceptingNeverType();
524:
525: case 'list':
526: return new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), new MixedType()), new AccessoryArrayListType()]);
527: case 'non-empty-list':
528: return new IntersectionType([
529: new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), new MixedType()),
530: new NonEmptyArrayType(),
531: new AccessoryArrayListType(),
532: ]);
533:
534: case 'empty':
535: $type = $this->tryResolvePseudoTypeClassType($typeNode, $nameScope);
536: if ($type !== null) {
537: return $type;
538: }
539:
540: return StaticTypeFactory::falsey();
541: case '__stringandstringable':
542: return new StringAlwaysAcceptingObjectWithToStringType();
543: case '__stringnotstringable':
544: return new StringNeverAcceptingObjectWithToStringType();
545: }
546:
547: if ($nameScope->getClassName() !== null) {
548: switch (strtolower($typeNode->name)) {
549: case 'self':
550: return new ObjectType($nameScope->getClassName());
551:
552: case 'static':
553: if ($this->getReflectionProvider()->hasClass($nameScope->getClassName())) {
554: $classReflection = $this->getReflectionProvider()->getClass($nameScope->getClassName());
555:
556: return new StaticType($classReflection);
557: }
558:
559: return new ErrorType();
560: case 'parent':
561: if ($this->getReflectionProvider()->hasClass($nameScope->getClassName())) {
562: $classReflection = $this->getReflectionProvider()->getClass($nameScope->getClassName());
563: $parentClass = $classReflection->getNativeReflection()->getParentClass();
564: if ($parentClass !== false) {
565: return new ObjectType($parentClass->getName());
566: }
567: }
568:
569: return new NonexistentParentClassType();
570: }
571: }
572:
573: if (!$nameScope->shouldBypassTypeAliases()) {
574: $typeAlias = $this->getTypeAliasResolver()->resolveTypeAlias($typeNode->name, $nameScope);
575: if ($typeAlias !== null) {
576: return $typeAlias;
577: }
578: }
579:
580: $templateType = $nameScope->resolveTemplateTypeName($typeNode->name);
581: if ($templateType !== null) {
582: return $templateType;
583: }
584:
585: $stringName = $nameScope->resolveStringName($typeNode->name);
586: if (str_contains($stringName, '-') && !str_starts_with($stringName, 'OCI-')) {
587: return new ErrorType();
588: }
589:
590: if ($this->mightBeConstant($typeNode->name) && !$this->getReflectionProvider()->hasClass($stringName)) {
591: $constType = $this->tryResolveConstant($typeNode->name, $nameScope);
592: if ($constType !== null) {
593: return $constType;
594: }
595: }
596:
597: return new ObjectType($stringName);
598: }
599:
600: private function mightBeConstant(string $name): bool
601: {
602: return preg_match('((?:^|\\\\)[A-Z_][A-Z0-9_]*$)', $name) > 0;
603: }
604:
605: private function tryResolveConstant(string $name, NameScope $nameScope): ?Type
606: {
607: foreach ($nameScope->resolveConstantNames($name) as $constName) {
608: $nameNode = new Name\FullyQualified(explode('\\', $constName));
609: $constType = $this->constantResolver->resolveConstant($nameNode, null);
610: if ($constType !== null) {
611: return $constType;
612: }
613: }
614:
615: return null;
616: }
617:
618: private function tryResolvePseudoTypeClassType(IdentifierTypeNode $typeNode, NameScope $nameScope): ?Type
619: {
620: if ($nameScope->hasUseAlias($typeNode->name)) {
621: return new ObjectType($nameScope->resolveStringName($typeNode->name));
622: }
623:
624: if ($nameScope->getNamespace() === null) {
625: return null;
626: }
627:
628: $className = $nameScope->resolveStringName($typeNode->name);
629:
630: if ($this->getReflectionProvider()->hasClass($className)) {
631: return new ObjectType($className);
632: }
633:
634: return null;
635: }
636:
637: private function resolveThisTypeNode(NameScope $nameScope): Type
638: {
639: $className = $nameScope->getClassName();
640: if ($className !== null) {
641: if ($this->getReflectionProvider()->hasClass($className)) {
642: return new ThisType($this->getReflectionProvider()->getClass($className));
643: }
644: }
645:
646: return new ErrorType();
647: }
648:
649: private function resolveNullableTypeNode(NullableTypeNode $typeNode, NameScope $nameScope): Type
650: {
651: return TypeCombinator::union($this->resolveType($typeNode->type, $nameScope), new NullType());
652: }
653:
654: private function resolveUnionTypeNode(UnionTypeNode $typeNode, NameScope $nameScope): Type
655: {
656: $iterableTypeNodes = [];
657: $otherTypeNodes = [];
658:
659: foreach ($typeNode->types as $innerTypeNode) {
660: if ($innerTypeNode instanceof ArrayTypeNode) {
661: $iterableTypeNodes[] = $innerTypeNode->type;
662: } else {
663: $otherTypeNodes[] = $innerTypeNode;
664: }
665: }
666:
667: $otherTypeTypes = $this->resolveMultiple($otherTypeNodes, $nameScope);
668: if (count($iterableTypeNodes) > 0) {
669: $arrayTypeTypes = $this->resolveMultiple($iterableTypeNodes, $nameScope);
670: $arrayTypeType = TypeCombinator::union(...$arrayTypeTypes);
671: $addArray = true;
672:
673: foreach ($otherTypeTypes as &$type) {
674: if (!$type->isIterable()->yes() || !$type->getIterableValueType()->isSuperTypeOf($arrayTypeType)->yes()) {
675: continue;
676: }
677:
678: if ($type instanceof ObjectType && !$type instanceof GenericObjectType) {
679: $type = new IntersectionType([$type, new IterableType(new MixedType(), $arrayTypeType)]);
680: } elseif ($type instanceof ArrayType) {
681: $type = new ArrayType(new MixedType(), $arrayTypeType);
682: } elseif ($type instanceof ConstantArrayType) {
683: $type = new ArrayType(new MixedType(), $arrayTypeType);
684: } elseif ($type instanceof IterableType) {
685: $type = new IterableType(new MixedType(), $arrayTypeType);
686: } else {
687: continue;
688: }
689:
690: $addArray = false;
691: }
692:
693: if ($addArray) {
694: $otherTypeTypes[] = new ArrayType(new MixedType(), $arrayTypeType);
695: }
696: }
697:
698: return TypeCombinator::union(...$otherTypeTypes);
699: }
700:
701: private function resolveIntersectionTypeNode(IntersectionTypeNode $typeNode, NameScope $nameScope): Type
702: {
703: $types = $this->resolveMultiple($typeNode->types, $nameScope);
704: $result = $types[0];
705: for ($i = 1, $count = count($types); $i < $count; $i++) {
706: $result = TypeCombinator::intersect($result, $types[$i]);
707: }
708: return $result;
709: }
710:
711: private function resolveConditionalTypeNode(ConditionalTypeNode $typeNode, NameScope $nameScope): Type
712: {
713: return new ConditionalType(
714: $this->resolveType($typeNode->subjectType, $nameScope),
715: $this->resolveType($typeNode->targetType, $nameScope),
716: $this->resolveType($typeNode->if, $nameScope),
717: $this->resolveType($typeNode->else, $nameScope),
718: $typeNode->negated,
719: );
720: }
721:
722: private function resolveConditionalTypeForParameterNode(ConditionalTypeForParameterNode $typeNode, NameScope $nameScope): Type
723: {
724: return new ConditionalTypeForParameter(
725: $typeNode->parameterName,
726: $this->resolveType($typeNode->targetType, $nameScope),
727: $this->resolveType($typeNode->if, $nameScope),
728: $this->resolveType($typeNode->else, $nameScope),
729: $typeNode->negated,
730: );
731: }
732:
733: private function resolveArrayTypeNode(ArrayTypeNode $typeNode, NameScope $nameScope): Type
734: {
735: $itemType = $this->resolveType($typeNode->type, $nameScope);
736: return new ArrayType((new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey(), $itemType);
737: }
738:
739: private function resolveGenericTypeNode(GenericTypeNode $typeNode, NameScope $nameScope): Type
740: {
741: $mainTypeName = $typeNode->type instanceof NameNode ? null : strtolower($typeNode->type->name);
742: $genericTypes = $this->resolveMultiple($typeNode->genericTypes, $nameScope);
743: $variances = array_map(
744: static function (string $variance): TemplateTypeVariance {
745: switch ($variance) {
746: case GenericTypeNode::VARIANCE_INVARIANT:
747: return TemplateTypeVariance::createInvariant();
748: case GenericTypeNode::VARIANCE_COVARIANT:
749: return TemplateTypeVariance::createCovariant();
750: case GenericTypeNode::VARIANCE_CONTRAVARIANT:
751: return TemplateTypeVariance::createContravariant();
752: case GenericTypeNode::VARIANCE_BIVARIANT:
753: return TemplateTypeVariance::createBivariant();
754: }
755: },
756: $typeNode->variances,
757: );
758:
759: if (in_array($mainTypeName, ['array', 'non-empty-array'], true)) {
760: if (count($genericTypes) === 1) { // array<ValueType>
761: $arrayType = new ArrayType((new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey(), $genericTypes[0]);
762: } elseif (count($genericTypes) === 2) { // array<KeyType, ValueType>
763: $keyType = $this->transformUnsafeArrayKey($genericTypes[0]);
764: $finiteTypes = $keyType->getFiniteTypes();
765: if (
766: count($finiteTypes) === 1
767: && ($finiteTypes[0] instanceof ConstantStringType || $finiteTypes[0] instanceof ConstantIntegerType)
768: ) {
769: $arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
770: $arrayBuilder->setOffsetValueType($finiteTypes[0], $genericTypes[1], true);
771: $arrayType = $arrayBuilder->getArray();
772: } else {
773: $arrayType = new ArrayType($keyType, $genericTypes[1]);
774: }
775: } else {
776: return new ErrorType();
777: }
778:
779: if ($mainTypeName === 'non-empty-array') {
780: return TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
781: }
782:
783: return $arrayType;
784: } elseif (in_array($mainTypeName, ['list', 'non-empty-list'], true)) {
785: if (count($genericTypes) === 1) { // list<ValueType>
786: $listType = new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $genericTypes[0]), new AccessoryArrayListType()]);
787: if ($mainTypeName === 'non-empty-list') {
788: return TypeCombinator::intersect($listType, new NonEmptyArrayType());
789: }
790:
791: return $listType;
792: }
793:
794: return new ErrorType();
795: } elseif ($mainTypeName === 'iterable') {
796: if (count($genericTypes) === 1) { // iterable<ValueType>
797: return new IterableType(new MixedType(true), $genericTypes[0]);
798:
799: }
800:
801: if (count($genericTypes) === 2) { // iterable<KeyType, ValueType>
802: return new IterableType($genericTypes[0], $genericTypes[1]);
803: }
804: } elseif (in_array($mainTypeName, ['class-string', 'interface-string'], true)) {
805: if (count($genericTypes) === 1) {
806: $genericType = $genericTypes[0];
807: if ($genericType->isObject()->yes() || $genericType instanceof MixedType) {
808: return new GenericClassStringType($genericType);
809: }
810: }
811:
812: return new ErrorType();
813: } elseif ($mainTypeName === 'enum-string') {
814: if (count($genericTypes) === 1) {
815: $genericType = $genericTypes[0];
816: return new GenericClassStringType(TypeCombinator::intersect($genericType, new ObjectType('UnitEnum')));
817: }
818:
819: return new ErrorType();
820: } elseif ($mainTypeName === 'int') {
821: if (count($genericTypes) === 2) { // int<min, max>, int<1, 3>
822:
823: if ($genericTypes[0] instanceof ConstantIntegerType) {
824: $min = $genericTypes[0]->getValue();
825: } elseif ($typeNode->genericTypes[0] instanceof IdentifierTypeNode && $typeNode->genericTypes[0]->name === 'min') {
826: $min = null;
827: } else {
828: return new ErrorType();
829: }
830:
831: if ($genericTypes[1] instanceof ConstantIntegerType) {
832: $max = $genericTypes[1]->getValue();
833: } elseif ($typeNode->genericTypes[1] instanceof IdentifierTypeNode && $typeNode->genericTypes[1]->name === 'max') {
834: $max = null;
835: } else {
836: return new ErrorType();
837: }
838:
839: return IntegerRangeType::fromInterval($min, $max);
840: }
841: } elseif ($mainTypeName === 'float') {
842: if (count($genericTypes) === 2) { // float<min, max>, float<0, 1.5>
843: $min = $this->resolveFloatRangeBound($genericTypes[0], $typeNode->genericTypes[0], 'min', -INF);
844: $max = $this->resolveFloatRangeBound($genericTypes[1], $typeNode->genericTypes[1], 'max', INF);
845: if ($min === null || $max === null) {
846: return new ErrorType();
847: }
848:
849: return FloatRangeType::fromInterval($min, $max);
850: }
851: } elseif ($mainTypeName === 'key-of') {
852: if (count($genericTypes) === 1) { // key-of<ValueType>
853: $type = new KeyOfType($genericTypes[0]);
854: return $type->isResolvable() ? $type->resolve() : $type;
855: }
856:
857: return new ErrorType();
858: } elseif ($mainTypeName === 'value-of') {
859: if (count($genericTypes) === 1) { // value-of<ValueType>
860: $type = new ValueOfType($genericTypes[0]);
861:
862: return $type->isResolvable() ? $type->resolve() : $type;
863: }
864:
865: return new ErrorType();
866: } elseif ($mainTypeName === 'int-mask-of') {
867: if (count($genericTypes) === 1) { // int-mask-of<Class::CONST*>
868: $maskType = $this->expandIntMaskToType($genericTypes[0]);
869: if ($maskType !== null) {
870: return $maskType;
871: }
872: }
873:
874: return new ErrorType();
875: } elseif ($mainTypeName === 'int-mask') {
876: if (count($genericTypes) > 0) { // int-mask<1, 2, 4>
877: $maskType = $this->expandIntMaskToType(TypeCombinator::union(...$genericTypes));
878: if ($maskType !== null) {
879: return $maskType;
880: }
881: }
882:
883: return new ErrorType();
884: } elseif ($mainTypeName === '__benevolent') {
885: if (count($genericTypes) === 1) {
886: return TypeUtils::toBenevolentUnion($genericTypes[0]);
887: }
888: return new ErrorType();
889: } elseif ($mainTypeName === 'template-type') {
890: if (count($genericTypes) === 3) {
891: $result = [];
892: /** @var class-string $ancestorClassName */
893: foreach ($genericTypes[1]->getObjectClassNames() as $ancestorClassName) {
894: foreach ($genericTypes[2]->getConstantStrings() as $templateTypeName) {
895: $result[] = new GetTemplateTypeType($genericTypes[0], $ancestorClassName, $templateTypeName->getValue());
896: }
897: }
898:
899: return TypeCombinator::union(...$result);
900: }
901:
902: return new ErrorType();
903: } elseif ($mainTypeName === 'new') {
904: if (count($genericTypes) === 1) {
905: $type = new NewObjectType($genericTypes[0]);
906: return $type->isResolvable() ? $type->resolve() : $type;
907: }
908:
909: return new ErrorType();
910: } elseif ($mainTypeName === 'static') {
911: if ($nameScope->getClassName() !== null && $this->getReflectionProvider()->hasClass($nameScope->getClassName())) {
912: $classReflection = $this->getReflectionProvider()->getClass($nameScope->getClassName());
913:
914: return new GenericStaticType($classReflection, $genericTypes, null, $variances);
915: }
916:
917: return new ErrorType();
918: }
919:
920: $mainType = $typeNode->type instanceof NameNode
921: ? $this->resolveNameNode($typeNode->type, $nameScope)
922: : $this->resolveIdentifierTypeNode($typeNode->type, $nameScope);
923: $mainTypeObjectClassNames = $mainType->getObjectClassNames();
924: if (count($mainTypeObjectClassNames) > 1) {
925: if ($mainType instanceof TemplateType) {
926: return new ErrorType();
927: }
928: throw new ShouldNotHappenException();
929: }
930: $mainTypeClassName = $mainTypeObjectClassNames[0] ?? null;
931:
932: if ($mainTypeClassName !== null) {
933: if (!$this->getReflectionProvider()->hasClass($mainTypeClassName)) {
934: return new GenericObjectType($mainTypeClassName, $genericTypes, variances: $variances);
935: }
936:
937: $classReflection = $this->getReflectionProvider()->getClass($mainTypeClassName);
938: if ($classReflection->isGeneric()) {
939: $templateTypes = array_values($classReflection->getTemplateTypeMap()->getTypes());
940: for ($i = count($genericTypes), $templateTypesCount = count($templateTypes); $i < $templateTypesCount; $i++) {
941: $templateType = $templateTypes[$i];
942: if (!$templateType instanceof TemplateType || $templateType->getDefault() === null) {
943: continue;
944: }
945: $genericTypes[] = $templateType->getDefault();
946: }
947:
948: if (in_array($mainTypeClassName, [
949: Traversable::class,
950: IteratorAggregate::class,
951: Iterator::class,
952: ], true)) {
953: if (count($genericTypes) === 1) {
954: return new GenericObjectType($mainTypeClassName, [
955: new MixedType(true),
956: $genericTypes[0],
957: ], variances: [
958: TemplateTypeVariance::createInvariant(),
959: $variances[0],
960: ]);
961: }
962:
963: if (count($genericTypes) === 2) {
964: return new GenericObjectType($mainTypeClassName, [
965: $genericTypes[0],
966: $genericTypes[1],
967: ], variances: [
968: $variances[0],
969: $variances[1],
970: ]);
971: }
972: }
973: if ($mainTypeClassName === Generator::class) {
974: if (count($genericTypes) === 1) {
975: $mixed = new MixedType(true);
976: return new GenericObjectType($mainTypeClassName, [
977: $mixed,
978: $genericTypes[0],
979: $mixed,
980: $mixed,
981: ], variances: [
982: TemplateTypeVariance::createInvariant(),
983: $variances[0],
984: TemplateTypeVariance::createInvariant(),
985: TemplateTypeVariance::createInvariant(),
986: ]);
987: }
988:
989: if (count($genericTypes) === 2) {
990: $mixed = new MixedType(true);
991: return new GenericObjectType($mainTypeClassName, [
992: $genericTypes[0],
993: $genericTypes[1],
994: $mixed,
995: $mixed,
996: ], variances: [
997: $variances[0],
998: $variances[1],
999: TemplateTypeVariance::createInvariant(),
1000: TemplateTypeVariance::createInvariant(),
1001: ]);
1002: }
1003: }
1004:
1005: if (!$mainType->isIterable()->yes()) {
1006: return new GenericObjectType($mainTypeClassName, $genericTypes, variances: $variances);
1007: }
1008:
1009: if (
1010: count($genericTypes) !== 1
1011: || $classReflection->getTemplateTypeMap()->count() === 1
1012: ) {
1013: return new GenericObjectType($mainTypeClassName, $genericTypes, variances: $variances);
1014: }
1015: }
1016: }
1017:
1018: if ($mainType->isIterable()->yes()) {
1019: if ($mainTypeClassName !== null) {
1020: if (isset($this->genericTypeResolvingStack[$mainTypeClassName])) {
1021: return new ErrorType();
1022: }
1023:
1024: $this->genericTypeResolvingStack[$mainTypeClassName] = true;
1025: }
1026:
1027: try {
1028: if (count($genericTypes) === 1) { // Foo<ValueType>
1029: return TypeCombinator::intersect(
1030: $mainType,
1031: new IterableType(new MixedType(true), $genericTypes[0]),
1032: );
1033: }
1034:
1035: if (count($genericTypes) === 2) { // Foo<KeyType, ValueType>
1036: return TypeCombinator::intersect(
1037: $mainType,
1038: new IterableType($genericTypes[0], $genericTypes[1]),
1039: );
1040: }
1041: } finally {
1042: if ($mainTypeClassName !== null) {
1043: unset($this->genericTypeResolvingStack[$mainTypeClassName]);
1044: }
1045: }
1046: }
1047:
1048: if ($mainTypeClassName !== null) {
1049: return new GenericObjectType($mainTypeClassName, $genericTypes, variances: $variances);
1050: }
1051:
1052: return new ErrorType();
1053: }
1054:
1055: private function transformUnsafeArrayKey(Type $keyType): Type
1056: {
1057: if ($this->reportUnsafeArrayStringKeyCasting === ReportUnsafeArrayStringKeyCastingToggle::PREVENT) {
1058: if (!$keyType->isSuperTypeOf(new IntegerType())->yes()) {
1059: $keyType = TypeTraverser::map($keyType, static function (Type $type, callable $traverse) {
1060: if ($type instanceof UnionType || $type instanceof IntersectionType) {
1061: return $traverse($type);
1062: }
1063:
1064: if ($type instanceof StringType) {
1065: return TypeCombinator::intersect($type, new AccessoryDecimalIntegerStringType(inverse: true));
1066: }
1067:
1068: return $type;
1069: });
1070: }
1071: }
1072:
1073: return TypeCombinator::intersect($keyType->toArrayKey(), new UnionType([
1074: new IntegerType(),
1075: new StringType(),
1076: ]))->toArrayKey();
1077: }
1078:
1079: private function resolveCallableTypeNode(CallableTypeNode $typeNode, NameScope $nameScope): Type
1080: {
1081: $templateTags = [];
1082:
1083: if (count($typeNode->templateTypes) > 0) {
1084: foreach ($typeNode->templateTypes as $templateType) {
1085: $templateTags[$templateType->name] = new TemplateTag(
1086: $templateType->name,
1087: $templateType->bound !== null
1088: ? $this->resolveType($templateType->bound, $nameScope)
1089: : new MixedType(),
1090: $templateType->default !== null
1091: ? $this->resolveType($templateType->default, $nameScope)
1092: : null,
1093: TemplateTypeVariance::createInvariant(),
1094: );
1095: }
1096: $templateTypeScope = TemplateTypeScope::createWithAnonymousFunction();
1097:
1098: $templateTypeMap = new TemplateTypeMap(array_map(
1099: static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag),
1100: $templateTags,
1101: ));
1102:
1103: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap, $templateTags);
1104: } else {
1105: $templateTypeMap = TemplateTypeMap::createEmpty();
1106: }
1107:
1108: $mainType = $this->resolveType($typeNode->identifier, $nameScope);
1109:
1110: $isVariadic = false;
1111: $parameters = array_values(array_map(
1112: function (CallableTypeParameterNode $parameterNode) use ($nameScope, &$isVariadic): NativeParameterReflection {
1113: $isVariadic = $isVariadic || $parameterNode->isVariadic;
1114: $parameterName = $parameterNode->parameterName;
1115: if (str_starts_with($parameterName, '$')) {
1116: $parameterName = substr($parameterName, 1);
1117: }
1118:
1119: return new NativeParameterReflection(
1120: $parameterName,
1121: $parameterNode->isOptional || $parameterNode->isVariadic,
1122: $this->resolveType($parameterNode->type, $nameScope),
1123: $parameterNode->isReference ? PassedByReference::createCreatesNewVariable() : PassedByReference::createNo(),
1124: $parameterNode->isVariadic,
1125: defaultValue: null,
1126: );
1127: },
1128: $typeNode->parameters,
1129: ));
1130:
1131: $assertions = $this->resolveCallableReturnTypeAssertions($typeNode, $nameScope, $parameters);
1132: if ($assertions !== null) {
1133: $returnType = new BooleanType();
1134: } else {
1135: $returnType = $this->resolveType($typeNode->returnType, $nameScope);
1136: }
1137:
1138: if ($mainType instanceof CallableType) {
1139: $pure = $mainType->isPure();
1140: if ($pure->yes() && $returnType->isVoid()->yes()) {
1141: return new ErrorType();
1142: }
1143:
1144: return new CallableType($parameters, $returnType, $isVariadic, $templateTypeMap, templateTags: $templateTags, isPure: $pure, assertions: $assertions);
1145:
1146: } elseif (
1147: $mainType instanceof ObjectType
1148: && $mainType->getClassName() === Closure::class
1149: ) {
1150: return new ClosureType($parameters, $returnType, $isVariadic, $templateTypeMap, templateTags: $templateTags, impurePoints: [
1151: new SimpleImpurePoint(
1152: 'functionCall',
1153: 'call to a Closure',
1154: false,
1155: ),
1156: ], assertions: $assertions);
1157: } elseif ($mainType instanceof ClosureType) {
1158: $closure = new ClosureType($parameters, $returnType, $isVariadic, $templateTypeMap, templateTags: $templateTags, impurePoints: $mainType->getImpurePoints(), invalidateExpressions: $mainType->getInvalidateExpressions(), usedVariables: $mainType->getUsedVariables(), acceptsNamedArguments: $mainType->acceptsNamedArguments(), mustUseReturnValue: $mainType->mustUseReturnValue(), assertions: $assertions, isStatic: $mainType->isStaticClosure());
1159: if ($closure->isPure()->yes() && $returnType->isVoid()->yes()) {
1160: return new ErrorType();
1161: }
1162:
1163: return $closure;
1164: }
1165:
1166: return new ErrorType();
1167: }
1168:
1169: /**
1170: * Interprets a conditional return type referencing the callable's own parameter,
1171: * like `callable(mixed $value): ($value is int ? true : false)`, as a type predicate.
1172: *
1173: * @param list<NativeParameterReflection> $parameters
1174: */
1175: private function resolveCallableReturnTypeAssertions(CallableTypeNode $typeNode, NameScope $nameScope, array $parameters): ?Assertions
1176: {
1177: $returnTypeNode = $typeNode->returnType;
1178: if (!$returnTypeNode instanceof ConditionalTypeForParameterNode) {
1179: return null;
1180: }
1181:
1182: foreach ($parameters as $parameter) {
1183: if ('$' . $parameter->getName() !== $returnTypeNode->parameterName) {
1184: continue;
1185: }
1186:
1187: return CallableAssertionsHelper::createAssertionsFromConditional(
1188: $returnTypeNode->parameterName,
1189: $this->resolveType($returnTypeNode->targetType, $nameScope),
1190: $returnTypeNode->negated,
1191: $this->resolveType($returnTypeNode->if, $nameScope),
1192: $this->resolveType($returnTypeNode->else, $nameScope),
1193: );
1194: }
1195:
1196: return null;
1197: }
1198:
1199: private function resolveArrayShapeNode(ArrayShapeNode $typeNode, NameScope $nameScope): Type
1200: {
1201: $items = [];
1202: foreach ($typeNode->items as $itemNode) {
1203: $items[] = [
1204: $this->resolveArrayShapeOffsetType($itemNode, $nameScope),
1205: $this->resolveType($itemNode->valueType, $nameScope),
1206: $itemNode->optional,
1207: ];
1208: }
1209:
1210: $unsealed = null;
1211: if (!$typeNode->sealed) {
1212: // A key type that is not written down is derived from the shape kind
1213: // when the shape gets built, so that it can be printed back as `...`.
1214: $unsealedKeyType = $typeNode->unsealedType === null || $typeNode->unsealedType->keyType === null
1215: ? null
1216: : $this->transformUnsafeArrayKey($this->resolveType($typeNode->unsealedType->keyType, $nameScope));
1217:
1218: $unsealedValueType = $typeNode->unsealedType === null
1219: ? new MixedType()
1220: : $this->resolveType($typeNode->unsealedType->valueType, $nameScope);
1221:
1222: $unsealed = [$unsealedKeyType, $unsealedValueType];
1223: }
1224:
1225: return LateResolvableArrayShapeType::create($items, $unsealed, $typeNode->kind);
1226: }
1227:
1228: private function resolveArrayShapeOffsetType(ArrayShapeItemNode $itemNode, NameScope $nameScope): ?Type
1229: {
1230: if ($itemNode->keyName instanceof ConstExprIntegerNode) {
1231: return new ConstantIntegerType((int) $itemNode->keyName->value);
1232: } elseif ($itemNode->keyName instanceof IdentifierTypeNode) {
1233: $templateType = $nameScope->resolveTemplateTypeName($itemNode->keyName->name);
1234: if ($templateType !== null) {
1235: return $templateType;
1236: }
1237:
1238: return new ConstantStringType($itemNode->keyName->name);
1239: } elseif ($itemNode->keyName instanceof ConstExprStringNode) {
1240: return new ConstantStringType($itemNode->keyName->value);
1241: } elseif ($itemNode->keyName instanceof ConstFetchNode) {
1242: $constExpr = $itemNode->keyName;
1243: if ($constExpr->className === '') {
1244: throw new ShouldNotHappenException(); // global constant should get parsed as class name in IdentifierTypeNode
1245: }
1246:
1247: $isStatic = false;
1248: if ($nameScope->getClassName() !== null) {
1249: switch (strtolower($constExpr->className)) {
1250: case 'static':
1251: $className = $nameScope->getClassName();
1252: $isStatic = true;
1253: break;
1254:
1255: case 'self':
1256: $className = $nameScope->getClassName();
1257: break;
1258:
1259: case 'parent':
1260: if ($this->getReflectionProvider()->hasClass($nameScope->getClassName())) {
1261: $classReflection = $this->getReflectionProvider()->getClass($nameScope->getClassName());
1262: if ($classReflection->getParentClass() === null) {
1263: return new ErrorType();
1264:
1265: }
1266:
1267: $className = $classReflection->getParentClass()->getName();
1268: }
1269: break;
1270: }
1271: }
1272:
1273: if (!isset($className)) {
1274: $className = $nameScope->resolveStringName($constExpr->className);
1275: }
1276:
1277: if (!$this->getReflectionProvider()->hasClass($className)) {
1278: return new ErrorType();
1279: }
1280: $classReflection = $this->getReflectionProvider()->getClass($className);
1281:
1282: if ($isStatic && $classReflection->isFinal()) {
1283: $isStatic = false;
1284: }
1285:
1286: $constantName = $constExpr->name;
1287: if (strtolower($constantName) === 'class') {
1288: if ($isStatic) {
1289: return new GenericClassStringType(new StaticType($classReflection));
1290: }
1291:
1292: return new ConstantStringType($classReflection->getName(), true);
1293: }
1294:
1295: if (!$classReflection->hasConstant($constantName)) {
1296: return new ErrorType();
1297: }
1298:
1299: if ($isStatic) {
1300: return new ClassConstantAccessType(new StaticType($classReflection), $constantName);
1301: }
1302:
1303: $reflectionConstant = $classReflection->getNativeReflection()->getReflectionConstant($constantName);
1304: if ($reflectionConstant === false) {
1305: return new ErrorType();
1306: }
1307: $declaringClass = $reflectionConstant->getDeclaringClass();
1308:
1309: return $this->initializerExprTypeResolver->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($declaringClass->getName(), $declaringClass->getFileName() ?: null));
1310: } elseif ($itemNode->keyName !== null) {
1311: throw new ShouldNotHappenException('Unsupported key node type: ' . get_class($itemNode->keyName));
1312: }
1313:
1314: return null;
1315: }
1316:
1317: private function resolveObjectShapeNode(ObjectShapeNode $typeNode, NameScope $nameScope): Type
1318: {
1319: $items = [];
1320: foreach ($typeNode->items as $itemNode) {
1321: if ($itemNode->keyName instanceof IdentifierTypeNode) {
1322: $keyType = $nameScope->resolveTemplateTypeName($itemNode->keyName->name)
1323: ?? new ConstantStringType($itemNode->keyName->name);
1324: } else {
1325: $keyType = new ConstantStringType($itemNode->keyName->value);
1326: }
1327:
1328: $items[] = [$keyType, $this->resolveType($itemNode->valueType, $nameScope), $itemNode->optional];
1329: }
1330:
1331: return LateResolvableObjectShapeType::create($items);
1332: }
1333:
1334: private function resolveConstTypeNode(ConstTypeNode $typeNode, NameScope $nameScope): Type
1335: {
1336: $constExpr = $typeNode->constExpr;
1337: if ($constExpr instanceof ConstExprArrayNode) {
1338: throw new ShouldNotHappenException(); // we prefer array shapes
1339: }
1340:
1341: if (
1342: $constExpr instanceof ConstExprFalseNode
1343: || $constExpr instanceof ConstExprTrueNode
1344: || $constExpr instanceof ConstExprNullNode
1345: ) {
1346: throw new ShouldNotHappenException(); // we prefer IdentifierTypeNode
1347: }
1348:
1349: if ($constExpr instanceof ConstFetchNode) {
1350: if ($constExpr->className === '') {
1351: throw new ShouldNotHappenException(); // global constant should get parsed as class name in IdentifierTypeNode
1352: }
1353:
1354: $isStatic = false;
1355: if ($nameScope->getClassName() !== null) {
1356: switch (strtolower($constExpr->className)) {
1357: case 'static':
1358: $className = $nameScope->getClassName();
1359: $isStatic = true;
1360: break;
1361:
1362: case 'self':
1363: $className = $nameScope->getClassName();
1364: break;
1365:
1366: case 'parent':
1367: if ($this->getReflectionProvider()->hasClass($nameScope->getClassName())) {
1368: $classReflection = $this->getReflectionProvider()->getClass($nameScope->getClassName());
1369: if ($classReflection->getParentClass() === null) {
1370: return new ErrorType();
1371:
1372: }
1373:
1374: $className = $classReflection->getParentClass()->getName();
1375: }
1376: break;
1377: }
1378: }
1379:
1380: if (!isset($className)) {
1381: $templateType = $nameScope->resolveTemplateTypeName($constExpr->className);
1382: if ($templateType instanceof TemplateType) {
1383: if (strtolower($constExpr->name) === 'class') {
1384: return new GenericClassStringType($templateType);
1385: }
1386:
1387: // A template bound to a final class can only be that class. Any other can be a class
1388: // declaring constants its bound does not - known once the template is resolved.
1389: $boundClassReflections = $templateType->getBound()->getObjectClassReflections();
1390: if (count($boundClassReflections) !== 1 || !$boundClassReflections[0]->isFinal()) {
1391: return new ClassConstantAccessType($templateType, $constExpr->name);
1392: }
1393:
1394: $className = $boundClassReflections[0]->getName();
1395: }
1396: }
1397:
1398: if (!isset($className)) {
1399: $className = $nameScope->resolveStringName($constExpr->className);
1400: }
1401:
1402: if (!$this->getReflectionProvider()->hasClass($className)) {
1403: return new ErrorType();
1404: }
1405:
1406: $classReflection = $this->getReflectionProvider()->getClass($className);
1407:
1408: if ($isStatic && $classReflection->isFinal()) {
1409: $isStatic = false;
1410: }
1411:
1412: $constantName = $constExpr->name;
1413: if (strtolower($constantName) === 'class') {
1414: if ($isStatic) {
1415: return new GenericClassStringType(new StaticType($classReflection));
1416: }
1417:
1418: return new ConstantStringType($classReflection->getName(), true);
1419: }
1420:
1421: // A class that is not final can have subclasses declaring constants it does not - what
1422: // static:: stands for is known once static is resolved.
1423: if ($isStatic) {
1424: return new ClassConstantAccessType(new StaticType($classReflection), $constantName);
1425: }
1426:
1427: if (Strings::contains($constantName, '*')) {
1428: // convert * into .*? and escape everything else so the constants can be matched against the pattern
1429: $pattern = '{^' . str_replace('\\*', '.*?', preg_quote($constantName)) . '$}D';
1430: $constantTypes = [];
1431: foreach ($classReflection->getNativeReflection()->getReflectionConstants() as $reflectionConstant) {
1432: $classConstantName = $reflectionConstant->getName();
1433: if (Strings::match($classConstantName, $pattern) === null) {
1434: continue;
1435: }
1436:
1437: if ($classReflection->isEnum() && $classReflection->hasEnumCase($classConstantName)) {
1438: $constantTypes[] = new EnumCaseObjectType($classReflection->getName(), $classConstantName);
1439: continue;
1440: }
1441:
1442: $declaringClassName = $reflectionConstant->getDeclaringClass()->getName();
1443: if (!$this->getReflectionProvider()->hasClass($declaringClassName)) {
1444: continue;
1445: }
1446:
1447: $constantTypes[] = $this->initializerExprTypeResolver->getType(
1448: $reflectionConstant->getValueExpression(),
1449: InitializerExprContext::fromClassReflection(
1450: $this->getReflectionProvider()->getClass($declaringClassName),
1451: ),
1452: );
1453: }
1454:
1455: if (count($constantTypes) === 0) {
1456: return new ErrorType();
1457: }
1458:
1459: return TypeCombinator::union(...$constantTypes);
1460: }
1461:
1462: if (!$classReflection->hasConstant($constantName)) {
1463: return new ErrorType();
1464: }
1465:
1466: if ($classReflection->isEnum() && $classReflection->hasEnumCase($constantName)) {
1467: return new EnumCaseObjectType($classReflection->getName(), $constantName);
1468: }
1469:
1470: $reflectionConstant = $classReflection->getNativeReflection()->getReflectionConstant($constantName);
1471: if ($reflectionConstant === false) {
1472: return new ErrorType();
1473: }
1474: $declaringClass = $reflectionConstant->getDeclaringClass();
1475:
1476: return $this->initializerExprTypeResolver->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($declaringClass->getName(), $declaringClass->getFileName() ?: null));
1477: }
1478:
1479: if ($constExpr instanceof ConstExprFloatNode) {
1480: return new ConstantFloatType((float) $constExpr->value);
1481: }
1482:
1483: if ($constExpr instanceof ConstExprIntegerNode) {
1484: return new ConstantIntegerType((int) $constExpr->value);
1485: }
1486:
1487: if ($constExpr instanceof ConstExprStringNode) {
1488: return new ConstantStringType($constExpr->value);
1489: }
1490:
1491: return new ErrorType();
1492: }
1493:
1494: private function resolveOffsetAccessNode(OffsetAccessTypeNode $typeNode, NameScope $nameScope): Type
1495: {
1496: $type = $this->resolveType($typeNode->type, $nameScope);
1497: $offset = $this->resolveType($typeNode->offset, $nameScope);
1498:
1499: if ($type->isOffsetAccessible()->no() || $type->hasOffsetValueType($offset)->no()) {
1500: return new ErrorType();
1501: }
1502:
1503: return new OffsetAccessType($type, $offset);
1504: }
1505:
1506: private function resolveFloatRangeBound(Type $type, TypeNode $typeNode, string $keyword, float $keywordValue): ?float
1507: {
1508: if ($typeNode instanceof IdentifierTypeNode && $typeNode->name === $keyword) {
1509: return $keywordValue;
1510: }
1511:
1512: if ($type instanceof ConstantIntegerType) {
1513: return (float) $type->getValue();
1514: }
1515:
1516: if ($type instanceof ConstantFloatType && !is_nan($type->getValue())) {
1517: return $type->getValue();
1518: }
1519:
1520: return null;
1521: }
1522:
1523: private function expandIntMaskToType(Type $type): ?Type
1524: {
1525: $ints = array_map(static fn (ConstantIntegerType $type) => $type->getValue(), TypeUtils::getConstantIntegers($type));
1526: if (count($ints) === 0) {
1527: return null;
1528: }
1529:
1530: $values = [];
1531:
1532: foreach ($ints as $int) {
1533: if ($int !== 0 && !array_key_exists($int, $values)) {
1534: foreach ($values as $value) {
1535: $computedValue = $value | $int;
1536: $values[$computedValue] = $computedValue;
1537: }
1538: }
1539:
1540: $values[$int] = $int;
1541: }
1542:
1543: $values[0] = 0;
1544:
1545: $min = min($values);
1546: $max = max($values);
1547:
1548: if ($max - $min === count($values) - 1) {
1549: return IntegerRangeType::fromInterval($min, $max);
1550: }
1551:
1552: if (count($values) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1553: return IntegerRangeType::fromInterval($min, $max);
1554: }
1555:
1556: return TypeCombinator::union(...array_map(static fn ($value) => new ConstantIntegerType($value), $values));
1557: }
1558:
1559: /**
1560: * @api
1561: * @param TypeNode[] $typeNodes
1562: * @return list<Type>
1563: */
1564: public function resolveMultiple(array $typeNodes, NameScope $nameScope): array
1565: {
1566: $types = [];
1567: foreach ($typeNodes as $typeNode) {
1568: $types[] = $this->resolveType($typeNode, $nameScope);
1569: }
1570:
1571: return $types;
1572: }
1573:
1574: private function getReflectionProvider(): ReflectionProvider
1575: {
1576: return $this->reflectionProviderProvider->getReflectionProvider();
1577: }
1578:
1579: private function getTypeAliasResolver(): TypeAliasResolver
1580: {
1581: return $this->typeAliasResolverProvider->getTypeAliasResolver();
1582: }
1583:
1584: }
1585: