Skip to content

Commit fea0178

Browse files
committed
Narrow parameters through chained conditional parameter types
A condition on a parameter that has a conditional type itself is now checked against its resolved type, so `($a is int ? int : string) $b` narrows `($b is int ? 'I' : 'S') $c` too, whatever the order the parameters are declared in. Conditional parameter types in a union, like `($a is int ? int : string)|null`, narrow the parameter as well. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent af37cb5 commit fea0178

3 files changed

Lines changed: 194 additions & 18 deletions

File tree

‎src/Analyser/MutatingScope.php‎

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2193,25 +2193,60 @@ private function enterFunctionLike(
21932193
$parameterType = $parameter->getType();
21942194

21952195
if ($parameterType instanceof ConditionalTypeForParameter) {
2196-
$targetParameterName = substr($parameterType->getParameterName(), 1);
2197-
if (array_key_exists($targetParameterName, $parametersByName)) {
2198-
$targetParameter = $parametersByName[$targetParameterName];
2196+
$conditionalParameterTypes = [$parameterType];
2197+
} elseif ($parameterType instanceof UnionType) {
2198+
// `($a is int ? int : string)|null`
2199+
$conditionalParameterTypes = [];
2200+
foreach ($parameterType->getTypes() as $innerType) {
2201+
if (!$innerType instanceof ConditionalTypeForParameter) {
2202+
continue;
2203+
}
21992204

2200-
$ifType = $parameterType->isNegated() ? $parameterType->getElse() : $parameterType->getIf();
2201-
$elseType = $parameterType->isNegated() ? $parameterType->getIf() : $parameterType->getElse();
2205+
$conditionalParameterTypes[] = $innerType;
2206+
}
2207+
} else {
2208+
$conditionalParameterTypes = [];
2209+
}
22022210

2203-
$holder = new ConditionalExpressionHolder([
2204-
$parameterType->getParameterName() => ExpressionTypeHolder::createYes(new Variable($targetParameterName), TypeCombinator::intersect($targetParameter->getType(), $parameterType->getTarget())),
2205-
], ExpressionTypeHolder::createYes(new Variable($parameter->getName()), $ifType));
2206-
$conditionalTypes['$' . $parameter->getName()][$holder->getKey()] = $holder;
2211+
foreach ($conditionalParameterTypes as $conditionalParameterType) {
2212+
$targetParameterName = substr($conditionalParameterType->getParameterName(), 1);
2213+
if (!array_key_exists($targetParameterName, $parametersByName)) {
2214+
continue;
2215+
}
2216+
2217+
// the target parameter's own conditional type is resolved, so a condition
2218+
// on it matches its narrowed type and the conditions chain:
2219+
// `$a` narrows `($a is int ? int : string) $b`, which narrows `($b is int ? … : …) $c`
2220+
$targetParameterType = TypeUtils::resolveLateResolvableTypes($parametersByName[$targetParameterName]->getType());
2221+
$subjectTypes = [
2222+
TypeCombinator::intersect($targetParameterType, $conditionalParameterType->getTarget()),
2223+
TypeCombinator::remove($targetParameterType, $conditionalParameterType->getTarget()),
2224+
];
2225+
foreach ($subjectTypes as $i => $subjectType) {
2226+
if ($parameterType === $conditionalParameterType) {
2227+
$isIf = ($i === 0) !== $conditionalParameterType->isNegated();
2228+
$narrowedType = $isIf ? $conditionalParameterType->getIf() : $conditionalParameterType->getElse();
2229+
} else {
2230+
$narrowedType = TypeUtils::resolveLateResolvableTypes(ConditionalTypeForParameter::resolveInType(
2231+
$parameterType,
2232+
static fn (string $parameterName): ?Type => $parameterName === $conditionalParameterType->getParameterName() ? $subjectType : null,
2233+
));
2234+
}
22072235

22082236
$holder = new ConditionalExpressionHolder([
2209-
$parameterType->getParameterName() => ExpressionTypeHolder::createYes(new Variable($targetParameterName), TypeCombinator::remove($targetParameter->getType(), $parameterType->getTarget())),
2210-
], ExpressionTypeHolder::createYes(new Variable($parameter->getName()), $elseType));
2237+
$conditionalParameterType->getParameterName() => ExpressionTypeHolder::createYes(new Variable($targetParameterName), $subjectType),
2238+
], ExpressionTypeHolder::createYes(new Variable($parameter->getName()), $narrowedType));
22112239
$conditionalTypes['$' . $parameter->getName()][$holder->getKey()] = $holder;
22122240
}
22132241
}
22142242

2243+
if ($conditionalParameterTypes !== []) {
2244+
// the holders above narrow it, so the type itself is the union of the branches;
2245+
// narrowing an unresolved conditional type, like `is_int($b)`, would intersect
2246+
// it into `($a is int ? int : string)&int` that matches no condition on `$b`
2247+
$parameterType = TypeUtils::resolveLateResolvableTypes($parameterType);
2248+
}
2249+
22152250
$paramExprString = '$' . $parameter->getName();
22162251
if ($parameter->isVariadic()) {
22172252
if (!$this->getPhpVersion()->supportsNamedArguments()->no() && $functionReflection->acceptsNamedArguments()->yes()) {
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
<?php // lint >= 8.0
2+
3+
namespace ConditionalParameterTypeNarrowing;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @param int|string $a
9+
* @param ($a is int ? int : string) $b
10+
* @param ($b is int ? 'I' : 'S') $c
11+
*/
12+
function chain(int|string $a, int|string $b, string $c): void
13+
{
14+
if (is_int($a)) {
15+
assertType('int', $b);
16+
assertType("'I'", $c);
17+
} else {
18+
assertType('string', $b);
19+
assertType("'S'", $c);
20+
}
21+
22+
assertType("'I'|'S'", $c);
23+
}
24+
25+
/**
26+
* @param ($c is int ? 'I' : 'S') $d
27+
* @param ($b is int ? int : string) $c
28+
* @param ($a is int ? int : string) $b
29+
* @param int|string $a
30+
*/
31+
function chainDeclaredBackwards(string $d, int|string $c, int|string $b, int|string $a): void
32+
{
33+
if (is_int($a)) {
34+
assertType('int', $c);
35+
assertType("'I'", $d);
36+
} else {
37+
assertType('string', $c);
38+
assertType("'S'", $d);
39+
}
40+
41+
if (is_int($b)) {
42+
assertType("'I'", $d);
43+
}
44+
}
45+
46+
/**
47+
* @param ($a is int ? int : string)|null $b
48+
*/
49+
function nullable(int|string $a, int|string|null $b): void
50+
{
51+
if (is_int($a)) {
52+
assertType('int|null', $b);
53+
} else {
54+
assertType('string|null', $b);
55+
}
56+
}
57+
58+
/**
59+
* @param ($a is int ? int : string)|null $b
60+
* @param ($b is int ? 'I' : 'S') $c
61+
*/
62+
function chainThroughNullable(int|string $a, int|string|null $b, string $c): void
63+
{
64+
if (is_int($a)) {
65+
// $b can still be null, which is not int
66+
assertType("'I'|'S'", $c);
67+
}
68+
69+
if (is_int($b)) {
70+
assertType("'I'", $c);
71+
}
72+
}
73+
74+
/**
75+
* @param ($b is int ? int : string) $a
76+
* @param ($a is int ? int : string) $b
77+
*/
78+
function cycle(int|string $a, int|string $b): void
79+
{
80+
if (is_int($a)) {
81+
assertType('int', $b);
82+
} else {
83+
assertType('string', $b);
84+
}
85+
}
86+
87+
/**
88+
* @template T of int|string
89+
* @param T $a
90+
* @param (T is int ? 'I' : 'S') $c
91+
*/
92+
function conditionOnTemplate(int|string $a, string $c): void
93+
{
94+
if (is_int($a)) {
95+
// T can be int|string, with an int passed for $a
96+
assertType("'I'|'S'", $c);
97+
}
98+
}

‎turbo-ext/src/MutatingScope.cpp‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4600,8 +4600,32 @@ class MutatingScope
46004600
if (UNEXPECTED(parameterNameRaw == NULL)) return zv::Val();
46014601
zv::Str parameterName = zv::Str::adopt(parameterNameRaw);
46024602

4603+
/* the ConditionalTypeForParameter itself, or the ones in a union:
4604+
* `($a is int ? int : string)|null` */
4605+
bool hasConditionalParameterTypes = false;
46034606
if (parameterType.ref().isObject() && parameterType.ref().instanceOf(pt_ce_conditional_type_for_parameter)) {
4604-
if (UNEXPECTED(!addConditionalParameterTypes(conditionalTypes, parametersByName, parameterType.ref(), parameterName.get()))) return zv::Val();
4607+
hasConditionalParameterTypes = true;
4608+
if (UNEXPECTED(!addConditionalParameterTypes(conditionalTypes, parametersByName, parameterType.ref(), parameterType.raw(), parameterName.get()))) return zv::Val();
4609+
} else if (parameterType.ref().isObject() && parameterType.ref().instanceOf(pt_ce_union_type)) {
4610+
zv::Val innerTypes = pt_type_call(parameterType.ref().asObject(), PT_LC("gettypes"), 0, NULL);
4611+
if (UNEXPECTED(innerTypes.isUndef())) return zv::Val();
4612+
if (UNEXPECTED(!innerTypes.ref().isArray())) {
4613+
zend_type_error("phpstan_turbo: getTypes() must return array, %s returned", zend_zval_value_name(innerTypes.raw()));
4614+
return zv::Val();
4615+
}
4616+
for (auto inner : zv::ArrRef(innerTypes.raw())) {
4617+
zv::Ref innerType = inner.value().deref();
4618+
if (!innerType.isObject() || !innerType.instanceOf(pt_ce_conditional_type_for_parameter)) continue;
4619+
hasConditionalParameterTypes = true;
4620+
if (UNEXPECTED(!addConditionalParameterTypes(conditionalTypes, parametersByName, innerType, parameterType.raw(), parameterName.get()))) return zv::Val();
4621+
}
4622+
}
4623+
4624+
if (hasConditionalParameterTypes) {
4625+
/* the holders narrow it, so the type itself is the union of the branches */
4626+
zv::Val resolved = pt_type_utils_resolve_late_resolvable_types(parameterType.raw());
4627+
if (UNEXPECTED(resolved.isUndef())) return zv::Val();
4628+
parameterType = std::move(resolved);
46054629
}
46064630

46074631
zv::Str paramExprString = zv::Str::adopt(zend_strpprintf(0, "$%s", ZSTR_VAL(parameterName.get())));
@@ -4694,11 +4718,13 @@ class MutatingScope
46944718
return true;
46954719
}
46964720

4697-
/* the two ConditionalExpressionHolders a ConditionalTypeForParameter
4698-
* parameter adds to $conditionalTypes; false = pending exception */
4699-
[[nodiscard]] bool addConditionalParameterTypes(zv::Arr &conditionalTypes, zv::Arr &parametersByName, zv::Ref parameterType, zend_string *parameterName)
4721+
/* the two ConditionalExpressionHolders a ConditionalTypeForParameter in
4722+
* the type of a parameter adds to $conditionalTypes: conditionalType is
4723+
* parameterType itself or one of its union members; false = pending exception */
4724+
[[nodiscard]] bool addConditionalParameterTypes(zv::Arr &conditionalTypes, zv::Arr &parametersByName, zv::Ref conditionalType, zval *parameterType, zend_string *parameterName)
47004725
{
4701-
zend_object *conditional = parameterType.asObject();
4726+
zend_object *conditional = conditionalType.asObject();
4727+
bool isTopLevel = Z_TYPE_P(parameterType) == IS_OBJECT && Z_OBJ_P(parameterType) == conditional;
47024728
zv::Val targetParameterName = pt_type_call(conditional, PT_LC("getparametername"), 0, NULL);
47034729
if (UNEXPECTED(targetParameterName.isUndef())) return false;
47044730
zend_string *rawTargetName = zval_get_string(targetParameterName.raw());
@@ -4726,7 +4752,11 @@ class MutatingScope
47264752
? pt_type_call(conditional, PT_LC("getif"), 0, NULL)
47274753
: pt_type_call(conditional, PT_LC("getelse"), 0, NULL);
47284754
if (UNEXPECTED(elseType.isUndef())) return false;
4729-
zv::Val targetParameterType = pt_type_call(Z_OBJ_P(targetParameter), PT_LC("gettype"), 0, NULL);
4755+
zv::Val declaredTargetParameterType = pt_type_call(Z_OBJ_P(targetParameter), PT_LC("gettype"), 0, NULL);
4756+
if (UNEXPECTED(declaredTargetParameterType.isUndef())) return false;
4757+
/* TypeUtils::resolveLateResolvableTypes($targetParameter->getType()): a condition
4758+
* on a parameter with its own conditional type matches its narrowed type */
4759+
zv::Val targetParameterType = pt_type_utils_resolve_late_resolvable_types(declaredTargetParameterType.raw());
47304760
if (UNEXPECTED(targetParameterType.isUndef())) return false;
47314761
zv::Val target = pt_type_call(conditional, PT_LC("gettarget"), 0, NULL);
47324762
if (UNEXPECTED(target.isUndef())) return false;
@@ -4758,8 +4788,21 @@ class MutatingScope
47584788
zv::Val condition = zv::Val::adopt(conditionHolder);
47594789
zv::Arr conditions = zv::Arr::create(1);
47604790
conditions.set(fullTargetName.get(), std::move(condition));
4791+
zv::Val narrowedType;
4792+
if (isTopLevel) {
4793+
narrowedType = zv::Val::copyOf(zv::Ref(i == 0 ? ifType.raw() : elseType.raw()));
4794+
} else {
4795+
/* TypeUtils::resolveLateResolvableTypes(ConditionalTypeForParameter::resolveInType(
4796+
* $parameterType, fn ($name) => $name === $targetName ? $subjectType : null)) */
4797+
zv::Arr subjectArgs = zv::Arr::create(1);
4798+
subjectArgs.set(fullTargetName.get(), zv::Val::copyOf(zv::Ref(i == 0 ? intersected.raw() : removed.raw())));
4799+
zv::Val resolvedInType = pt_conditional_type_for_parameter_resolve_in_type_with_args(parameterType, subjectArgs.raw());
4800+
if (UNEXPECTED(resolvedInType.isUndef())) return false;
4801+
narrowedType = pt_type_utils_resolve_late_resolvable_types(resolvedInType.raw());
4802+
if (UNEXPECTED(narrowedType.isUndef())) return false;
4803+
}
47614804
zval typeHolder;
4762-
pt_holder_create(&typeHolder, parameterVariable.raw(), i == 0 ? ifType.raw() : elseType.raw(), PT_TRI_YES);
4805+
pt_holder_create(&typeHolder, parameterVariable.raw(), narrowedType.raw(), PT_TRI_YES);
47634806
zv::Val holderType = zv::Val::adopt(typeHolder);
47644807
zv::Args holderArgs{conditions.raw(), holderType.raw()};
47654808
zv::Val holder = pt_type_new_ce(pt_ce_cond_expr_holder, 2, holderArgs);

0 commit comments

Comments
 (0)