1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Generic;
4:
5: use PHPStan\DependencyInjection\BleedingEdgeToggle;
6: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
7: use PHPStan\ShouldNotHappenException;
8: use PHPStan\TrinaryLogic;
9: use PHPStan\Turbo\ShadowedByTurboExtension;
10: use PHPStan\Type\BenevolentUnionType;
11: use PHPStan\Type\IsSuperTypeOfResult;
12: use PHPStan\Type\MixedType;
13: use PHPStan\Type\NeverType;
14: use PHPStan\Type\Type;
15: use function sprintf;
16:
17: /**
18: * Represents the variance of a template type parameter.
19: *
20: * Variance describes how subtyping of a generic type relates to subtyping of its
21: * type arguments. For a class `Box<T>`:
22: *
23: * - **Invariant** (default): `Box<Cat>` is NOT a subtype of `Box<Animal>`, even though
24: * Cat extends Animal. The type argument must match exactly. Declared with `@template T`.
25: * - **Covariant**: `Box<Cat>` IS a subtype of `Box<Animal>`. Safe when T only appears
26: * in "output" positions (return types). Declared with `@template-covariant T`.
27: * - **Contravariant**: `Box<Animal>` IS a subtype of `Box<Cat>`. Safe when T only
28: * appears in "input" positions (parameter types). Declared with `@template-contravariant T`.
29: * - **Bivariant**: The type argument is ignored for subtyping purposes. Rarely used.
30: * - **Static**: Special variance for `static` return type in template context.
31: *
32: * Variance composition follows standard rules — e.g. covariant composed with
33: * contravariant yields contravariant. This is used when template types appear
34: * inside nested generic types.
35: *
36: * @api
37: */
38: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateTypeVariance.cpp')]
39: final class TemplateTypeVariance
40: {
41:
42: private const INVARIANT = 1;
43: private const COVARIANT = 2;
44: private const CONTRAVARIANT = 3;
45: private const STATIC = 4;
46: private const BIVARIANT = 5;
47:
48: /** @var self[] */
49: private static array $registry;
50:
51: private function __construct(private int $value)
52: {
53: }
54:
55: private static function create(int $value): self
56: {
57: self::$registry[$value] ??= new self($value);
58: return self::$registry[$value];
59: }
60:
61: /** Type argument must match exactly. This is the default for @template T. */
62: public static function createInvariant(): self
63: {
64: return self::create(self::INVARIANT);
65: }
66:
67: /** Subtyping flows with the type argument: Cat <: Animal ⟹ Box<Cat> <: Box<Animal>. */
68: public static function createCovariant(): self
69: {
70: return self::create(self::COVARIANT);
71: }
72:
73: /** Subtyping flows against the type argument: Cat <: Animal ⟹ Box<Animal> <: Box<Cat>. */
74: public static function createContravariant(): self
75: {
76: return self::create(self::CONTRAVARIANT);
77: }
78:
79: /** Special variance for static return type in template context. */
80: public static function createStatic(): self
81: {
82: return self::create(self::STATIC);
83: }
84:
85: /** Type argument is ignored for subtyping — all types are compatible. */
86: public static function createBivariant(): self
87: {
88: return self::create(self::BIVARIANT);
89: }
90:
91: public function invariant(): bool
92: {
93: return $this->value === self::INVARIANT;
94: }
95:
96: public function covariant(): bool
97: {
98: return $this->value === self::COVARIANT;
99: }
100:
101: public function contravariant(): bool
102: {
103: return $this->value === self::CONTRAVARIANT;
104: }
105:
106: public function static(): bool
107: {
108: return $this->value === self::STATIC;
109: }
110:
111: public function bivariant(): bool
112: {
113: return $this->value === self::BIVARIANT;
114: }
115:
116: public function compose(self $other): self
117: {
118: if ($this->contravariant()) {
119: if ($other->contravariant()) {
120: return self::createCovariant();
121: }
122: if ($other->covariant()) {
123: return self::createContravariant();
124: }
125: if ($other->bivariant()) {
126: return self::createBivariant();
127: }
128: return self::createInvariant();
129: }
130:
131: if ($this->covariant()) {
132: if ($other->contravariant()) {
133: return self::createContravariant();
134: }
135: if ($other->covariant()) {
136: return self::createCovariant();
137: }
138: if ($other->bivariant()) {
139: return self::createBivariant();
140: }
141: return self::createInvariant();
142: }
143:
144: if ($this->invariant()) {
145: return self::createInvariant();
146: }
147:
148: if ($this->bivariant()) {
149: return self::createBivariant();
150: }
151:
152: return $other;
153: }
154:
155: /**
156: * By default `mixed` and benevolent unions are compatible with any other type
157: * argument in both directions - that is how gradual typing works.
158: *
159: * With $strict that answer is not given: it makes the relation symmetric
160: * (`Foo<mixed>` and `Foo<int>` end up supertypes of each other) and
161: * TypeCombinator::union() then discards one of them depending on the order the
162: * types come in. In the strict mode invariance is relaxed just enough to keep
163: * `Foo<mixed>` a supertype of `Foo<int>` and not the other way around.
164: */
165: public function isValidVariance(TemplateType $templateType, Type $a, Type $b, bool $strict = false): IsSuperTypeOfResult
166: {
167: if ($b instanceof NeverType) {
168: return IsSuperTypeOfResult::createYes();
169: }
170:
171: if (!$strict) {
172: if ($a instanceof MixedType && !$a instanceof TemplateType) {
173: return IsSuperTypeOfResult::createYes();
174: }
175:
176: if ($a instanceof BenevolentUnionType) {
177: if (!$a->isSuperTypeOf($b)->no()) {
178: return IsSuperTypeOfResult::createYes();
179: }
180: }
181:
182: if ($b instanceof BenevolentUnionType) {
183: if (!$b->isSuperTypeOf($a)->no()) {
184: return IsSuperTypeOfResult::createYes();
185: }
186: }
187:
188: if ($b instanceof MixedType && !$b instanceof TemplateType) {
189: return IsSuperTypeOfResult::createYes();
190: }
191: }
192:
193: if ($this->invariant()) {
194: if ($a instanceof TemplateType && $b instanceof TemplateType
195: && $a->getScope()->equals($b->getScope())
196: && $a->getName() === $b->getName()
197: ) {
198: return IsSuperTypeOfResult::createYes();
199: }
200:
201: if ($strict) {
202: if ($a instanceof MixedType && !$a instanceof TemplateType) {
203: return IsSuperTypeOfResult::createYes();
204: }
205:
206: if ($a instanceof BenevolentUnionType && !$a->isSuperTypeOf($b)->no()) {
207: return IsSuperTypeOfResult::createYes();
208: }
209:
210: if ($b instanceof BenevolentUnionType && !$b->isSuperTypeOf($a)->no()) {
211: return IsSuperTypeOfResult::createMaybe();
212: }
213:
214: if ($b instanceof MixedType && !$b instanceof TemplateType) {
215: return IsSuperTypeOfResult::createMaybe();
216: }
217: }
218:
219: $result = $a->equals($b);
220: $reasons = [];
221: if (!$result) {
222: $isSuperType = $a->isSuperTypeOf($b)->yes();
223: // invariant arguments are the same type when each is a subtype of the other;
224: // an unresolved template argument stays opaque here - it never equals its delegate.
225: // Legacy array shapes are open as subtypes and closed as supertypes, so array{a: int}
226: // and array{a: int, b?: int} would be subtypes of each other without bleeding edge
227: if (
228: $isSuperType
229: && BleedingEdgeToggle::isBleedingEdge()
230: && !$a->hasUnresolvedTemplateArgumentType()
231: && !$b->hasUnresolvedTemplateArgumentType()
232: && $b->isSuperTypeOf($a)->yes()
233: ) {
234: $result = true;
235: } elseif (
236: $templateType->getScope()->getClassName() !== null
237: && $isSuperType
238: ) {
239: $reasons[] = sprintf(
240: 'Template type %s on class %s is not covariant. Learn more: <fg=cyan>https://phpstan.org/blog/whats-up-with-template-covariant</>',
241: $templateType->getName(),
242: $templateType->getScope()->getClassName(),
243: );
244: }
245: }
246:
247: return new IsSuperTypeOfResult(TrinaryLogic::createFromBoolean($result), $reasons);
248: }
249:
250: if ($this->covariant() || $this->contravariant()) {
251: // The "exactly this class" flavour of a `new Foo()` value cannot be written
252: // in a PHPDoc type argument - ignore it like equals() does for invariance.
253: $a = TemplateTypeHelper::removeFinalByKeywordOverrides($a);
254: $b = TemplateTypeHelper::removeFinalByKeywordOverrides($b);
255:
256: return $this->covariant() ? $a->isSuperTypeOf($b) : $b->isSuperTypeOf($a);
257: }
258:
259: if ($this->bivariant()) {
260: return IsSuperTypeOfResult::createYes();
261: }
262:
263: throw new ShouldNotHappenException();
264: }
265:
266: public function equals(self $other): bool
267: {
268: return $other->value === $this->value;
269: }
270:
271: public function validPosition(self $other): bool
272: {
273: return $other->value === $this->value
274: || $other->invariant()
275: || $this->bivariant()
276: || $this->static();
277: }
278:
279: public function describe(): string
280: {
281: switch ($this->value) {
282: case self::INVARIANT:
283: return 'invariant';
284: case self::COVARIANT:
285: return 'covariant';
286: case self::CONTRAVARIANT:
287: return 'contravariant';
288: case self::STATIC:
289: return 'static';
290: case self::BIVARIANT:
291: return 'bivariant';
292: }
293:
294: throw new ShouldNotHappenException();
295: }
296:
297: /**
298: * @return GenericTypeNode::VARIANCE_*
299: */
300: public function toPhpDocNodeVariance(): string
301: {
302: switch ($this->value) {
303: case self::INVARIANT:
304: return GenericTypeNode::VARIANCE_INVARIANT;
305: case self::COVARIANT:
306: return GenericTypeNode::VARIANCE_COVARIANT;
307: case self::CONTRAVARIANT:
308: return GenericTypeNode::VARIANCE_CONTRAVARIANT;
309: case self::BIVARIANT:
310: return GenericTypeNode::VARIANCE_BIVARIANT;
311: }
312:
313: throw new ShouldNotHappenException();
314: }
315:
316: }
317: