1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Generic;
4:
5: use PHPStan\PhpDocParser\Ast\Type\FullyQualifiedNameNode;
6: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
7: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
8: use PHPStan\Reflection\ClassMemberAccessAnswerer;
9: use PHPStan\Reflection\ClassReflection;
10: use PHPStan\Reflection\ExtendedMethodReflection;
11: use PHPStan\Reflection\ExtendedPropertyReflection;
12: use PHPStan\Reflection\ReflectionProviderStaticAccessor;
13: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
14: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
15: use PHPStan\ShouldNotHappenException;
16: use PHPStan\Turbo\ShadowedByTurboExtension;
17: use PHPStan\Type\AcceptsResult;
18: use PHPStan\Type\CompoundType;
19: use PHPStan\Type\ErrorType;
20: use PHPStan\Type\InstanceofDeprecated;
21: use PHPStan\Type\IntersectionType;
22: use PHPStan\Type\IsSuperTypeOfResult;
23: use PHPStan\Type\ObjectType;
24: use PHPStan\Type\RecursionGuard;
25: use PHPStan\Type\Type;
26: use PHPStan\Type\TypeWithClassName;
27: use PHPStan\Type\UnionType;
28: use PHPStan\Type\VerbosityLevel;
29: use function array_map;
30: use function count;
31: use function implode;
32: use function sprintf;
33:
34: /** @api */
35: #[InstanceofDeprecated]
36: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/GenericObjectType.cpp')]
37: class GenericObjectType extends ObjectType
38: {
39:
40: /**
41: * @api
42: * @param array<int, Type> $types
43: * @param array<int, TemplateTypeVariance> $variances
44: */
45: public function __construct(
46: string $mainType,
47: private array $types,
48: ?Type $subtractedType = null,
49: private ?ClassReflection $classReflection = null,
50: private array $variances = [],
51: )
52: {
53: parent::__construct($mainType, $subtractedType, $classReflection);
54: }
55:
56: public function describe(VerbosityLevel $level): string
57: {
58: return sprintf(
59: '%s<%s>',
60: parent::describe($level),
61: implode(', ', array_map(
62: static fn (Type $type, ?TemplateTypeVariance $variance = null): string => TypeProjectionHelper::describe($type, $variance, $level),
63: $this->types,
64: $this->variances,
65: )),
66: );
67: }
68:
69: public function equals(Type $type): bool
70: {
71: if (!$type instanceof self) {
72: return false;
73: }
74:
75: if (!parent::equals($type)) {
76: return false;
77: }
78:
79: if (count($this->types) !== count($type->types)) {
80: return false;
81: }
82:
83: foreach ($this->types as $i => $genericType) {
84: $otherGenericType = $type->types[$i];
85: if (!$genericType->equals($otherGenericType)) {
86: return false;
87: }
88:
89: $variance = $this->variances[$i] ?? TemplateTypeVariance::createInvariant();
90: $otherVariance = $type->variances[$i] ?? TemplateTypeVariance::createInvariant();
91: if (!$variance->equals($otherVariance)) {
92: return false;
93: }
94: }
95:
96: return true;
97: }
98:
99: public function getReferencedClasses(): array
100: {
101: $classes = parent::getReferencedClasses();
102: foreach ($this->types as $type) {
103: $referencedClasses = RecursionGuard::runOnObjectIdentity($type, static fn () => $type->getReferencedClasses());
104: if ($referencedClasses instanceof ErrorType) {
105: continue;
106: }
107: foreach ($referencedClasses as $referencedClass) {
108: $classes[] = $referencedClass;
109: }
110: }
111:
112: return $classes;
113: }
114:
115: /** @return array<int, Type> */
116: public function getTypes(): array
117: {
118: return $this->types;
119: }
120:
121: /** @return array<int, TemplateTypeVariance> */
122: public function getVariances(): array
123: {
124: return $this->variances;
125: }
126:
127: public function accepts(Type $type, bool $strictTypes): AcceptsResult
128: {
129: if ($type instanceof CompoundType) {
130: return $type->isAcceptedBy($this, $strictTypes);
131: }
132:
133: return $this->isSuperTypeOfInternal($type, true)->toAcceptsResult();
134: }
135:
136: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
137: {
138: if ($type instanceof CompoundType) {
139: return $type->isSubTypeOf($this);
140: }
141:
142: return $this->isSuperTypeOfInternal($type, false);
143: }
144:
145: private function isSuperTypeOfInternal(Type $type, bool $acceptsContext): IsSuperTypeOfResult
146: {
147: $nakedSuperTypeOf = parent::isSuperTypeOf($type);
148: if ($nakedSuperTypeOf->no()) {
149: return $nakedSuperTypeOf;
150: }
151:
152: if (!$type instanceof ObjectType) {
153: return $nakedSuperTypeOf;
154: }
155:
156: $ancestor = $type->getAncestorWithClassName($this->getClassName());
157: if ($ancestor === null) {
158: return $nakedSuperTypeOf;
159: }
160: if (!$ancestor instanceof self) {
161: if ($acceptsContext) {
162: return $nakedSuperTypeOf;
163: }
164:
165: return $nakedSuperTypeOf->and(IsSuperTypeOfResult::createMaybe());
166: }
167:
168: if (count($this->types) !== count($ancestor->types)) {
169: return IsSuperTypeOfResult::createNo();
170: }
171:
172: $classReflection = $this->getClassReflection();
173: if ($classReflection === null) {
174: return $nakedSuperTypeOf;
175: }
176:
177: // Type arguments of a class name written without them are resolved to the
178: // template bounds, so a `mixed` there means "not parameterized" and stays
179: // compatible with any other type argument. When the other side is explicitly
180: // parameterized, `mixed` is a type argument like any other and the variance
181: // has to be evaluated strictly - otherwise `Foo<mixed>` and `Foo<int>` would
182: // be supertypes of each other and TypeCombinator::union() would discard one
183: // of them depending on their order.
184: $strictVariance = !$acceptsContext && $type instanceof self;
185:
186: $typeList = $classReflection->typeMapToList($classReflection->getTemplateTypeMap());
187: $results = [];
188: foreach ($typeList as $i => $templateType) {
189: if (!isset($ancestor->types[$i])) {
190: continue;
191: }
192: if (!isset($this->types[$i])) {
193: continue;
194: }
195: if ($templateType instanceof ErrorType) {
196: continue;
197: }
198: if (!$templateType instanceof TemplateType) {
199: throw new ShouldNotHappenException();
200: }
201:
202: $thisVariance = $this->variances[$i] ?? TemplateTypeVariance::createInvariant();
203: $ancestorVariance = $ancestor->variances[$i] ?? TemplateTypeVariance::createInvariant();
204: if (!$thisVariance->invariant()) {
205: $results[] = $thisVariance->isValidVariance($templateType, $this->types[$i], $ancestor->types[$i], $strictVariance);
206: } else {
207: $results[] = $templateType->isValidVariance($this->types[$i], $ancestor->types[$i], $strictVariance);
208: }
209:
210: $results[] = IsSuperTypeOfResult::createFromBoolean($thisVariance->validPosition($ancestorVariance));
211: }
212:
213: if (count($results) === 0) {
214: return $nakedSuperTypeOf;
215: }
216:
217: $result = IsSuperTypeOfResult::createYes();
218: foreach ($results as $innerResult) {
219: $result = $result->and($innerResult);
220: }
221:
222: return $result;
223: }
224:
225: public function getClassReflection(): ?ClassReflection
226: {
227: if ($this->classReflection !== null) {
228: return $this->classReflection;
229: }
230:
231: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
232: if (!$reflectionProvider->hasClass($this->getClassName())) {
233: return null;
234: }
235:
236: return $this->classReflection = $reflectionProvider->getClass($this->getClassName())
237: ->withTypes($this->types)
238: ->withVariances($this->variances);
239: }
240:
241: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
242: {
243: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
244: }
245:
246: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
247: {
248: $prototype = parent::getUnresolvedPropertyPrototype($propertyName, $scope);
249:
250: return $prototype->doNotResolveTemplateTypeMapToBounds();
251: }
252:
253: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
254: {
255: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
256: }
257:
258: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
259: {
260: $prototype = parent::getUnresolvedInstancePropertyPrototype($propertyName, $scope);
261:
262: return $prototype->doNotResolveTemplateTypeMapToBounds();
263: }
264:
265: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
266: {
267: return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty();
268: }
269:
270: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
271: {
272: $prototype = parent::getUnresolvedStaticPropertyPrototype($propertyName, $scope);
273:
274: return $prototype->doNotResolveTemplateTypeMapToBounds();
275: }
276:
277: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
278: {
279: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
280: }
281:
282: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
283: {
284: $prototype = parent::getUnresolvedMethodPrototype($methodName, $scope);
285:
286: return $prototype->doNotResolveTemplateTypeMapToBounds();
287: }
288:
289: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
290: {
291: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
292: return $receivedType->inferTemplateTypesOn($this);
293: }
294:
295: if (!$receivedType instanceof TypeWithClassName) {
296: return TemplateTypeMap::createEmpty();
297: }
298:
299: $ancestor = $receivedType->getAncestorWithClassName($this->getClassName());
300:
301: if ($ancestor === null) {
302: return TemplateTypeMap::createEmpty();
303: }
304: $ancestorClassReflection = $ancestor->getClassReflection();
305: if ($ancestorClassReflection === null) {
306: return TemplateTypeMap::createEmpty();
307: }
308:
309: $otherTypes = $ancestorClassReflection->typeMapToList($ancestorClassReflection->getActiveTemplateTypeMap());
310: $typeList = $ancestorClassReflection->typeMapToList($ancestorClassReflection->getTemplateTypeMap());
311: $typeMap = TemplateTypeMap::createEmpty();
312:
313: foreach ($this->getTypes() as $i => $type) {
314: $other = $otherTypes[$i] ?? new ErrorType();
315: $inferred = $type->inferTemplateTypes($other);
316:
317: $effectiveVariance = $this->variances[$i] ?? TemplateTypeVariance::createInvariant();
318: if ($effectiveVariance->invariant() && isset($typeList[$i]) && $typeList[$i] instanceof TemplateType) {
319: $effectiveVariance = $typeList[$i]->getVariance();
320: }
321: if ($effectiveVariance->contravariant()) {
322: $inferred = $inferred->swapBounds();
323: }
324:
325: $typeMap = $typeMap->union($inferred);
326: }
327:
328: return $typeMap;
329: }
330:
331: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
332: {
333: $classReflection = $this->getClassReflection();
334: if ($classReflection !== null) {
335: $typeList = $classReflection->typeMapToList($classReflection->getTemplateTypeMap());
336: } else {
337: $typeList = [];
338: }
339:
340: $references = [];
341:
342: foreach ($this->types as $i => $type) {
343: $effectiveVariance = $this->variances[$i] ?? TemplateTypeVariance::createInvariant();
344: if ($effectiveVariance->invariant() && isset($typeList[$i]) && $typeList[$i] instanceof TemplateType) {
345: $effectiveVariance = $typeList[$i]->getVariance();
346: }
347:
348: $variance = $positionVariance->compose($effectiveVariance);
349: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
350: $references[] = $reference;
351: }
352: }
353:
354: return $references;
355: }
356:
357: public function traverse(callable $cb): Type
358: {
359: $subtractedType = $this->getSubtractedType() !== null ? $cb($this->getSubtractedType()) : null;
360:
361: $typesChanged = false;
362: $types = [];
363: foreach ($this->types as $type) {
364: $newType = $cb($type);
365: $types[] = $newType;
366: if ($newType === $type) {
367: continue;
368: }
369:
370: $typesChanged = true;
371: }
372:
373: if ($subtractedType !== $this->getSubtractedType() || $typesChanged) {
374: return $this->recreate($this->getClassName(), $types, $subtractedType, $this->variances);
375: }
376:
377: return $this;
378: }
379:
380: public function traverseSimultaneously(Type $right, callable $cb): Type
381: {
382: if (!$right instanceof TypeWithClassName) {
383: return $this;
384: }
385:
386: $ancestor = $right->getAncestorWithClassName($this->getClassName());
387: if (!$ancestor instanceof self) {
388: return $this;
389: }
390:
391: if (count($this->types) !== count($ancestor->types)) {
392: return $this;
393: }
394:
395: $typesChanged = false;
396: $types = [];
397: foreach ($this->types as $i => $leftType) {
398: $rightType = $ancestor->types[$i];
399: $newType = $cb($leftType, $rightType);
400: $types[] = $newType;
401: if ($newType === $leftType) {
402: continue;
403: }
404:
405: $typesChanged = true;
406: }
407:
408: if ($typesChanged) {
409: return $this->recreate($this->getClassName(), $types, null);
410: }
411:
412: return $this;
413: }
414:
415: /**
416: * @param Type[] $types
417: * @param TemplateTypeVariance[] $variances
418: */
419: protected function recreate(string $className, array $types, ?Type $subtractedType, array $variances = []): self
420: {
421: return new self(
422: $className,
423: $types,
424: $subtractedType,
425: null,
426: $variances,
427: );
428: }
429:
430: /**
431: * @param TemplateTypeVariance[] $variances
432: */
433: public function changeVariances(array $variances): self
434: {
435: return $this->recreate($this->getClassName(), $this->getTypes(), $this->getSubtractedType(), $variances);
436: }
437:
438: public function withoutFinalByKeywordOverride(): Type
439: {
440: if ($this->classReflection === null || !$this->classReflection->hasFinalByKeywordOverride()) {
441: return $this;
442: }
443:
444: return new self(
445: $this->getClassName(),
446: $this->types,
447: $this->getSubtractedType(),
448: $this->classReflection->withoutFinalByKeywordOverride(),
449: $this->variances,
450: );
451: }
452:
453: public function changeSubtractedType(?Type $subtractedType): Type
454: {
455: $result = parent::changeSubtractedType($subtractedType);
456:
457: // Parent handles sealed type exhaustiveness (returning NeverType when all
458: // allowed subtypes are subtracted, or a single remaining subtype).
459: if (!$result instanceof ObjectType || $result->getClassName() !== $this->getClassName()) {
460: return $result;
461: }
462:
463: return new self($this->getClassName(), $this->types, $subtractedType, null, $this->variances);
464: }
465:
466: public function toPhpDocNode(): TypeNode
467: {
468: /** @var FullyQualifiedNameNode $parent */
469: $parent = parent::toPhpDocNode();
470: return new GenericTypeNode(
471: $parent,
472: array_map(static fn (Type $type) => $type->toPhpDocNode(), $this->types),
473: array_map(static fn (TemplateTypeVariance $variance) => $variance->toPhpDocNodeVariance(), $this->variances),
474: );
475: }
476:
477: public function hasTemplateOrLateResolvableType(): bool
478: {
479: foreach ($this->types as $type) {
480: if (!$type->hasTemplateOrLateResolvableType()) {
481: continue;
482: }
483:
484: return true;
485: }
486:
487: if ($this->getSubtractedType() === null) {
488: return false;
489: }
490:
491: return $this->getSubtractedType()->hasTemplateOrLateResolvableType();
492: }
493:
494: public function hasUnresolvedTemplateArgumentType(): bool
495: {
496: foreach ($this->types as $type) {
497: if ($type->hasUnresolvedTemplateArgumentType()) {
498: return true;
499: }
500: }
501:
502: $subtractedType = $this->getSubtractedType();
503:
504: return $subtractedType !== null && $subtractedType->hasUnresolvedTemplateArgumentType();
505: }
506:
507: }
508: