Skip to content

Commit 671e1ed

Browse files
committed
Infer from each branch of an undecided conditional parameter type
A conditional parameter type its arguments do not decide is either branch, so the templates are what the branches the argument may be infer. `($mode is 'list' ? list<T> : T)` given `array{1}` with an unknown $mode is T = `1|array{1}` instead of 1, which the union of the branches gave by letting `list<T>` take the whole argument. What a branch on a template infers must take that branch, so `(T is int ? list<T> : T)` given `array{'a'}` is T = `array{'a'}`. A branch without templates that takes the argument still tells nothing about the other one, as for `T|null`. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 416fce9 commit 671e1ed

4 files changed

Lines changed: 143 additions & 8 deletions

File tree

‎src/Reflection/ConditionalParameterTypeInference.php‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,20 @@ public function resolve(string $paramName, Type $paramType, array $passedArgs, T
126126
return $paramType;
127127
}
128128

129-
$type = ConditionalTypeForParameter::resolveInType(
130-
$paramType,
131-
static fn (string $parameterName): ?Type => $passedArgs[$parameterName] ?? null,
132-
);
129+
// only the conditions the arguments decide; an undecided one stays, so each of its
130+
// branches infers on its own (see inferTemplateTypes())
131+
$type = TypeTraverser::map($paramType, static function (Type $type, callable $traverse) use ($passedArgs): Type {
132+
if (!$type instanceof ConditionalTypeForParameter || !array_key_exists($type->getParameterName(), $passedArgs)) {
133+
return $traverse($type);
134+
}
135+
136+
$isSuperType = $type->getTarget()->isSuperTypeOf($passedArgs[$type->getParameterName()]);
137+
if ($isSuperType->maybe()) {
138+
return $traverse($type);
139+
}
140+
141+
return $traverse($isSuperType->yes() !== $type->isNegated() ? $type->getIf() : $type->getElse());
142+
});
133143

134144
$known = [];
135145
foreach ($this->conditionTemplateTypes[$paramName] ?? [] as $name) {
@@ -182,7 +192,58 @@ public static function inferFromDecided(Type $decidedType, Type $argType, Templa
182192
$keptMap = $keptMap->unsetType($reference->getType()->getName());
183193
}
184194

185-
return $decidedType->inferTemplateTypes($argType)->union($keptMap);
195+
return self::inferTemplateTypes($decidedType, $argType)->union($keptMap);
196+
}
197+
198+
/**
199+
* Infers from a parameter type whose top-level conditions may be undecided. An undecided
200+
* condition is either branch, so the templates are what the branches the argument may be
201+
* infer: `($mode is 'list' ? list<T> : T)` given `array{1}` is T = `1|array{1}`, where
202+
* the union of the branches would let `list<T>` take the whole argument. A branch without
203+
* templates that takes the argument tells nothing about the other one, as for `T|null`.
204+
*/
205+
public static function inferTemplateTypes(Type $type, Type $argType): TemplateTypeMap
206+
{
207+
if ($type instanceof ConditionalType && $type->isResolvable()) {
208+
return self::inferTemplateTypes($type->resolve(), $argType);
209+
}
210+
if (!$type instanceof ConditionalType && !$type instanceof ConditionalTypeForParameter) {
211+
return $type->inferTemplateTypes($argType);
212+
}
213+
214+
$branches = [$type->getIf(), $type->getElse()];
215+
foreach ($branches as $branch) {
216+
if (!$branch->hasTemplateOrLateResolvableType() && $branch->isSuperTypeOf($argType)->yes()) {
217+
return TemplateTypeMap::createEmpty();
218+
}
219+
}
220+
221+
$map = null;
222+
foreach ($branches as $i => $branch) {
223+
if ($branch->isSuperTypeOf($argType)->no()) {
224+
continue;
225+
}
226+
227+
$branchMap = self::inferTemplateTypes($branch, $argType);
228+
// what a branch infers must take that branch: `(T is int ? list<T> : T)` given
229+
// `array{'a'}` does not make T `'a'`, which is no int
230+
if ($type instanceof ConditionalType && !self::takesBranch($type, $i === 0, $branchMap)) {
231+
continue;
232+
}
233+
234+
$map = $map === null ? $branchMap : $map->union($branchMap);
235+
}
236+
237+
// the argument is no branch, so it is reported against what the union of them infers
238+
return $map ?? $type->inferTemplateTypes($argType);
239+
}
240+
241+
private static function takesBranch(ConditionalType $type, bool $if, TemplateTypeMap $branchMap): bool
242+
{
243+
$isSuperType = $type->getTarget()->isSuperTypeOf(self::resolveKnown($type->getSubject(), $branchMap));
244+
$conditionHolds = $if !== $type->isNegated();
245+
246+
return $conditionHolds ? !$isSuperType->no() : !$isSuperType->yes();
186247
}
187248

188249
private static function resolveKnown(Type $type, TemplateTypeMap $known): Type

‎src/Reflection/GenericParametersAcceptorResolver.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
257257
$paramName = $param->getName();
258258
$passedArgs['$' . $paramName] = $argType;
259259
$paramType = $predicateTypeMap === null ? $param->getType() : self::resolvePredicateTemplateTypes($param->getType(), $predicateTypeMap);
260-
$paramTypeMap = $paramType->inferTemplateTypes($argType);
260+
$paramTypeMap = $conditionalInference === null ? $paramType->inferTemplateTypes($argType) : ConditionalParameterTypeInference::inferTemplateTypes($paramType, $argType);
261261
if ($conditionalInference !== null) {
262262
$decidedParamType = $conditionalInference->resolve($paramName, $paramType, $passedArgs, $typeMap);
263263
if ($decidedParamType !== $paramType) {

‎tests/PHPStan/Analyser/nsrt/conditional-parameter-type-inference.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ function test(): void
8181
assertType('array{\'v\'}', chainedAfter(['v'], 5, 1));
8282
assertType('\'v\'', chainedAfter(['v'], ['u'], 'a'));
8383

84-
// T is inferred only from the conditional on T itself, so both branches still infer it
85-
assertType('1', onlyThroughItself([1]));
84+
// T is inferred only from the conditional on T itself: T = 1 takes the list<T> branch
85+
// and T = array{1} the other one, while T = 'a' cannot take the list<T> branch
86+
assertType('1|array{1}', onlyThroughItself([1]));
87+
assertType('array{\'a\'}', onlyThroughItself(['a']));
8688
assertType('\'a\'', onlyThroughItself('a'));
8789
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
namespace ConditionalParameterTypeUndecided;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template T
9+
* @param ($mode is 'list' ? list<T> : T) $v
10+
* @return T
11+
*/
12+
function listOrValue(string $mode, $v)
13+
{
14+
}
15+
16+
/**
17+
* @template T
18+
* @param ($wrap is true ? list<T> : T) $v
19+
* @return T
20+
*/
21+
function wrapped($v, bool $wrap = false)
22+
{
23+
}
24+
25+
/**
26+
* @template T
27+
* @param ($mode is 'value' ? T : null) $v
28+
* @return T
29+
*/
30+
function valueOrNull(string $mode, $v)
31+
{
32+
}
33+
34+
/**
35+
* @template T
36+
* @param ($mode is 'int' ? callable(T): int : callable(T): string) $cb
37+
* @return T
38+
*/
39+
function callbacks(string $mode, callable $cb)
40+
{
41+
}
42+
43+
/**
44+
* @template T
45+
* @template U
46+
* @param ($mode is 'a' ? T : ($mode is 'b' ? list<T> : array<string, U>)) $v
47+
* @return T
48+
*/
49+
function nested(string $mode, $v)
50+
{
51+
}
52+
53+
function (string $mode, bool $wrap): void {
54+
// the condition is undecided, so T is what either branch infers
55+
assertType('1|array{1}', listOrValue($mode, [1]));
56+
assertType('1|array{1}', wrapped([1], $wrap));
57+
58+
// null tells nothing about T, as for T|null
59+
assertType('mixed', valueOrNull($mode, null));
60+
assertType('5', valueOrNull($mode, 5));
61+
62+
// only the branch the argument may be infers
63+
assertType('int', callbacks($mode, static fn (int $i): int => $i));
64+
65+
assertType('1|array{1}', nested($mode, [1]));
66+
// list<T> cannot be an array with a string key
67+
assertType('array{k: \'v\'}', nested($mode, ['k' => 'v']));
68+
69+
// decided conditions are unchanged
70+
assertType('1', listOrValue('list', [1]));
71+
assertType('array{1}', listOrValue('value', [1]));
72+
};

0 commit comments

Comments
 (0)