Skip to content

Commit af37cb5

Browse files
committed
Infer template types from conditional parameter types in dependency order
A conditional parameter type is decided before template types are inferred from it, so the branch that is not taken does not take part in the inference. A condition on a template type is decided by what the other parameters inferred for it, so those parameters are inferred first. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 6c839c6 commit af37cb5

4 files changed

Lines changed: 628 additions & 10 deletions

File tree

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Reflection;
4+
5+
use PHPStan\Type\ConditionalType;
6+
use PHPStan\Type\ConditionalTypeForParameter;
7+
use PHPStan\Type\ErrorType;
8+
use PHPStan\Type\Generic\TemplateType;
9+
use PHPStan\Type\Generic\TemplateTypeHelper;
10+
use PHPStan\Type\Generic\TemplateTypeMap;
11+
use PHPStan\Type\Generic\TemplateTypeVariance;
12+
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
13+
use PHPStan\Type\NeverType;
14+
use PHPStan\Type\Type;
15+
use PHPStan\Type\TypeTraverser;
16+
use function array_key_exists;
17+
use function array_keys;
18+
use function array_values;
19+
use function count;
20+
21+
/**
22+
* Infers template types from parameters with conditional types only after the conditions
23+
* are decided, so the branch that is not taken does not take part in the inference:
24+
* `@param ($wrap is true ? list<T> : T) $value` called with `false` infers T from `T` alone.
25+
*
26+
* A condition on a parameter is decided by its argument. A condition on a template type,
27+
* like `(T is int ? U : list<U>)`, is decided by what the other parameters inferred for
28+
* T, so the parameters are inferred in dependency order: the ones T is inferred from
29+
* first. A template type inferred only from the condition on itself stays undecided,
30+
* and both branches take part, as before.
31+
*/
32+
final class ConditionalParameterTypeInference
33+
{
34+
35+
/** @var array<string, list<string>> template types each parameter's conditions depend on, inferred from other parameters */
36+
private array $conditionTemplateTypes = [];
37+
38+
/** @var list<ParameterReflection> */
39+
private array $order;
40+
41+
/**
42+
* @param array<string, ParameterReflection> $parametersWithArgs parameters that have an argument or a default value, by name
43+
*/
44+
public function __construct(array $parametersWithArgs, TemplateTypeMap $templateTypeMap)
45+
{
46+
$templateNames = $templateTypeMap->getTypes();
47+
48+
/** @var array<string, array<string, true>> $mentioned */
49+
$mentioned = [];
50+
/** @var array<string, array<string, true>> $inConditions */
51+
$inConditions = [];
52+
foreach ($parametersWithArgs as $paramName => $param) {
53+
$mentioned[$paramName] = self::findTemplateNames($param->getType(), $templateNames, false);
54+
$inConditions[$paramName] = self::findTemplateNames($param->getType(), $templateNames, true);
55+
}
56+
57+
/** @var array<string, array<string, true>> $dependencies */
58+
$dependencies = [];
59+
foreach ($inConditions as $paramName => $names) {
60+
$dependencies[$paramName] = [];
61+
$this->conditionTemplateTypes[$paramName] = [];
62+
foreach (array_keys($names) as $name) {
63+
$inferredElsewhere = false;
64+
foreach ($mentioned as $otherName => $otherNames) {
65+
if ($otherName === $paramName || !array_key_exists($name, $otherNames)) {
66+
continue;
67+
}
68+
69+
$dependencies[$paramName][$otherName] = true;
70+
$inferredElsewhere = true;
71+
}
72+
73+
if (!$inferredElsewhere) {
74+
continue;
75+
}
76+
77+
$this->conditionTemplateTypes[$paramName][] = $name;
78+
}
79+
}
80+
81+
$this->order = [];
82+
foreach (self::sort($dependencies) as $paramName) {
83+
$this->order[] = $parametersWithArgs[$paramName];
84+
}
85+
}
86+
87+
public static function hasConditionalType(Type $type): bool
88+
{
89+
if (!$type->hasTemplateOrLateResolvableType()) {
90+
return false;
91+
}
92+
93+
$has = false;
94+
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$has): Type {
95+
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
96+
$has = true;
97+
return $type;
98+
}
99+
100+
return $traverse($type);
101+
});
102+
103+
return $has;
104+
}
105+
106+
/**
107+
* The parameter names, each after the parameters its conditions depend on, otherwise in
108+
* declaration order. Parameters whose conditions depend on each other stay in
109+
* declaration order.
110+
*
111+
* @return list<ParameterReflection>
112+
*/
113+
public function order(): array
114+
{
115+
return $this->order;
116+
}
117+
118+
/**
119+
* Decides the conditions in $paramType that can be decided now.
120+
*
121+
* @param array<string, Type> $passedArgs
122+
*/
123+
public function resolve(string $paramName, Type $paramType, array $passedArgs, TemplateTypeMap $typeMap): Type
124+
{
125+
if (!self::hasConditionalType($paramType)) {
126+
return $paramType;
127+
}
128+
129+
$type = ConditionalTypeForParameter::resolveInType(
130+
$paramType,
131+
static fn (string $parameterName): ?Type => $passedArgs[$parameterName] ?? null,
132+
);
133+
134+
$known = [];
135+
foreach ($this->conditionTemplateTypes[$paramName] ?? [] as $name) {
136+
$inferred = $typeMap->getType($name);
137+
if ($inferred === null || $inferred instanceof ErrorType || $inferred instanceof NeverType) {
138+
continue;
139+
}
140+
141+
$known[$name] = $inferred;
142+
}
143+
$knownMap = new TemplateTypeMap($known);
144+
145+
return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($knownMap): Type {
146+
if (!$type instanceof ConditionalType) {
147+
return $traverse($type);
148+
}
149+
150+
// only the condition is decided, so the branches still infer their template types
151+
if (!$knownMap->isEmpty()) {
152+
$type = new ConditionalType(
153+
self::resolveKnown($type->getSubject(), $knownMap),
154+
self::resolveKnown($type->getTarget(), $knownMap),
155+
$type->getIf(),
156+
$type->getElse(),
157+
$type->isNegated(),
158+
);
159+
}
160+
161+
if (!$type->isResolvable()) {
162+
return $traverse($type);
163+
}
164+
165+
return $traverse($type->resolve());
166+
});
167+
}
168+
169+
/**
170+
* Infers from the decided type. A template type the decided branch does not mention,
171+
* like T when an argument for `($mode is 'one' ? T : never)` takes the never branch,
172+
* keeps what the undecided type inferred, so the argument is reported against it
173+
* instead of the template type becoming unresolvable. A template type it mentions
174+
* is inferred from it alone, even when the argument does not match, so
175+
* `callable(T, K=)` given `Closure(int, bool)` does not take K from `callable(K)`
176+
* in another branch.
177+
*/
178+
public static function inferFromDecided(Type $decidedType, Type $argType, TemplateTypeMap $undecidedMap): TemplateTypeMap
179+
{
180+
$keptMap = $undecidedMap;
181+
foreach ($decidedType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
182+
$keptMap = $keptMap->unsetType($reference->getType()->getName());
183+
}
184+
185+
return $decidedType->inferTemplateTypes($argType)->union($keptMap);
186+
}
187+
188+
private static function resolveKnown(Type $type, TemplateTypeMap $known): Type
189+
{
190+
return TemplateTypeHelper::resolveTemplateTypes(
191+
$type,
192+
$known,
193+
TemplateTypeVarianceMap::createEmpty(),
194+
TemplateTypeVariance::createInvariant(),
195+
true,
196+
);
197+
}
198+
199+
/**
200+
* @param array<string, Type> $templateNames
201+
* @return array<string, true>
202+
*/
203+
private static function findTemplateNames(Type $type, array $templateNames, bool $inConditionsOnly): array
204+
{
205+
if (!$type->hasTemplateOrLateResolvableType()) {
206+
return [];
207+
}
208+
209+
$names = [];
210+
$collect = static function (Type $type, callable $traverse) use ($templateNames, &$names): Type {
211+
if ($type instanceof TemplateType && array_key_exists($type->getName(), $templateNames)) {
212+
$names[$type->getName()] = true;
213+
}
214+
215+
// a template type traverses into its bound, so `class-string<TFormType>` with
216+
// `TFormType of FormTypeInterface<TData>` mentions TData too
217+
return $traverse($type);
218+
};
219+
220+
if (!$inConditionsOnly) {
221+
TypeTraverser::map($type, $collect);
222+
return $names;
223+
}
224+
225+
TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($collect): Type {
226+
if ($type instanceof ConditionalType) {
227+
TypeTraverser::map($type->getSubject(), $collect);
228+
TypeTraverser::map($type->getTarget(), $collect);
229+
} elseif ($type instanceof ConditionalTypeForParameter) {
230+
TypeTraverser::map($type->getTarget(), $collect);
231+
}
232+
233+
return $traverse($type);
234+
});
235+
236+
return $names;
237+
}
238+
239+
/**
240+
* @param array<string, array<string, true>> $dependencies
241+
* @return list<string>
242+
*/
243+
private static function sort(array $dependencies): array
244+
{
245+
$order = [];
246+
$emitted = [];
247+
$remaining = array_keys($dependencies);
248+
while (count($remaining) > 0) {
249+
$next = null;
250+
foreach ($remaining as $i => $paramName) {
251+
foreach (array_keys($dependencies[$paramName]) as $dependency) {
252+
if (!array_key_exists($dependency, $emitted)) {
253+
continue 2;
254+
}
255+
}
256+
257+
$next = $i;
258+
break;
259+
}
260+
261+
// parameters whose conditions depend on each other
262+
$next ??= 0;
263+
264+
$order[] = $remaining[$next];
265+
$emitted[$remaining[$next]] = true;
266+
unset($remaining[$next]);
267+
$remaining = array_values($remaining);
268+
}
269+
270+
return $order;
271+
}
272+
273+
}

‎src/Reflection/GenericParametersAcceptorResolver.php‎

Lines changed: 72 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,30 +232,46 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
232232
$predicateTypeMap = $predicateTypeMap === null ? $paramPredicateTypeMap : $predicateTypeMap->union($paramPredicateTypeMap);
233233
}
234234

235+
// null when no parameter has a conditional type, which is almost always
236+
$conditionalInference = self::createConditionalInference($parameters, $namedArgTypes, $parametersAcceptor->getTemplateTypeMap());
237+
if ($conditionalInference !== null) {
238+
// conditions on later parameters are decided by their arguments, so all of them are known up front
239+
foreach ($parameters as $param) {
240+
$argType = self::getArgType($param, $namedArgTypes);
241+
if ($argType === null) {
242+
continue;
243+
}
244+
245+
$passedArgs['$' . $param->getName()] = $argType;
246+
}
247+
}
248+
235249
/** @var array<string, list<Type>> $pinnedTypes */
236250
$pinnedTypes = [];
237-
foreach ($parameters as $param) {
238-
$paramName = $param->getName();
239-
if (isset($namedArgTypes[$paramName])) {
240-
$argType = $namedArgTypes[$paramName];
241-
} elseif ($param->getDefaultValue() !== null) {
242-
$argType = $param->getDefaultValue();
243-
} elseif ($param->isVariadic()) {
244-
$argType = new NeverType(true);
245-
} else {
251+
foreach ($conditionalInference === null ? $parameters : $conditionalInference->order() as $param) {
252+
$argType = self::getArgType($param, $namedArgTypes);
253+
if ($argType === null) {
246254
continue;
247255
}
248256

257+
$paramName = $param->getName();
258+
$passedArgs['$' . $paramName] = $argType;
249259
$paramType = $predicateTypeMap === null ? $param->getType() : self::resolvePredicateTemplateTypes($param->getType(), $predicateTypeMap);
250260
$paramTypeMap = $paramType->inferTemplateTypes($argType);
261+
if ($conditionalInference !== null) {
262+
$decidedParamType = $conditionalInference->resolve($paramName, $paramType, $passedArgs, $typeMap);
263+
if ($decidedParamType !== $paramType) {
264+
$paramTypeMap = ConditionalParameterTypeInference::inferFromDecided($decidedParamType, $argType, $paramTypeMap);
265+
$paramType = $decidedParamType;
266+
}
267+
}
251268
$typeMap = $typeMap->union($paramTypeMap);
252269
// a bare template refers only to itself, in the parameter's contravariant position, so it never pins
253270
if (!$paramType instanceof TemplateType) {
254271
$pinnedTypes = self::collectPinnedTemplateTypes($paramType, $paramTypeMap, $pinnedTypes);
255272
}
256273
// otherwise the last map stays alive until the end of resolve() and raises its peak memory
257274
unset($paramTypeMap);
258-
$passedArgs['$' . $paramName] = $argType;
259275
}
260276

261277
if ($predicateTypeMap !== null) {
@@ -335,6 +351,52 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
335351
return $result;
336352
}
337353

354+
/**
355+
* @param array<string, Type> $namedArgTypes
356+
*/
357+
private static function getArgType(ParameterReflection $param, array $namedArgTypes): ?Type
358+
{
359+
if (isset($namedArgTypes[$param->getName()])) {
360+
return $namedArgTypes[$param->getName()];
361+
}
362+
if ($param->getDefaultValue() !== null) {
363+
return $param->getDefaultValue();
364+
}
365+
if ($param->isVariadic()) {
366+
return new NeverType(true);
367+
}
368+
369+
return null;
370+
}
371+
372+
/**
373+
* @param list<ParameterReflection> $parameters
374+
* @param array<string, Type> $namedArgTypes
375+
*/
376+
private static function createConditionalInference(array $parameters, array $namedArgTypes, TemplateTypeMap $templateTypeMap): ?ConditionalParameterTypeInference
377+
{
378+
foreach ($parameters as $param) {
379+
$type = $param->getType();
380+
// a bare template type is the common case and has no conditional type in it
381+
if ($type instanceof TemplateType || !ConditionalParameterTypeInference::hasConditionalType($type)) {
382+
continue;
383+
}
384+
385+
$parametersWithArgs = [];
386+
foreach ($parameters as $parameter) {
387+
if (self::getArgType($parameter, $namedArgTypes) === null) {
388+
continue;
389+
}
390+
391+
$parametersWithArgs[$parameter->getName()] = $parameter;
392+
}
393+
394+
return new ConditionalParameterTypeInference($parametersWithArgs, $templateTypeMap);
395+
}
396+
397+
return null;
398+
}
399+
338400
/**
339401
* An argument for a parameter that mentions a template only in invariant positions,
340402
* like Inv<int> for Inv<T>, determines the template exactly: other arguments can only

0 commit comments

Comments
 (0)