Skip to content

Commit aa89492

Browse files
committed
Enhance nested generic variance for upper bound of nested generic type checking and add comprehensive tests for generic bounds and variance resolution
1 parent f46c6b8 commit aa89492

2 files changed

Lines changed: 378 additions & 2 deletions

File tree

‎src/Internal/Generics/TemplateManager.php‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1344,13 +1344,29 @@ private static function checkExistingIntersectionVariance(IntersectionTypeNode $
13441344

13451345
private static function checkNestedGenericVariance(GenericTypeNode $existing, GenericTypeNode $expected): bool
13461346
{
1347-
if (! is_a($existing->type->name, $expected->type->name, true)) {
1347+
$expectedClassName = $expected->type->name;
1348+
if (! is_a($existing->type->name, $expectedClassName, true)) {
13481349
return false;
13491350
}
13501351

1352+
$declaredVariances = [];
1353+
if (class_exists($expectedClassName, false) || class_exists($expectedClassName) || interface_exists($expectedClassName)) {
1354+
try {
1355+
$ref = new \ReflectionClass($expectedClassName);
1356+
[, $classVariances] = self::collectHierarchyTemplatesAndVariances($ref);
1357+
$declaredVariances = array_values($classVariances);
1358+
} catch (\Throwable $e) {
1359+
}
1360+
}
1361+
13511362
foreach ($expected->genericTypes as $idx => $expectedInner) {
13521363
$existingInner = $existing->genericTypes[$idx] ?? new IdentifierTypeNode('mixed');
1353-
$innerVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
1364+
$useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
1365+
$declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
1366+
1367+
$innerVariance = ($useSiteVariance !== GenericTypeNode::VARIANCE_INVARIANT)
1368+
? $useSiteVariance
1369+
: $declaredVariance;
13541370

13551371
if (! self::checkVariance($existingInner, $expectedInner, $innerVariance)) {
13561372
return false;
Lines changed: 360 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,360 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\TypeChecking\Generics;
6+
7+
use TypePHP\Exception\TypeError;
8+
9+
// =========================================================================
10+
// Domain Model Fixtures
11+
// =========================================================================
12+
13+
class CovariantBoundModel
14+
{
15+
}
16+
17+
class CovariantBoundUser extends CovariantBoundModel
18+
{
19+
public function __construct(public string $name = 'Alice')
20+
{
21+
}
22+
}
23+
24+
class CovariantBoundAdmin extends CovariantBoundUser
25+
{
26+
}
27+
28+
class CovariantBoundProduct
29+
{
30+
public function __construct(public string $sku = 'SKU-001')
31+
{
32+
}
33+
}
34+
35+
/**
36+
* Covariant Collection: @template-covariant T
37+
*
38+
* @template-covariant T
39+
*/
40+
class CovariantBoundCollection
41+
{
42+
/**
43+
* @var array<int, T>
44+
*/
45+
public array $items = [];
46+
47+
/**
48+
* @param array<int, T> $items
49+
*/
50+
public function __construct(array $items = [])
51+
{
52+
$this->items = $items;
53+
}
54+
55+
public function count(): int
56+
{
57+
return \count($this->items);
58+
}
59+
}
60+
61+
/**
62+
* Invariant Container: standard @template T
63+
*
64+
* @template T
65+
*/
66+
class InvariantBoundBox
67+
{
68+
/**
69+
* @param T $item
70+
*/
71+
public function __construct(public mixed $item)
72+
{
73+
}
74+
}
75+
76+
/**
77+
* Contravariant Consumer: @template-contravariant T
78+
*
79+
* @template-contravariant T
80+
*/
81+
class ContravariantBoundConsumer
82+
{
83+
/**
84+
* @param T $item
85+
*/
86+
public function consume(mixed $item): void
87+
{
88+
}
89+
}
90+
91+
/**
92+
* Bound: Covariant collection of Model
93+
*
94+
* @template T of CovariantBoundCollection<CovariantBoundModel>
95+
*/
96+
class CovariantBatchProcessor
97+
{
98+
/**
99+
* @param T $collection
100+
*/
101+
public function __construct(public mixed $collection)
102+
{
103+
}
104+
105+
public function process(): int
106+
{
107+
return $this->collection->count();
108+
}
109+
}
110+
111+
/**
112+
* Bound: Invariant box of Model
113+
*
114+
* @template T of InvariantBoundBox<CovariantBoundModel>
115+
*/
116+
class InvariantBatchProcessor
117+
{
118+
/**
119+
* @param T $box
120+
*/
121+
public function __construct(public mixed $box)
122+
{
123+
}
124+
}
125+
126+
/**
127+
* Bound: Invariant box with explicit use-site covariance (<covariant Model>)
128+
*
129+
* @template T of InvariantBoundBox<covariant CovariantBoundModel>
130+
*/
131+
class UseSiteCovariantBatchProcessor
132+
{
133+
/**
134+
* @param T $box
135+
*/
136+
public function __construct(public mixed $box)
137+
{
138+
}
139+
}
140+
141+
/**
142+
* Bound: Contravariant consumer of User
143+
*
144+
* @template T of ContravariantBoundConsumer<CovariantBoundUser>
145+
*/
146+
class ContravariantBatchProcessor
147+
{
148+
/**
149+
* @param T $consumer
150+
*/
151+
public function __construct(public mixed $consumer)
152+
{
153+
}
154+
}
155+
156+
/**
157+
* Standalone function with generic bound of covariant generic type
158+
*
159+
* @template T of CovariantBoundCollection<CovariantBoundModel>
160+
*
161+
* @param T $collection
162+
*
163+
* @return T
164+
*/
165+
function processCovariantCollection(mixed $collection): mixed
166+
{
167+
return $collection;
168+
}
169+
170+
/**
171+
* Standalone function with 2-level nested generic bound
172+
*
173+
* @template T of CovariantBoundCollection<CovariantBoundCollection<CovariantBoundModel>>
174+
*
175+
* @param T $nested
176+
*
177+
* @return T
178+
*/
179+
function processNestedCovariantCollection(mixed $nested): mixed
180+
{
181+
return $nested;
182+
}
183+
184+
describe('Generic Bounds of Another Generic Type & Variance Resolution', function () {
185+
describe('1. Declaration-Site Covariance in Generic Bounds (@template T of Collection<Model>)', function () {
186+
test('accepts Collection<User> because Collection is @template-covariant and User extends Model', function () {
187+
$userCollection = new CovariantBoundCollection([
188+
new CovariantBoundUser('Alice'),
189+
new CovariantBoundUser('Bob'),
190+
]);
191+
192+
/** @var CovariantBatchProcessor<CovariantBoundCollection<CovariantBoundUser>> $processor */
193+
$processor = new CovariantBatchProcessor($userCollection);
194+
195+
expect($processor->process())->toBe(2);
196+
});
197+
198+
test('accepts multi-level child class Collection<Admin> (Admin extends User extends Model)', function () {
199+
$adminCollection = new CovariantBoundCollection([
200+
new CovariantBoundAdmin('SuperAdmin'),
201+
]);
202+
203+
/** @var CovariantBatchProcessor<CovariantBoundCollection<CovariantBoundAdmin>> $processor */
204+
$processor = new CovariantBatchProcessor($adminCollection);
205+
206+
expect($processor->process())->toBe(1);
207+
});
208+
209+
test('accepts exact type match Collection<Model>', function () {
210+
$modelCollection = new CovariantBoundCollection();
211+
212+
/** @var CovariantBatchProcessor<CovariantBoundCollection<CovariantBoundModel>> $processor */
213+
$processor = new CovariantBatchProcessor($modelCollection);
214+
215+
expect($processor->process())->toBe(0);
216+
});
217+
218+
test('rejects Collection<Product> because Product does not extend Model', function () {
219+
$productCollection = new CovariantBoundCollection([
220+
new CovariantBoundProduct('SKU-100'),
221+
]);
222+
223+
expect(function () use ($productCollection) {
224+
/** @var CovariantBatchProcessor<CovariantBoundCollection<CovariantBoundProduct>> $processor */
225+
$processor = new CovariantBatchProcessor($productCollection);
226+
})->toThrow(TypeError::class, 'expects');
227+
});
228+
229+
test('rejects non-Collection types (e.g. array) for template bounded by Collection<Model>', function () {
230+
expect(function () {
231+
/** @var CovariantBatchProcessor<array> $processor */
232+
$processor = new CovariantBatchProcessor([]);
233+
})->toThrow(TypeError::class, 'must be an object of type');
234+
});
235+
});
236+
237+
describe('2. Declaration-Site Invariance in Generic Bounds (@template T of InvariantBox<Model>)', function () {
238+
test('accepts exact InvariantBox<Model>', function () {
239+
$model = new CovariantBoundModel();
240+
$box = new InvariantBoundBox($model);
241+
242+
/** @var InvariantBatchProcessor<InvariantBoundBox<CovariantBoundModel>> $processor */
243+
$processor = new InvariantBatchProcessor($box);
244+
245+
expect($processor->box)->toBe($box);
246+
});
247+
248+
test('rejects InvariantBox<User> because InvariantBox is invariant in T even though User extends Model', function () {
249+
$user = new CovariantBoundUser('Alice');
250+
$box = new InvariantBoundBox($user);
251+
252+
expect(function () use ($box) {
253+
/** @var InvariantBatchProcessor<InvariantBoundBox<CovariantBoundUser>> $processor */
254+
$processor = new InvariantBatchProcessor($box);
255+
})->toThrow(TypeError::class, 'expects');
256+
});
257+
});
258+
259+
describe('3. Use-Site Covariance Overriding Invariant Classes (<covariant Model>)', function () {
260+
test('accepts InvariantBox<User> when bound explicitly specifies use-site covariance', function () {
261+
$user = new CovariantBoundUser('Alice');
262+
$box = new InvariantBoundBox($user);
263+
264+
/** @var UseSiteCovariantBatchProcessor<InvariantBoundBox<CovariantBoundUser>> $processor */
265+
$processor = new UseSiteCovariantBatchProcessor($box);
266+
267+
expect($processor->box->item)->toBe($user);
268+
});
269+
270+
test('rejects InvariantBox<Product> under use-site covariance because Product is not a Model', function () {
271+
$product = new CovariantBoundProduct('SKU-999');
272+
$box = new InvariantBoundBox($product);
273+
274+
expect(function () use ($box) {
275+
/** @var UseSiteCovariantBatchProcessor<InvariantBoundBox<CovariantBoundProduct>> $processor */
276+
$processor = new UseSiteCovariantBatchProcessor($box);
277+
})->toThrow(TypeError::class, 'expects');
278+
});
279+
});
280+
281+
describe('4. Declaration-Site Contravariance in Generic Bounds (@template T of Consumer<User>)', function () {
282+
test('accepts Consumer<Model> because Consumer is @template-contravariant and Model is a supertype of User', function () {
283+
$consumer = new ContravariantBoundConsumer();
284+
285+
/** @var ContravariantBatchProcessor<ContravariantBoundConsumer<CovariantBoundModel>> $processor */
286+
$processor = new ContravariantBatchProcessor($consumer);
287+
288+
expect($processor->consumer)->toBe($consumer);
289+
});
290+
291+
test('accepts exact match Consumer<User>', function () {
292+
$consumer = new ContravariantBoundConsumer();
293+
294+
/** @var ContravariantBatchProcessor<ContravariantBoundConsumer<CovariantBoundUser>> $processor */
295+
$processor = new ContravariantBatchProcessor($consumer);
296+
297+
expect($processor->consumer)->toBe($consumer);
298+
});
299+
300+
test('rejects Consumer<Admin> under contravariance because Admin is a subtype (narrower), not a supertype', function () {
301+
$consumer = new ContravariantBoundConsumer();
302+
303+
expect(function () use ($consumer) {
304+
/** @var ContravariantBatchProcessor<ContravariantBoundConsumer<CovariantBoundAdmin>> $processor */
305+
$processor = new ContravariantBatchProcessor($consumer);
306+
})->toThrow(TypeError::class);
307+
});
308+
309+
test('rejects Consumer<Product> because Product is completely unrelated to User', function () {
310+
$consumer = new ContravariantBoundConsumer();
311+
312+
expect(function () use ($consumer) {
313+
/** @var ContravariantBatchProcessor<ContravariantBoundConsumer<CovariantBoundProduct>> $processor */
314+
$processor = new ContravariantBatchProcessor($consumer);
315+
})->toThrow(TypeError::class);
316+
});
317+
});
318+
319+
describe('5. Standalone Generic Functions with Covariant Generic Upper Bounds', function () {
320+
test('infers and accepts Collection<User> on standalone function with @template T of Collection<Model>', function () {
321+
$userCollection = new CovariantBoundCollection([
322+
new CovariantBoundUser('Alice'),
323+
]);
324+
325+
$result = processCovariantCollection($userCollection);
326+
327+
expect($result)->toBe($userCollection);
328+
});
329+
330+
test('rejects Collection<Product> on standalone function with @template T of Collection<Model>', function () {
331+
$productCollection = new CovariantBoundCollection([
332+
new CovariantBoundProduct('SKU-100'),
333+
]);
334+
335+
expect(fn () => processCovariantCollection($productCollection))
336+
->toThrow(TypeError::class, 'expects')
337+
;
338+
});
339+
});
340+
341+
describe('6. Multi-Level Nested Generic Bounds (Collection<Collection<Model>>)', function () {
342+
test('accepts 2-level nested covariant collection Collection<Collection<User>>', function () {
343+
$inner = new CovariantBoundCollection([new CovariantBoundUser('Alice')]);
344+
$nested = new CovariantBoundCollection([$inner]);
345+
346+
$result = processNestedCovariantCollection($nested);
347+
348+
expect($result)->toBe($nested);
349+
});
350+
351+
test('rejects 2-level nested collection when innermost type violates Model bound', function () {
352+
$inner = new CovariantBoundCollection([new CovariantBoundProduct('SKU-100')]);
353+
$nested = new CovariantBoundCollection([$inner]);
354+
355+
expect(fn () => processNestedCovariantCollection($nested))
356+
->toThrow(TypeError::class, 'expects')
357+
;
358+
});
359+
});
360+
});

0 commit comments

Comments
 (0)