Skip to content

Commit 84cc9a4

Browse files
committed
Type new $class(…) on a class-string of a template type bound by a class with consistent templates as an application of that template type
new $class($v) with class-string<K> $class, K of IFoo and IFoo<T> with @phpstan-consistent-templates is K<T>, its arguments inferred from the constructor like those of new Foo($v). A K<T> is a K. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 67af652 commit 84cc9a4

13 files changed

Lines changed: 620 additions & 112 deletions

File tree

‎src/Analyser/ExprHandler/NewHandler.php‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
use PHPStan\Type\Generic\GenericObjectType;
6363
use PHPStan\Type\Generic\GenericStaticType;
6464
use PHPStan\Type\Generic\TemplateType;
65+
use PHPStan\Type\Generic\TemplateTypeApplication;
6566
use PHPStan\Type\Generic\TemplateTypeHelper;
6667
use PHPStan\Type\Generic\TemplateTypeMap;
6768
use PHPStan\Type\Generic\TemplateTypeVariance;
@@ -531,7 +532,24 @@ private function resolveReturnType(MutatingScope $scope, Expr $expr, ?Parameters
531532
if ($classExprType === null) {
532533
throw new ShouldNotHappenException();
533534
}
534-
return $classExprType->getObjectTypeOrClassStringObjectType();
535+
$objectType = $classExprType->getObjectTypeOrClassStringObjectType();
536+
if ($preResolvedAcceptor === null) {
537+
return $objectType;
538+
}
539+
540+
// new $class(…) on a class-string<TColl>: TColl<…> with the arguments the constructor infers
541+
$application = TemplateTypeApplication::ofInstantiation($objectType);
542+
if ($application === null) {
543+
return $objectType;
544+
}
545+
546+
$frame = $allowUnresolved ? $scope->getCurrentTemplateArgumentFrame() : null;
547+
$arguments = TypeTraverser::map($application->getApplication(), new GenericTypeTemplateTraverser($preResolvedAcceptor->getResolvedTemplateTypeMap(), $expr, $frame, $allowUnresolved));
548+
if (!$arguments instanceof GenericStaticType) {
549+
return $objectType;
550+
}
551+
552+
return new TemplateTypeApplication($application->getConstructor(), $arguments, true);
535553
}
536554

537555
/**

‎src/Type/Generic/TemplateTypeApplication.php‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPStan\Reflection\ConsistentTemplatesHelper;
1010
use PHPStan\Reflection\ExtendedMethodReflection;
1111
use PHPStan\Reflection\ExtendedPropertyReflection;
12+
use PHPStan\Reflection\ReflectionProviderStaticAccessor;
1213
use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
1314
use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
1415
use PHPStan\Turbo\ShadowedByTurboExtension;
@@ -24,6 +25,7 @@
2425
use PHPStan\Type\VerbosityLevel;
2526
use function array_map;
2627
use function array_merge;
28+
use function count;
2729
use function implode;
2830
use function sprintf;
2931

@@ -84,6 +86,38 @@ public static function ofCalledOnType(Type $calledOnType, StaticType $static): ?
8486
return new self($calledOnType, $static, true);
8587
}
8688

89+
/**
90+
* `new $class(…)` on a class-string<TColl> is a TColl<…> when the class TColl is bound by
91+
* has `@phpstan-consistent-templates`: this application of TColl to that class's own
92+
* template types, for the caller to resolve from the constructor's arguments.
93+
*/
94+
public static function ofInstantiation(Type $objectType): ?self
95+
{
96+
if (!$objectType instanceof TemplateType) {
97+
return null;
98+
}
99+
100+
$classReflections = $objectType->getBound()->getObjectClassReflections();
101+
if (count($classReflections) !== 1) {
102+
return null;
103+
}
104+
105+
$classReflection = ReflectionProviderStaticAccessor::getInstance()->getClass($classReflections[0]->getName());
106+
if (!$classReflection->isGeneric()) {
107+
return null;
108+
}
109+
110+
if ((new ConsistentTemplatesHelper())->findConsistentTemplatesClass($classReflection) === null) {
111+
return null;
112+
}
113+
114+
return new self(
115+
$objectType,
116+
new GenericStaticType($classReflection, $classReflection->typeMapToList($classReflection->getTemplateTypeMap()), null, []),
117+
true,
118+
);
119+
}
120+
87121
public function isConsistent(): bool
88122
{
89123
return $this->consistent;
@@ -189,6 +223,35 @@ public function accepts(Type $type, bool $strictTypes): AcceptsResult
189223
return $accepts;
190224
}
191225

226+
public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult
227+
{
228+
// a TColl<X> is a TColl
229+
if (!$this->isResolvable() && $otherType->isSuperTypeOf($this->constructor)->yes()) {
230+
return IsSuperTypeOfResult::createYes();
231+
}
232+
233+
$result = $this->resolve();
234+
if ($result instanceof CompoundType) {
235+
return $result->isSubTypeOf($otherType);
236+
}
237+
238+
return $otherType->isSuperTypeOf($result);
239+
}
240+
241+
public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult
242+
{
243+
if (!$this->isResolvable() && $acceptingType->accepts($this->constructor, $strictTypes)->yes()) {
244+
return AcceptsResult::createYes();
245+
}
246+
247+
$result = $this->resolve();
248+
if ($result instanceof CompoundType) {
249+
return $result->isAcceptedBy($acceptingType, $strictTypes);
250+
}
251+
252+
return $acceptingType->accepts($result, $strictTypes);
253+
}
254+
192255
public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
193256
{
194257
// the received object is the class the constructor stands for,
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php // lint >= 8.1
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug12646;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
class Promise {
10+
public function doPromise(): string {
11+
return "promise";
12+
}
13+
}
14+
15+
interface Result {}
16+
class ResultA implements Result {
17+
public function doA(): string {
18+
return "a";
19+
}
20+
}
21+
22+
/**
23+
* @template TypeConcurrent of bool
24+
* @phpstan-consistent-templates
25+
*/
26+
abstract class Communicator
27+
{
28+
/** @param TypeConcurrent $concurrent */
29+
public function __construct(readonly private bool $concurrent) {}
30+
/**
31+
* @template TypeResult of Result
32+
* @param class-string<TypeResult> $resultClass
33+
* @return (TypeConcurrent is true ? Promise : TypeResult)
34+
*/
35+
protected function getResultOrPromise(string $resultClass): Result|Promise
36+
{
37+
return $this->concurrent ? new Promise() : new $resultClass();
38+
}
39+
}
40+
41+
/**
42+
* @template TypeConcurrent of bool
43+
* @extends Communicator<TypeConcurrent>
44+
*/
45+
class ACommunicator extends Communicator
46+
{
47+
/** @param TypeConcurrent $concurrent */
48+
public function __construct(bool $concurrent)
49+
{
50+
parent::__construct($concurrent);
51+
}
52+
/** @return (TypeConcurrent is true ? Promise : ResultA) */
53+
public function findResult(): ResultA|Promise
54+
{
55+
return $this->getResultOrPromise(ResultA::class);
56+
}
57+
}
58+
59+
/**
60+
* @template TypeCommunicator of Communicator
61+
* @template TypeConcurrent of bool
62+
* @param class-string<TypeCommunicator> $communicatorClass
63+
* @param TypeConcurrent $concurrent
64+
* @return TypeCommunicator<TypeConcurrent>
65+
*/
66+
function communicatorFactory(string $communicatorClass, bool $concurrent): Communicator
67+
{
68+
return new $communicatorClass($concurrent);
69+
}
70+
71+
(new ACommunicator(false))->findResult()->doA();
72+
(new ACommunicator(true))->findResult()->doPromise();
73+
74+
// [QUESTION] Why dont these work, if above works?
75+
assertType('Bug12646\\ACommunicator<false>', communicatorFactory(ACommunicator::class, false));
76+
assertType('Bug12646\\ResultA', communicatorFactory(ACommunicator::class, false)->findResult());
77+
communicatorFactory(ACommunicator::class, false)->findResult()->doA();
78+
assertType('Bug12646\\Promise', communicatorFactory(ACommunicator::class, true)->findResult());
79+
communicatorFactory(ACommunicator::class, true)->findResult()->doPromise();
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug4971;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template T
9+
* @phpstan-consistent-templates
10+
*/
11+
interface IFoo
12+
{
13+
/** @param T $v */
14+
public function __construct($v);
15+
}
16+
17+
/**
18+
* @template T
19+
* @implements IFoo<T>
20+
*/
21+
class Foo implements IFoo
22+
{
23+
/** @var T */
24+
private $v;
25+
/**
26+
* @param T $v
27+
*/
28+
public function __construct($v)
29+
{
30+
$this->v = $v;
31+
}
32+
}
33+
34+
/**
35+
* @template T
36+
* @template K of IFoo
37+
* @param T $v
38+
* @param class-string<K> $class
39+
* @return K
40+
*/
41+
function make1($v, string $class)
42+
{
43+
return new $class($v);
44+
}
45+
46+
/**
47+
* @template T
48+
* @template K of IFoo
49+
* @param T $v
50+
* @param class-string<K> $class
51+
* @return K<T>
52+
*/
53+
function make2($v, string $class)
54+
{
55+
return new $class($v);
56+
}
57+
58+
$obj1 = make1(1, Foo::class);
59+
assertType('Bug4971\\Foo', $obj1);
60+
61+
$obj2 = make2(1, Foo::class); // I want to type Foo<int>
62+
assertType('Bug4971\\Foo<int>', $obj2);

‎tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,21 @@ public function testBug13394(): void
672672
$this->analyse([__DIR__ . '/data/bug-13394.php'], []);
673673
}
674674

675+
public function testBug4971(): void
676+
{
677+
$this->checkNullables = true;
678+
$this->checkExplicitMixed = true;
679+
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-4971.php'], []);
680+
}
681+
682+
#[RequiresPhp('>= 8.1.0')]
683+
public function testBug12646(): void
684+
{
685+
$this->checkNullables = true;
686+
$this->checkExplicitMixed = true;
687+
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-12646.php'], []);
688+
}
689+
675690
#[RequiresPhp('>= 8.1.0')]
676691
public function testBug15873(): void
677692
{

‎tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4732,6 +4732,15 @@ public function testBug13400(): void
47324732
$this->analyse([__DIR__ . '/data/bug-13400.php'], []);
47334733
}
47344734

4735+
#[RequiresPhp('>= 8.1.0')]
4736+
public function testBug12646(): void
4737+
{
4738+
$this->checkThisOnly = false;
4739+
$this->checkNullables = true;
4740+
$this->checkUnionTypes = true;
4741+
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-12646.php'], []);
4742+
}
4743+
47354744
public function testBug14872(): void
47364745
{
47374746
$this->checkThisOnly = false;
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Type\Generic;
4+
5+
use PHPStan\Testing\PHPStanTestCase;
6+
use PHPStan\Type\IntegerType;
7+
use PHPStan\Type\NullType;
8+
use PHPStan\Type\ObjectType;
9+
use PHPStan\Type\Test\TemplateTypeApplication\Coll;
10+
use PHPStan\Type\Test\TemplateTypeApplication\Vec;
11+
use PHPStan\Type\TypeCombinator;
12+
13+
class TemplateTypeApplicationTest extends PHPStanTestCase
14+
{
15+
16+
/**
17+
* @return array{TemplateType, TemplateTypeApplication} K of Coll, and K<int>
18+
*/
19+
private static function createApplication(): array
20+
{
21+
$constructor = TemplateTypeFactory::create(
22+
TemplateTypeScope::createWithFunction('f'),
23+
'K',
24+
new ObjectType(Coll::class),
25+
TemplateTypeVariance::createInvariant(),
26+
);
27+
28+
return [
29+
$constructor,
30+
new TemplateTypeApplication(
31+
$constructor,
32+
new GenericStaticType(self::createReflectionProvider()->getClass(Coll::class), [new IntegerType()], null, []),
33+
true,
34+
),
35+
];
36+
}
37+
38+
public function testIsSubTypeOf(): void
39+
{
40+
[$constructor, $application] = self::createApplication();
41+
42+
// a K<int> is a K, which a Coll<int> is only maybe
43+
$this->assertTrue(TypeCombinator::union($constructor, new NullType())->isSuperTypeOf($application)->yes());
44+
45+
// a K<int> is a Coll<int>, which is a Vec<int> only maybe
46+
$this->assertTrue((new GenericObjectType(Vec::class, [new IntegerType()]))->isSuperTypeOf($application)->maybe());
47+
}
48+
49+
public function testIsAcceptedBy(): void
50+
{
51+
[$constructor, $application] = self::createApplication();
52+
53+
// a K<int> is a K
54+
$this->assertTrue(TypeCombinator::union($constructor, new NullType())->accepts($application, true)->yes());
55+
56+
// a K<int> is a Coll<int>, which is a Vec<int> only maybe
57+
$this->assertTrue((new GenericObjectType(Vec::class, [new IntegerType()]))->accepts($application, true)->maybe());
58+
}
59+
60+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace PHPStan\Type\Test\TemplateTypeApplication;
4+
5+
/**
6+
* @template-covariant T
7+
* @phpstan-consistent-templates
8+
*/
9+
interface Coll {}
10+
11+
/**
12+
* @template-covariant T
13+
* @implements Coll<T>
14+
*/
15+
final class Vec implements Coll {}

0 commit comments

Comments
 (0)