Skip to content

Commit 3030903

Browse files
authored
Bug fixes on Generics (#78)
* TDD test for replication of problem identified in github issue * Enhance BoxConsumer with generic methods and type validation tests and implement fix on the bug
1 parent e0b1371 commit 3030903

9 files changed

Lines changed: 252 additions & 1 deletion

File tree

‎src/Internal/Checker/ParamChecker.php‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@
1818
use TypePHP\Internal\Diagnostic\ErrorFactory;
1919
use TypePHP\Internal\Diagnostic\ErrorMessage;
2020
use TypePHP\Internal\Diagnostic\TypeFormatter;
21+
use TypePHP\Internal\Docblock\DocblockExtractor;
2122
use TypePHP\Internal\Docblock\DocblockParser;
2223
use TypePHP\Internal\Generics\TemplateManager;
2324
use TypePHP\Internal\Generics\TemplateSubstitutor;
2425
use TypePHP\Internal\Resolver\HierarchyResolver;
2526
use TypePHP\Internal\Resolver\SpecialTypeResolver;
2627
use TypePHP\Internal\Util\ClassNameValidator;
2728
use TypePHP\Internal\Util\Config;
29+
use TypePHP\Internal\Util\StubManager;
2830
use TypePHP\Internal\Validator\TypeValidatorRegistry;
2931

3032
/**
@@ -51,13 +53,21 @@ final class ParamChecker
5153
*/
5254
private static array $baseTypeCache = [];
5355

56+
/**
57+
* Cache for declared class template names by class FQCN.
58+
*
59+
* @var array<string, list<string>>
60+
*/
61+
private static array $classDeclaredTemplateNamesCache = [];
62+
5463
/**
5564
* Resets internal caches. Useful for test isolation.
5665
*/
5766
public static function reset(): void
5867
{
5968
self::$effectiveFunctionCache = [];
6069
self::$noParamContractCache = [];
70+
self::$classDeclaredTemplateNamesCache = [];
6171
ClassNameValidator::reset();
6272
self::$baseTypeCache = [];
6373
}
@@ -803,6 +813,25 @@ private static function inferGenericObjectNode(
803813
return;
804814
}
805815

816+
$targetClassFqcn = SpecialTypeResolver::resolveFqcn($typeNode->type->name, new \ReflectionClass($value));
817+
$targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null;
818+
819+
if ($targetTemplateNames === null) {
820+
$targetTemplateNames = [];
821+
if (class_exists($targetClassFqcn, false) || class_exists($targetClassFqcn) || interface_exists($targetClassFqcn) || trait_exists($targetClassFqcn)) {
822+
try {
823+
$targetRef = new \ReflectionClass($targetClassFqcn);
824+
$targetDoc = StubManager::getClassDoc($targetClassFqcn) ?? $targetRef->getDocComment();
825+
if ($targetDoc !== false && $targetDoc !== null) {
826+
$targetPhpDocNode = DocblockExtractor::parseDocString($targetDoc);
827+
$targetTemplateNames = array_keys(DocblockExtractor::extractTemplates($targetPhpDocNode));
828+
}
829+
} catch (\Throwable $e) {
830+
}
831+
}
832+
self::$classDeclaredTemplateNamesCache[$targetClassFqcn] = $targetTemplateNames;
833+
}
834+
806835
$instanceBoundTypes = array_values($boundOnInstance);
807836

808837
foreach ($typeNode->genericTypes as $idx => $gtNode) {
@@ -812,7 +841,14 @@ private static function inferGenericObjectNode(
812841
$targetObj = $isClassLevel ? $thisObj : null;
813842

814843
if (! TemplateManager::isBound($effectiveFunction, $targetObj, $tName)) {
815-
$inferredCandidate = $instanceBoundTypes[$idx] ?? null;
844+
$targetTemplateName = $targetTemplateNames[$idx] ?? null;
845+
$inferredCandidate = null;
846+
847+
if ($targetTemplateName !== null && isset($boundOnInstance[$targetTemplateName])) {
848+
$inferredCandidate = $boundOnInstance[$targetTemplateName];
849+
} elseif (isset($instanceBoundTypes[$idx])) {
850+
$inferredCandidate = $instanceBoundTypes[$idx];
851+
}
816852

817853
if ($inferredCandidate !== null) {
818854
$templateTag = $templates[$tName];
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
/**
8+
* Notice the extra leading template TSelf that shifts T and U by +1
9+
*
10+
* @template TSelf of AbstractBox
11+
* @template T of ItemBase
12+
* @template U of ItemBase
13+
*
14+
* @implements BoxInterface<T, U>
15+
*/
16+
abstract class AbstractBox implements BoxInterface
17+
{
18+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
final class BoxConsumer
8+
{
9+
/**
10+
* @template T of ItemBase
11+
* @template U of ItemBase
12+
*
13+
* @param BoxInterface<T, U> $box
14+
*/
15+
public function __construct(public readonly BoxInterface $box)
16+
{
17+
}
18+
19+
/**
20+
* @template T of ItemBase
21+
* @template U of ItemBase
22+
*
23+
* @param BoxInterface<T, U> $box
24+
*
25+
* @return T
26+
*/
27+
public function extractFirst(BoxInterface $box): ItemBase
28+
{
29+
return new ItemA();
30+
}
31+
32+
/**
33+
* @template T of ItemBase
34+
* @template U of ItemBase
35+
*
36+
* @param BoxInterface<T, U> $box
37+
*
38+
* @return U
39+
*/
40+
public function extractSecond(BoxInterface $box): ItemBase
41+
{
42+
return new ItemB();
43+
}
44+
45+
/**
46+
* Method returning invalid type (returns ItemB when T is ItemA)
47+
*
48+
* @template T of ItemBase
49+
* @template U of ItemBase
50+
*
51+
* @param BoxInterface<T, U> $box
52+
*
53+
* @return T
54+
*/
55+
public function extractBad(BoxInterface $box): ItemBase
56+
{
57+
return new ItemB();
58+
}
59+
60+
/**
61+
* @template T of ItemBase
62+
* @template U of ItemBase
63+
*
64+
* @param BoxInterface<T, U> $box
65+
*
66+
* @return BoxInterface<T, U>
67+
*/
68+
public function passThrough(BoxInterface $box): BoxInterface
69+
{
70+
return $box;
71+
}
72+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
/**
8+
* @template T of ItemBase
9+
* @template U of ItemBase
10+
*/
11+
interface BoxInterface
12+
{
13+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
/**
8+
* @extends AbstractBox<ConcreteBox, ItemA, ItemB>
9+
*/
10+
final class ConcreteBox extends AbstractBox
11+
{
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
final class ItemA implements ItemBase
8+
{
9+
public function __construct(public string $name = 'A')
10+
{
11+
}
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
final class ItemB implements ItemBase
8+
{
9+
public function __construct(public string $name = 'B')
10+
{
11+
}
12+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\Fixtures\Forwarding;
6+
7+
interface ItemBase
8+
{
9+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\TypeChecking\Generics;
6+
7+
use TypePHP\Exception\TypeError;
8+
use TypePHP\Tests\Fixtures\Forwarding\BoxConsumer;
9+
use TypePHP\Tests\Fixtures\Forwarding\ConcreteBox;
10+
use TypePHP\Tests\Fixtures\Forwarding\ItemA;
11+
use TypePHP\Tests\Fixtures\Forwarding\ItemB;
12+
use TypePHP\TypePHP;
13+
14+
describe('Generic Template Forwarding Across Abstract Hierarchies with Shifted Template Indexes', function () {
15+
test('infers method template arguments T and U from implementing class when abstract parent has extra leading template', function () {
16+
$concreteBox = new ConcreteBox();
17+
$consumer = new BoxConsumer($concreteBox);
18+
19+
expect($consumer->box)->toBe($concreteBox);
20+
});
21+
22+
test('reifies bound generic types on concrete box instance matching both interface and class templates', function () {
23+
$concreteBox = new ConcreteBox();
24+
25+
expect(TypePHP::getGenericType($concreteBox, 'T'))->toBe(ItemA::class)
26+
->and(TypePHP::getGenericType($concreteBox, 'U'))->toBe(ItemB::class)
27+
;
28+
});
29+
30+
describe('Return Type Contracts with Forwarded Generics', function () {
31+
test('validates @return T correctly uses inferred ItemA', function () {
32+
$concreteBox = new ConcreteBox();
33+
$consumer = new BoxConsumer($concreteBox);
34+
35+
$first = $consumer->extractFirst($concreteBox);
36+
expect($first)->toBeInstanceOf(ItemA::class);
37+
});
38+
39+
test('validates @return U correctly uses inferred ItemB', function () {
40+
$concreteBox = new ConcreteBox();
41+
$consumer = new BoxConsumer($concreteBox);
42+
43+
$second = $consumer->extractSecond($concreteBox);
44+
expect($second)->toBeInstanceOf(ItemB::class);
45+
});
46+
47+
test('throws TypeError when @return T returns ItemB instead of inferred ItemA', function () {
48+
$concreteBox = new ConcreteBox();
49+
$consumer = new BoxConsumer($concreteBox);
50+
51+
expect(fn () => $consumer->extractBad($concreteBox))
52+
->toThrow(
53+
TypeError::class,
54+
'Return value must be of type ' . ItemA::class . ', ' . ItemB::class . ' returned'
55+
)
56+
;
57+
});
58+
59+
test('validates @return BoxInterface<T, U> returning the forwarded concrete instance', function () {
60+
$concreteBox = new ConcreteBox();
61+
$consumer = new BoxConsumer($concreteBox);
62+
63+
$result = $consumer->passThrough($concreteBox);
64+
expect($result)->toBe($concreteBox);
65+
});
66+
});
67+
});

0 commit comments

Comments
 (0)