1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Generic;
4:
5: use PHPStan\Turbo\ShadowedByTurboExtension;
6: use PHPStan\Type\NeverType;
7: use PHPStan\Type\Type;
8: use PHPStan\Type\TypeCombinator;
9: use PHPStan\Type\TypeUtils;
10: use function array_key_exists;
11: use function count;
12:
13: /**
14: * Maps template type parameter names to their resolved types.
15: *
16: * This is the core data structure for PHPStan's generics support. When a class declares
17: * `@template T`, `@template U of object`, etc., the TemplateTypeMap tracks what concrete
18: * types T and U resolve to in a particular context.
19: *
20: * Two kinds of type bindings are tracked:
21: * - **types**: The concrete type inferred or declared for each template. During inference
22: * these are lower bounds: `T[]` receiving `int[]` means T :> int.
23: * - **upperBoundTypes**: Types inferred from contravariant positions, such as the parameter
24: * of `callable(T): void` receiving `callable(int): void`, which means T <: int.
25: * A template is resolved to its lower bound when it has one, otherwise to its upper bound.
26: *
27: * TemplateTypeMap supports set operations (union, intersect, benevolentUnion) that combine
28: * maps from different code paths: union() joins the lower bounds and meets the upper
29: * bounds, intersect() the other way around. resolveToBounds() replaces unresolved template
30: * types with their declared bounds.
31: *
32: * Common usage: ParametersAcceptor::getTemplateTypeMap() returns the template declarations,
33: * and ParametersAcceptor::getResolvedTemplateTypeMap() returns inferred concrete types.
34: * Type::inferTemplateTypes() produces a TemplateTypeMap from a concrete type.
35: *
36: * @api
37: */
38: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateTypeMap.cpp')]
39: final class TemplateTypeMap
40: {
41:
42: private static ?TemplateTypeMap $empty = null;
43:
44: private ?TemplateTypeMap $resolvedToBounds = null;
45:
46: /** @var array<string, Type> */
47: private array $upperBoundTypes;
48:
49: /**
50: * @api
51: * @param array<string, Type> $types Concrete types for each template parameter, lower bounds during inference
52: * @param array<string, Type> $lowerBoundTypes Upper bounds, inferred from contravariant positions (the name is kept for backward compatibility)
53: */
54: public function __construct(private array $types, array $lowerBoundTypes = [])
55: {
56: $this->upperBoundTypes = $lowerBoundTypes;
57: }
58:
59: /**
60: * The map inferred from a type in a contravariant position, such as the parameter of a
61: * callable: its lower bounds become upper bounds and vice versa.
62: */
63: public function swapBounds(): self
64: {
65: return new self($this->upperBoundTypes, $this->types);
66: }
67:
68: /** @deprecated Use swapBounds() */
69: public function convertToLowerBoundTypes(): self
70: {
71: return $this->swapBounds();
72: }
73:
74: public static function createEmpty(): self
75: {
76: $empty = self::$empty;
77:
78: if ($empty !== null) {
79: return $empty;
80: }
81:
82: $empty = new self([], []);
83: self::$empty = $empty;
84:
85: return $empty;
86: }
87:
88: public function isEmpty(): bool
89: {
90: return $this->count() === 0;
91: }
92:
93: public function count(): int
94: {
95: return count($this->types + $this->upperBoundTypes);
96: }
97:
98: /** @return array<string, Type> */
99: public function getTypes(): array
100: {
101: $types = $this->types;
102: foreach ($this->upperBoundTypes as $name => $type) {
103: if (array_key_exists($name, $types)) {
104: continue;
105: }
106:
107: $types[$name] = $type;
108: }
109:
110: return $types;
111: }
112:
113: /**
114: * The upper bounds alone, including those of templates that also have a lower bound,
115: * which getTypes() prefers.
116: *
117: * @return array<string, Type>
118: */
119: public function getUpperBoundTypes(): array
120: {
121: return $this->upperBoundTypes;
122: }
123:
124: public function hasType(string $name): bool
125: {
126: return array_key_exists($name, $this->getTypes());
127: }
128:
129: public function getType(string $name): ?Type
130: {
131: return $this->getTypes()[$name] ?? null;
132: }
133:
134: public function unsetType(string $name): self
135: {
136: if (!$this->hasType($name)) {
137: return $this;
138: }
139:
140: $types = $this->types;
141: $upperBoundTypes = $this->upperBoundTypes;
142:
143: unset($types[$name]);
144: unset($upperBoundTypes[$name]);
145:
146: if (count($types) === 0 && count($upperBoundTypes) === 0) {
147: return self::createEmpty();
148: }
149:
150: return new self($types, $upperBoundTypes);
151: }
152:
153: public function union(self $other): self
154: {
155: $result = $this->types;
156:
157: foreach ($other->types as $name => $type) {
158: if (isset($result[$name])) {
159: $result[$name] = self::combine($result[$name], $type, static fn (Type $a, Type $b): Type => TypeCombinator::union($a, $b));
160: } else {
161: $result[$name] = $type;
162: }
163: }
164:
165: $resultUpperBoundTypes = $this->upperBoundTypes;
166: foreach ($other->upperBoundTypes as $name => $type) {
167: if (isset($resultUpperBoundTypes[$name])) {
168: $intersection = TypeCombinator::intersect($resultUpperBoundTypes[$name], $type);
169: if ($intersection instanceof NeverType) {
170: // conflicting upper bounds: the first one wins, so that the argument
171: // checked against it reports the conflict in terms of real types
172: continue;
173: }
174: $resultUpperBoundTypes[$name] = $intersection;
175: } else {
176: $resultUpperBoundTypes[$name] = $type;
177: }
178: }
179:
180: return new self($result, $resultUpperBoundTypes);
181: }
182:
183: public function benevolentUnion(self $other): self
184: {
185: $result = $this->types;
186:
187: foreach ($other->types as $name => $type) {
188: if (isset($result[$name])) {
189: $result[$name] = self::combine($result[$name], $type, static fn (Type $a, Type $b): Type => TypeUtils::toBenevolentUnion(TypeCombinator::union($a, $b)));
190: } else {
191: $result[$name] = $type;
192: }
193: }
194:
195: $resultUpperBoundTypes = $this->upperBoundTypes;
196: foreach ($other->upperBoundTypes as $name => $type) {
197: if (isset($resultUpperBoundTypes[$name])) {
198: $intersection = TypeCombinator::intersect($resultUpperBoundTypes[$name], $type);
199: if ($intersection instanceof NeverType) {
200: // conflicting upper bounds: the first one wins, so that the argument
201: // checked against it reports the conflict in terms of real types
202: continue;
203: }
204: $resultUpperBoundTypes[$name] = $intersection;
205: } else {
206: $resultUpperBoundTypes[$name] = $type;
207: }
208: }
209:
210: return new self($result, $resultUpperBoundTypes);
211: }
212:
213: /**
214: * A template left unresolved on purpose by one occurrence of the parameter type carries
215: * no type at all, so any type another occurrence did infer wins over it outright.
216: *
217: * @param callable(Type, Type): Type $cb
218: */
219: private static function combine(Type $a, Type $b, callable $cb): Type
220: {
221: if ($a instanceof AbsorbedTemplateArgumentType) {
222: return $b;
223: }
224: if ($b instanceof AbsorbedTemplateArgumentType) {
225: return $a;
226: }
227:
228: return $cb($a, $b);
229: }
230:
231: public function intersect(self $other): self
232: {
233: $result = $this->types;
234:
235: foreach ($other->types as $name => $type) {
236: if (isset($result[$name])) {
237: $result[$name] = TypeCombinator::intersect($result[$name], $type);
238: } else {
239: $result[$name] = $type;
240: }
241: }
242:
243: $resultUpperBoundTypes = $this->upperBoundTypes;
244: foreach ($other->upperBoundTypes as $name => $type) {
245: if (isset($resultUpperBoundTypes[$name])) {
246: $resultUpperBoundTypes[$name] = TypeCombinator::union($resultUpperBoundTypes[$name], $type);
247: } else {
248: $resultUpperBoundTypes[$name] = $type;
249: }
250: }
251:
252: return new self($result, $resultUpperBoundTypes);
253: }
254:
255: /** @param callable(string,Type):Type $cb */
256: public function map(callable $cb): self
257: {
258: $types = [];
259: foreach ($this->getTypes() as $name => $type) {
260: $types[$name] = $cb($name, $type);
261: }
262:
263: return new self($types);
264: }
265:
266: /**
267: * Replaces unresolved TemplateType values with their declared bounds (or defaults).
268: */
269: public function resolveToBounds(): self
270: {
271: if ($this->resolvedToBounds !== null) {
272: return $this->resolvedToBounds;
273: }
274: return $this->resolvedToBounds = $this->map(static fn (string $name, Type $type): Type => TemplateTypeHelper::resolveToDefaults($type));
275: }
276:
277: }
278: