Skip to content

Commit 89e8a3f

Browse files
committed
Type closures in ternary, match and coalesce arguments from the parameter they are passed to
A closure passed directly took its parameter types from the callable parameter, but one in a branch of `?:`, an arm of `match` or a side of `??` got mixed: only array literal arguments carried the parameter type in the ExpressionContext, match arms and coalesce operands dropped it. Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
1 parent 3d185ca commit 89e8a3f

7 files changed

Lines changed: 101 additions & 8 deletions

File tree

‎src/Analyser/ArgumentsHandler.php‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,16 @@ public function processArgs(
623623
$scopeToPass = $scopeToPass->enterExpressionAssign($arg->value);
624624
}
625625
$argContext = $context->enterDeep();
626-
if (!$arg->unpack && $arg->value instanceof Expr\Array_) {
626+
if (
627+
!$arg->unpack
628+
&& (
629+
$arg->value instanceof Expr\Array_
630+
// their closure operands are the passed value
631+
|| $arg->value instanceof Expr\Ternary
632+
|| $arg->value instanceof Expr\Match_
633+
|| $arg->value instanceof Expr\BinaryOp\Coalesce
634+
)
635+
) {
627636
$argContext = $argContext->enterPassedToType($parameterType, $parameterNativeType);
628637
if ($passedToTypeResolver !== null) {
629638
$argContext = $argContext->enterPassedToTypeResolver($passedToTypeResolver);

‎src/Analyser/ExprHandler/CoalesceHandler.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
5757
$beforeScope = $scope;
5858
$nonNullabilityResult = $this->nonNullabilityHelper->ensureNonNullability($scope, $expr->left);
5959
$condScope = $nodeScopeResolver->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $expr->left);
60-
$condResult = $nodeScopeResolver->processExprNode($stmt, $expr->left, $condScope, $storage, $nodeCallback, $context->enterDeep());
60+
// both sides are the value of the coalesce, so a closure on either side
61+
// is passed wherever the coalesce is
62+
$condResult = $nodeScopeResolver->processExprNode($stmt, $expr->left, $condScope, $storage, $nodeCallback, $context->enterDeep()->enterPassedToType($context->getPassedToType(), $context->getNativePassedToType()));
6163
$scope = $this->nonNullabilityHelper->revertNonNullability($condResult->getScope(), $nonNullabilityResult->getSpecifiedExpressions());
6264
$scope = $nodeScopeResolver->lookForUnsetAllowedUndefinedExpressions($scope, $expr->left);
6365

@@ -85,7 +87,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
8587
);
8688
}
8789
$rightScope = $scope->applySpecifiedTypes($rightSideSpecifiedTypes);
88-
$rightResult = $nodeScopeResolver->processExprNode($stmt, $expr->right, $rightScope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow());
90+
$rightResult = $nodeScopeResolver->processExprNode($stmt, $expr->right, $rightScope, $storage, $nodeCallback, $context->enterDeepKeepingValueFlow()->enterPassedToType($context->getPassedToType(), $context->getNativePassedToType()));
8991
// the left-is-set narrowing, composed from the already-processed chain
9092
// results - the inside-out equivalent of narrowing by isset($expr->left)
9193
// without synthesizing an Isset_ node and re-walking the chain on demand

‎src/Analyser/ExpressionContext.php‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,13 @@ public function withoutValueFlow(): self
9090
return new self($this->isDeep, $this->inAssignRightSideVariableName, $this->inAssignRightSideExpr, $this->inThrow, $this->inAssignRightSideType, $this->inAssignRightSideNativeType, $this->resolveTemplateArguments);
9191
}
9292

93-
/** Match arms allow void expressions, but still feed the enclosing value. */
93+
/**
94+
* Match arms allow void expressions, but still feed the enclosing value -
95+
* and a closure arm is passed wherever the match is.
96+
*/
9497
public function enterMatchArm(): self
9598
{
96-
return new self(false, null, null, resolveTemplateArguments: $this->resolveTemplateArguments, valueFlowTarget: $this->valueFlowTarget, valueConsumed: $this->isValueConsumed());
99+
return new self(false, null, null, resolveTemplateArguments: $this->resolveTemplateArguments, passedToType: $this->passedToType, nativePassedToType: $this->nativePassedToType, valueFlowTarget: $this->valueFlowTarget, valueConsumed: $this->isValueConsumed());
97100
}
98101

99102
public function isValueConsumed(): bool
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace ClosureArgumentInTernaryMatchCoalesce;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
/** @param callable(int): mixed $cb */
10+
function takesCb(callable $cb): void {}
11+
12+
/** @param \Closure(int): mixed $cb */
13+
function takesClosure(\Closure $cb): void {}
14+
15+
/** @param list<callable(string): mixed> $cbs */
16+
function takesCbs(array $cbs): void {}
17+
18+
/**
19+
* @template T
20+
* @param list<T> $xs
21+
* @param callable(T): mixed $cb
22+
*/
23+
function each(array $xs, callable $cb): void {}
24+
25+
/**
26+
* @param (\Closure(int): mixed)|null $maybe
27+
* @param (callable(int): mixed)|false $cbOrFalse
28+
*/
29+
function operands(bool $c, int $n, ?\Closure $maybe, $cbOrFalse): void
30+
{
31+
takesCb($c ? fn ($x) => assertType('int', $x) : fn ($y) => assertType('int', $y));
32+
takesCb($c ? function ($x) { assertType('int', $x); } : function ($y) { assertType('int', $y); });
33+
takesCb($cbOrFalse ?: fn ($x) => assertType('int', $x));
34+
takesCb(match ($n) {
35+
1 => fn ($x) => assertType('int', $x),
36+
default => fn ($y) => assertType('int', $y),
37+
});
38+
takesClosure($maybe ?? fn ($x) => assertType('int', $x));
39+
}
40+
41+
function nested(bool $c, bool $d, int $n): void
42+
{
43+
takesCb($c ? ($d ? fn ($x) => assertType('int', $x) : fn ($y) => assertType('int', $y)) : fn ($z) => assertType('int', $z));
44+
takesCb(match ($n) {
45+
1 => $c ? fn ($x) => assertType('int', $x) : fn ($y) => assertType('int', $y),
46+
default => fn ($z) => assertType('int', $z),
47+
});
48+
takesCbs($c ? [fn ($x) => assertType('string', $x)] : []);
49+
}
50+
51+
function generic(bool $c): void
52+
{
53+
each([1, 2], $c ? fn ($x) => assertType('1|2', $x) : fn ($y) => assertType('1|2', $y));
54+
}
55+
56+
function noContext(bool $c): void
57+
{
58+
$f = $c ? fn ($x) => assertType('mixed', $x) : fn ($y) => assertType('mixed', $y);
59+
}

‎turbo-ext/src/ArgumentsHandler.cpp‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2442,7 +2442,12 @@ class ArgumentsHandler
24422442
if (!unpack) {
24432443
bool isArray = false;
24442444
if (UNEXPECTED(!isA(value, PT_CLASS_ARRAY_EXPR, isArray))) return false;
2445-
if (isArray) {
2445+
// a ternary, match or coalesce: their closure operands are the passed value
2446+
bool passesOperands = false;
2447+
if (!isArray && UNEXPECTED(!isA(value, PT_CLASS_TERNARY_EXPR, passesOperands))) return false;
2448+
if (!isArray && !passesOperands && UNEXPECTED(!isA(value, PT_CLASS_MATCH, passesOperands))) return false;
2449+
if (!isArray && !passesOperands && UNEXPECTED(!isA(value, PT_CLASS_COALESCE_EXPR, passesOperands))) return false;
2450+
if (isArray || passesOperands) {
24462451
zv::Val passed = pt_expression_context_enter_passed_to_type(argContext.raw(), a.parameterType.isUndef() ? NULL : a.parameterType.raw(), a.parameterNativeType.isUndef() ? NULL : a.parameterNativeType.raw());
24472452
if (UNEXPECTED(passed.isUndef())) return false;
24482453
argContext = std::move(passed);

‎turbo-ext/src/CoalesceHandler.cpp‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ zend_class_entry *pt_ce_coalesce_handler = nullptr;
3030

3131
namespace {
3232

33+
/* $operandContext->enterPassedToType($context->getPassedToType(), $context->getNativePassedToType()) */
34+
zv::Val carryPassedToType(zv::Val operandContext, zval *context)
35+
{
36+
if (UNEXPECTED(operandContext.isUndef())) return operandContext;
37+
zv::Val type = pt_expression_context_get_passed_to_type(context);
38+
if (UNEXPECTED(type.isUndef())) return zv::Val();
39+
zv::Val nativeType = pt_expression_context_get_native_passed_to_type(context);
40+
if (UNEXPECTED(nativeType.isUndef())) return zv::Val();
41+
return pt_expression_context_enter_passed_to_type(operandContext.raw(), Z_TYPE_P(type.raw()) == IS_NULL ? NULL : type.raw(), Z_TYPE_P(nativeType.raw()) == IS_NULL ? NULL : nativeType.raw());
42+
}
43+
3344
/* $resolution->isSet($typeCallback) (IssetabilityResolution.cpp): the ?bool
3445
* verdict */
3546
zv::Val resolutionIsSet(zval *resolution, zval *typeCallback)
@@ -112,7 +123,9 @@ class CoalesceHandler
112123
if (UNEXPECTED(ensuredScope == NULL)) return zv::Val();
113124
zv::Val condScope = pt_node_scope_resolver_look_for_set_allowed_undefined_expressions(nodeScopeResolver, ensuredScope, left);
114125
if (UNEXPECTED(condScope.isUndef())) return zv::Val();
115-
zv::Val condContext = pt_expression_context_enter_deep(context);
126+
// both sides are the value of the coalesce, so a closure on either side
127+
// is passed wherever the coalesce is
128+
zv::Val condContext = carryPassedToType(pt_expression_context_enter_deep(context), context);
116129
if (UNEXPECTED(condContext.isUndef())) return zv::Val();
117130
zv::Val condResult = pt_node_scope_resolver_process_expr_node(nodeScopeResolver, stmt, left, condScope.raw(), storage, nodeCallback, condContext.raw());
118131
if (UNEXPECTED(condResult.isUndef())) return zv::Val();
@@ -172,7 +185,7 @@ class CoalesceHandler
172185
if (UNEXPECTED(rightScope.isUndef())) return zv::Val();
173186
zval *right = ptoh::binaryOpRight(expr);
174187
if (UNEXPECTED(right == NULL)) return zv::Val();
175-
zv::Val rightContext = pt_expression_context_enter_deep_keeping_value_flow(context);
188+
zv::Val rightContext = carryPassedToType(pt_expression_context_enter_deep_keeping_value_flow(context), context);
176189
if (UNEXPECTED(rightContext.isUndef())) return zv::Val();
177190
zv::Val rightResult = pt_node_scope_resolver_process_expr_node(nodeScopeResolver, stmt, right, rightScope.raw(), storage, nodeCallback, rightContext.raw());
178191
if (UNEXPECTED(rightResult.isUndef())) return zv::Val();

‎turbo-ext/src/ExpressionContext.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ class ExpressionContext
149149
f.inAssignRightSideVariableName = NULL;
150150
f.inAssignRightSideExpr = NULL;
151151
f.resolveTemplateArguments = boolSlot(slots::resolveTemplateArguments);
152+
f.passedToType = isNull(slots::passedToType) ? NULL : slot(slots::passedToType);
153+
f.nativePassedToType = isNull(slots::nativePassedToType) ? NULL : slot(slots::nativePassedToType);
152154
f.valueFlowTarget = slot(slots::valueFlowTarget);
153155
f.valueConsumed = isValueConsumed() ? 1 : 0;
154156
return newSelf(f);

0 commit comments

Comments
 (0)