Skip to content

Commit b958efe

Browse files
committed
Keep the creation-time fixpoint for closures assigned to their own by-ref variable
A closure assigned to one of its by-ref variables - $f = function () use (&$f) - reaches itself through that variable in ways invocations cannot all be followed: call_user_func($f), $f->__invoke(), aliasing. Its by-ref uses now keep the creation-time fixpoint instead of seeing the variable as null. Nested closures are scanned only for the variables they capture, and arrow functions without those shadowed by their parameters, so an unrelated nested $count() no longer widens the enclosing closure's by-ref $count. Amp-Thread-ID: https://ampcode.com/threads/T-01a19c29-188b-7572-9730-387584a8a9fd
1 parent b2f452e commit b958efe

6 files changed

Lines changed: 349 additions & 118 deletions

File tree

‎src/Analyser/Generics/ClosureSignatureInference.php‎

Lines changed: 61 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@
2424
use PHPStan\Type\TypeCombinator;
2525
use PHPStan\Type\TypeTraverser;
2626
use PHPStan\Type\UnionType;
27+
use function array_diff;
2728
use function array_keys;
2829
use function array_pop;
30+
use function array_values;
2931
use function count;
3032
use function in_array;
3133
use function is_array;
@@ -89,6 +91,8 @@ final class ClosureSignatureInference
8991

9092
private const REBOUND_VARIABLES_ATTRIBUTE = 'closureSignatureReboundVariables';
9193

94+
private const NESTED_ASSIGNED_CLOSURES_ATTRIBUTE = 'closureSignatureNestedAssignedClosures';
95+
9296
public function __construct(
9397
#[AutowiredParameter(ref: '%featureToggles.closureSignaturesFromUsages%')]
9498
private bool $enabled,
@@ -118,7 +122,7 @@ public static function isByRefMarker(UnresolvedTemplateArgumentType $marker): bo
118122
* by variable name - while observing, and in the second pass for a site the
119123
* observation resolved. Empty for a closure whose invocations cannot be
120124
* followed: a generator (invoking it does not run the body), a closure
121-
* invoking its own by-ref variable.
125+
* invoking its own by-ref variable or assigned to it.
122126
*
123127
* @return array<string, Type>
124128
*/
@@ -143,12 +147,19 @@ public function getByRefUseMarkers(MutatingScope $scope, Closure|ArrowFunction $
143147
return [];
144148
}
145149
$reboundNames = self::getReboundVariableNames($body, $frame->getClosureSignatureStmts());
150+
$assignedClosures = self::getAssignedClosures($body, $frame->getClosureSignatureStmts(), true);
146151
foreach ($names as $name) {
147152
// unset or bound to another reference, the variable no longer is the
148153
// one the closure writes to - its effects stay the creation-time fixpoint
149154
if (isset($reboundNames[$name])) {
150155
return [];
151156
}
157+
// `$f = function () use (&$f)`: the body reaches the closure itself
158+
// through the variable - aliased, captured, passed on - so its
159+
// invocations cannot all be followed
160+
if (in_array($expr, $assignedClosures[$name] ?? [], true)) {
161+
return [];
162+
}
152163
}
153164

154165
$markers = [];
@@ -540,29 +551,48 @@ private static function byRefUseNames(Closure $expr): array
540551
}
541552

542553
/**
543-
* @param Node\Stmt[] $stmts
554+
* Closures and arrow functions written in the body are scanned for
555+
* invocations of the variables they capture; their yields are their own.
556+
*
557+
* @param Node[] $stmts
544558
* @param array<int, string> $names
545559
*/
546-
private static function bodyYieldsOrInvokes(array $stmts, array $names): bool
560+
private static function bodyYieldsOrInvokes(array $stmts, array $names, bool $checkYield = true): bool
547561
{
548562
$stack = $stmts;
549-
// closures and arrow functions written in the body: their yields are
550-
// their own, but they can invoke the variables on the body's behalf
551-
$nestedStack = [];
552-
while (count($stack) > 0 || count($nestedStack) > 0) {
553-
$nested = count($stack) === 0;
554-
$node = $nested ? array_pop($nestedStack) : array_pop($stack);
555-
if (!$nested && ($node instanceof Closure || $node instanceof ArrowFunction)) {
556-
$nestedStack[] = $node;
563+
while (count($stack) > 0) {
564+
$node = array_pop($stack);
565+
if ($node instanceof Closure) {
566+
$capturedNames = [];
567+
foreach ($node->uses as $use) {
568+
if (!is_string($use->var->name) || !in_array($use->var->name, $names, true)) {
569+
continue;
570+
}
571+
$capturedNames[] = $use->var->name;
572+
}
573+
if ($capturedNames !== [] && self::bodyYieldsOrInvokes($node->stmts, $capturedNames, false)) {
574+
return true;
575+
}
557576
continue;
558577
}
559-
if (
560-
($node instanceof Node\FunctionLike && !$node instanceof Closure && !$node instanceof ArrowFunction)
561-
|| $node instanceof Node\Stmt\ClassLike
562-
) {
578+
if ($node instanceof ArrowFunction) {
579+
$parameterNames = [];
580+
foreach ($node->params as $param) {
581+
if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) {
582+
continue;
583+
}
584+
$parameterNames[] = $param->var->name;
585+
}
586+
$capturedNames = array_values(array_diff($names, $parameterNames));
587+
if ($capturedNames !== [] && self::bodyYieldsOrInvokes([$node->expr], $capturedNames, false)) {
588+
return true;
589+
}
590+
continue;
591+
}
592+
if ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike) {
563593
continue;
564594
}
565-
if (!$nested && ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom)) {
595+
if ($checkYield && ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom)) {
566596
return true;
567597
}
568598
if (
@@ -575,14 +605,13 @@ private static function bodyYieldsOrInvokes(array $stmts, array $names): bool
575605
}
576606
foreach ($node->getSubNodeNames() as $subNodeName) {
577607
$subNode = $node->$subNodeName;
578-
$subNodes = is_array($subNode) ? $subNode : [$subNode];
579-
foreach ($subNodes as $item) {
580-
if (!$item instanceof Node) {
581-
continue;
582-
}
583-
if ($nested) {
584-
$nestedStack[] = $item;
585-
} else {
608+
if ($subNode instanceof Node) {
609+
$stack[] = $subNode;
610+
} elseif (is_array($subNode)) {
611+
foreach ($subNode as $item) {
612+
if (!$item instanceof Node) {
613+
continue;
614+
}
586615
$stack[] = $item;
587616
}
588617
}
@@ -1132,13 +1161,17 @@ public function findAssignedClosures(MutatingScope $scope, string $name): array
11321161
}
11331162

11341163
/**
1164+
* With $nested, also the closures assigned in the function-likes the body
1165+
* contains - to the variables of those.
1166+
*
11351167
* @param Node\Stmt[] $stmts
11361168
* @return array<string, list<Closure|ArrowFunction>>
11371169
*/
1138-
private static function getAssignedClosures(Node $body, array $stmts): array
1170+
private static function getAssignedClosures(Node $body, array $stmts, bool $nested = false): array
11391171
{
1172+
$attribute = $nested ? self::NESTED_ASSIGNED_CLOSURES_ATTRIBUTE : self::ASSIGNED_CLOSURES_ATTRIBUTE;
11401173
/** @var array<string, list<Closure|ArrowFunction>>|null $cached */
1141-
$cached = $body->getAttribute(self::ASSIGNED_CLOSURES_ATTRIBUTE);
1174+
$cached = $body->getAttribute($attribute);
11421175
if ($cached !== null) {
11431176
return $cached;
11441177
}
@@ -1147,7 +1180,7 @@ private static function getAssignedClosures(Node $body, array $stmts): array
11471180
$stack = $stmts;
11481181
while (count($stack) > 0) {
11491182
$node = array_pop($stack);
1150-
if ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike) {
1183+
if (!$nested && ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike)) {
11511184
continue;
11521185
}
11531186
if (
@@ -1172,7 +1205,7 @@ private static function getAssignedClosures(Node $body, array $stmts): array
11721205
}
11731206
}
11741207
}
1175-
$body->setAttribute(self::ASSIGNED_CLOSURES_ATTRIBUTE, $assigned);
1208+
$body->setAttribute($attribute, $assigned);
11761209

11771210
return $assigned;
11781211
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Bug15442;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
class GridLayout
10+
{
11+
protected function buildTemplate(): void
12+
{
13+
$fx = static function () use (&$fx) {
14+
(static function () use ($fx) {
15+
assertType('static-Closure(): void', $fx);
16+
$fx();
17+
18+
dummy(); // @phpstan-ignore-line
19+
})();
20+
};
21+
22+
dummy($fx); // @phpstan-ignore-line
23+
}
24+
25+
protected function arrowFunction(): void
26+
{
27+
$fx = static function () use (&$fx) {
28+
(static fn () => assertType('static-Closure(): void', $fx) && $fx())();
29+
};
30+
31+
dummy($fx); // @phpstan-ignore-line
32+
}
33+
34+
public function callUserFunc(): void
35+
{
36+
$fx = static function () use (&$fx) {
37+
assertType('static-Closure(): void', $fx);
38+
call_user_func($fx);
39+
};
40+
}
41+
42+
public function invokeMethod(): void
43+
{
44+
$fx = static function () use (&$fx) {
45+
assertType('static-Closure(): void', $fx);
46+
$fx->__invoke();
47+
};
48+
}
49+
50+
public function alias(): void
51+
{
52+
$fx = static function () use (&$fx) {
53+
$alias = $fx;
54+
assertType('static-Closure(): void', $alias);
55+
$alias();
56+
};
57+
}
58+
59+
public function insideClosure(): void
60+
{
61+
$outer = static function (): void {
62+
$fx = static function () use (&$fx) {
63+
(static function () use ($fx) {
64+
assertType('static-Closure(): void', $fx);
65+
$fx();
66+
})();
67+
};
68+
$fx();
69+
};
70+
$outer();
71+
}
72+
73+
public function unrelatedNestedScopes(): void
74+
{
75+
$count = 0;
76+
$increment = static function () use (&$count): void {
77+
assertType('0', $count);
78+
(static function (\Closure $count): void {
79+
$count();
80+
})(static function (): void {});
81+
(static fn (\Closure $count) => $count())(static function (): void {});
82+
$count++;
83+
};
84+
$increment();
85+
assertType('1', $count);
86+
}
87+
}

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,11 @@ public function testBug15285(): void
463463
$this->analyse([__DIR__ . '/data/bug-15285.php'], []);
464464
}
465465

466+
public function testBug15442(): void
467+
{
468+
$this->analyse([__DIR__ . '/data/bug-15442.php'], []);
469+
}
470+
466471
#[RequiresPhp('>= 8.0.0')]
467472
public function testBug11935WithCheckExplicitMixed(): void
468473
{
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Bug15442Rule;
6+
7+
class GridLayout
8+
{
9+
protected function buildTemplate(): void
10+
{
11+
$fx = static function () use (&$fx) {
12+
(static function () use ($fx) {
13+
$fx();
14+
15+
dummy();
16+
})();
17+
};
18+
19+
dummy($fx);
20+
}
21+
22+
protected function viaAlias(): void
23+
{
24+
$fx = static function () use (&$fx) {
25+
$alias = $fx;
26+
$alias();
27+
};
28+
}
29+
}

0 commit comments

Comments
 (0)