Skip to content

Commit 4db7884

Browse files
ondrejmirtesclaude
andcommitted
Replay scope-deriving mutators in NodeCallbackScope answers
NodeCallbackScope answers getType()/getNativeType() from the asked node's stored before-scope, which knows nothing about what a rule derived locally from the callback scope. filterByTruthyValue() and filterByFalseyValue() were already recorded and replayed onto the before-scope, but assignExpression(), assignVariable() and invalidateExpression() were not — a rule assigning a more specific type onto its scope read the original stored type right back. The recorded filters were also lost when the derivation chain passed through one of the unrecorded mutators. Record every scope-deriving call in one ordered list (replacing the separate truthy/falsey lists, whose replay was order-lossy between the two kinds) and replay it in call order in preprocessScope(). Only top-level calls are recorded: a mutator implemented via other mutators resets the list to its caller's view and appends itself, and the replay re-runs the composition. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01K2oPPwjrXy88MUsYekCFQ6
1 parent e288e03 commit 4db7884

4 files changed

Lines changed: 247 additions & 24 deletions

File tree

‎src/Analyser/NodeCallbackScope.php‎

Lines changed: 59 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
namespace PHPStan\Analyser;
44

5+
use Closure;
56
use PhpParser\Node\Expr;
67
use PHPStan\Node\Expr\TypeExpr;
8+
use PHPStan\Reflection\ClassReflection;
79
use PHPStan\Reflection\FunctionReflection;
810
use PHPStan\Reflection\MethodReflection;
911
use PHPStan\Reflection\ParameterReflection;
12+
use PHPStan\TrinaryLogic;
1013
use PHPStan\Type\Type;
1114
use function array_pop;
1215
use function count;
@@ -15,11 +18,19 @@
1518
final class NodeCallbackScope extends MutatingScope
1619
{
1720

18-
/** @var Expr[] */
19-
private array $truthyValueExprs = [];
20-
21-
/** @var Expr[] */
22-
private array $falseyValueExprs = [];
21+
/**
22+
* Scope-deriving calls a rule made on this scope, in call order. Asks are
23+
* answered from the asked node's stored before-scope (see doGetType()),
24+
* which knows nothing about what the rule derived locally — so every
25+
* deriving call is recorded here and replayed onto the before-scope
26+
* before it answers (preprocessScope()). Only top-level calls are
27+
* recorded: a mutator implemented via other mutators (assignVariable()
28+
* calls assignExpression()) resets the list to its own caller's view and
29+
* appends itself, and the replay re-runs the composition.
30+
*
31+
* @var list<Closure(MutatingScope): MutatingScope>
32+
*/
33+
private array $scopeOps = [];
2334

2435
private ?MutatingScope $walkScope = null;
2536

@@ -126,8 +137,7 @@ private function doGetType(Expr $node): Type
126137

127138
if (
128139
!$this->nativeTypesPromoted
129-
&& count($this->truthyValueExprs) === 0
130-
&& count($this->falseyValueExprs) === 0
140+
&& count($this->scopeOps) === 0
131141
) {
132142
if ($beforeScope !== null) {
133143
return $beforeScope->getType($node);
@@ -175,8 +185,7 @@ private function doGetNativeType(Expr $expr): Type
175185

176186
if (
177187
!$this->nativeTypesPromoted
178-
&& count($this->truthyValueExprs) === 0
179-
&& count($this->falseyValueExprs) === 0
188+
&& count($this->scopeOps) === 0
180189
) {
181190
if ($beforeScope !== null) {
182191
return $beforeScope->getNativeType($expr);
@@ -202,9 +211,8 @@ public function filterByTruthyValue(Expr $expr): self
202211
{
203212
/** @var self $scope */
204213
$scope = parent::filterByTruthyValue($expr);
205-
$scope->truthyValueExprs = $this->truthyValueExprs;
206-
$scope->falseyValueExprs = $this->falseyValueExprs;
207-
$scope->truthyValueExprs[] = $expr;
214+
$scope->scopeOps = $this->scopeOps;
215+
$scope->scopeOps[] = static fn (MutatingScope $scope): MutatingScope => $scope->filterByTruthyValue($expr);
208216

209217
return $scope;
210218
}
@@ -213,9 +221,41 @@ public function filterByFalseyValue(Expr $expr): self
213221
{
214222
/** @var self $scope */
215223
$scope = parent::filterByFalseyValue($expr);
216-
$scope->truthyValueExprs = $this->truthyValueExprs;
217-
$scope->falseyValueExprs = $this->falseyValueExprs;
218-
$scope->falseyValueExprs[] = $expr;
224+
$scope->scopeOps = $this->scopeOps;
225+
$scope->scopeOps[] = static fn (MutatingScope $scope): MutatingScope => $scope->filterByFalseyValue($expr);
226+
227+
return $scope;
228+
}
229+
230+
/**
231+
* @param list<string> $intertwinedPropagatedFrom
232+
*/
233+
public function assignVariable(string $variableName, Type $type, Type $nativeType, TrinaryLogic $certainty, array $intertwinedPropagatedFrom = []): self
234+
{
235+
/** @var self $scope */
236+
$scope = parent::assignVariable($variableName, $type, $nativeType, $certainty, $intertwinedPropagatedFrom);
237+
$scope->scopeOps = $this->scopeOps;
238+
$scope->scopeOps[] = static fn (MutatingScope $scope): MutatingScope => $scope->assignVariable($variableName, $type, $nativeType, $certainty, $intertwinedPropagatedFrom);
239+
240+
return $scope;
241+
}
242+
243+
public function assignExpression(Expr $expr, Type $type, Type $nativeType): self
244+
{
245+
/** @var self $scope */
246+
$scope = parent::assignExpression($expr, $type, $nativeType);
247+
$scope->scopeOps = $this->scopeOps;
248+
$scope->scopeOps[] = static fn (MutatingScope $scope): MutatingScope => $scope->assignExpression($expr, $type, $nativeType);
249+
250+
return $scope;
251+
}
252+
253+
public function invalidateExpression(Expr $expressionToInvalidate, bool $requireMoreCharacters = false, ?ClassReflection $invalidatingClass = null): self
254+
{
255+
/** @var self $scope */
256+
$scope = parent::invalidateExpression($expressionToInvalidate, $requireMoreCharacters, $invalidatingClass);
257+
$scope->scopeOps = $this->scopeOps;
258+
$scope->scopeOps[] = static fn (MutatingScope $scope): MutatingScope => $scope->invalidateExpression($expressionToInvalidate, $requireMoreCharacters, $invalidatingClass);
219259

220260
return $scope;
221261
}
@@ -230,11 +270,8 @@ private function preprocessScope(MutatingScope $scope): Scope
230270
$scope = $scope->doNotTreatPhpDocTypesAsCertain();
231271
}
232272

233-
foreach ($this->truthyValueExprs as $expr) {
234-
$scope = $scope->filterByTruthyValue($expr);
235-
}
236-
foreach ($this->falseyValueExprs as $expr) {
237-
$scope = $scope->filterByFalseyValue($expr);
273+
foreach ($this->scopeOps as $op) {
274+
$scope = $op($scope);
238275
}
239276

240277
return $scope;
@@ -247,8 +284,7 @@ public function pushInFunctionCall($reflection, ?ParameterReflection $parameter,
247284
{
248285
/** @var self $scope */
249286
$scope = parent::pushInFunctionCall($reflection, $parameter, $rememberTypes);
250-
$scope->truthyValueExprs = $this->truthyValueExprs;
251-
$scope->falseyValueExprs = $this->falseyValueExprs;
287+
$scope->scopeOps = $this->scopeOps;
252288

253289
return $scope;
254290
}
@@ -260,8 +296,7 @@ public function popInFunctionCall(): self
260296

261297
/** @var self $scope */
262298
$scope = parent::popInFunctionCall();
263-
$scope->truthyValueExprs = $this->truthyValueExprs;
264-
$scope->falseyValueExprs = $this->falseyValueExprs;
299+
$scope->scopeOps = $this->scopeOps;
265300

266301
return $scope;
267302
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use LogicException;
6+
use PhpParser\Node;
7+
use PhpParser\Node\Expr\FuncCall;
8+
use PhpParser\Node\Expr\Variable;
9+
use PHPStan\Rules\IdentifierRuleError;
10+
use PHPStan\Rules\Rule;
11+
use PHPStan\Rules\RuleErrorBuilder;
12+
use PHPStan\TrinaryLogic;
13+
use PHPStan\Type\Constant\ConstantStringType;
14+
use PHPStan\Type\Type;
15+
use PHPStan\Type\VerbosityLevel;
16+
use function count;
17+
use function is_string;
18+
use function sprintf;
19+
20+
/**
21+
* Exercises scope-deriving mutators (assignExpression(), assignVariable())
22+
* on the scope a rule received, the way third-party rules do: deriving a
23+
* locally modified scope and expecting getType() on it to see the
24+
* modification — including combined with filterByTruthyValue() and after an
25+
* earlier getType() call already answered from the unmodified scope.
26+
*
27+
* @implements Rule<FuncCall>
28+
*/
29+
class NodeCallbackScopeDerivedOpsRule implements Rule
30+
{
31+
32+
public function getNodeType(): string
33+
{
34+
return FuncCall::class;
35+
}
36+
37+
public function processNode(Node $node, Scope $scope): array
38+
{
39+
if (!$node->name instanceof Node\Name) {
40+
return [];
41+
}
42+
43+
if (!$scope instanceof MutatingScope) {
44+
throw new LogicException('Expected MutatingScope');
45+
}
46+
47+
$functionName = $node->name->getLast();
48+
$args = $node->getArgs();
49+
if (count($args) === 0) {
50+
return [];
51+
}
52+
53+
$var = $args[count($args) - 1]->value;
54+
if (!$var instanceof Variable || !is_string($var->name)) {
55+
return [];
56+
}
57+
58+
$assignedType = new ConstantStringType('assigned');
59+
60+
if ($functionName === 'probeAssignExpression') {
61+
$assignedScope = $scope->assignExpression($var, $assignedType, $assignedType);
62+
63+
return [$this->describe('assigned', $assignedScope->getType($var))];
64+
}
65+
66+
if ($functionName === 'probeAssignExpressionAfterRead') {
67+
$before = $scope->getType($var);
68+
$assignedScope = $scope->assignExpression($var, $assignedType, $assignedType);
69+
70+
return [$this->describe(sprintf(
71+
'before %s, after',
72+
$before->describe(VerbosityLevel::precise()),
73+
), $assignedScope->getType($var))];
74+
}
75+
76+
if ($functionName === 'probeAssignVariable') {
77+
$assignedScope = $scope->assignVariable($var->name, $assignedType, $assignedType, TrinaryLogic::createYes());
78+
79+
return [$this->describe('assigned', $assignedScope->getType($var))];
80+
}
81+
82+
if ($functionName === 'probeFilterThenAssign') {
83+
if (count($args) < 2) {
84+
return [];
85+
}
86+
87+
$filteredScope = $scope->filterByTruthyValue($args[0]->value);
88+
$filteredThenAssignedScope = $filteredScope->assignExpression($var, $assignedType, $assignedType);
89+
90+
return [$this->describe(sprintf(
91+
'filtered %s, assigned',
92+
$filteredScope->getType($var)->describe(VerbosityLevel::precise()),
93+
), $filteredThenAssignedScope->getType($var))];
94+
}
95+
96+
return [];
97+
}
98+
99+
private function describe(string $prefix, Type $type): IdentifierRuleError
100+
{
101+
return RuleErrorBuilder::message(sprintf(
102+
'%s: %s',
103+
$prefix,
104+
$type->describe(VerbosityLevel::precise()),
105+
))->identifier('tests.nodeCallbackScopeDerivedOps')->build();
106+
}
107+
108+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Rules\Rule;
6+
use PHPStan\Testing\RuleTestCase;
7+
8+
/**
9+
* @extends RuleTestCase<NodeCallbackScopeDerivedOpsRule>
10+
*/
11+
class NodeCallbackScopeDerivedOpsRuleTest extends RuleTestCase
12+
{
13+
14+
protected function getRule(): Rule
15+
{
16+
return new NodeCallbackScopeDerivedOpsRule();
17+
}
18+
19+
public function testDerivedOps(): void
20+
{
21+
$this->analyse([__DIR__ . '/data/node-callback-scope-derived-ops.php'], [
22+
[
23+
'assigned: \'assigned\'',
24+
23,
25+
],
26+
[
27+
'before string, after: \'assigned\'',
28+
28,
29+
],
30+
[
31+
'assigned: \'assigned\'',
32+
33,
33+
],
34+
[
35+
'filtered string, assigned: \'assigned\'',
36+
38,
37+
],
38+
]);
39+
}
40+
41+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace NodeCallbackScopeDerivedOps;
4+
5+
function probeAssignExpression(string $subject): void
6+
{
7+
}
8+
9+
function probeAssignExpressionAfterRead(string $subject): void
10+
{
11+
}
12+
13+
function probeAssignVariable(string $subject): void
14+
{
15+
}
16+
17+
function probeFilterThenAssign(bool $condition, ?string $subject): void
18+
{
19+
}
20+
21+
function testAssignExpression(string $key): void
22+
{
23+
probeAssignExpression($key);
24+
}
25+
26+
function testAssignExpressionAfterRead(string $key): void
27+
{
28+
probeAssignExpressionAfterRead($key);
29+
}
30+
31+
function testAssignVariable(string $key): void
32+
{
33+
probeAssignVariable($key);
34+
}
35+
36+
function testFilterThenAssign(?string $key): void
37+
{
38+
probeFilterThenAssign($key !== null, $key);
39+
}

0 commit comments

Comments
 (0)