Skip to content

Commit 765f907

Browse files
ondrejmirtesclaude
andcommitted
Collect what a function assigns to a variable its @var tag declares
A `@var` tag above `$x = null`, `$x = []`, a scalar, `new Foo()` or `static $x` declares what the variable holds for the rest of the function. VarTagUsagesInference finds these declarations among the top-level statements of a body and the writes to their variables after them - assignments, compound assignments like `.=`, increments and decrements, offset writes like `$a[50] = ...` and destructuring, also in a closure that uses the variable by reference. At the end of the two-pass walk each write is evaluated again with the variable narrowed to the tag's type, so a write is judged on its own - one after an earlier wrong write, or inside a loop, is not coloured by it - while what the body knows about the variable's offsets (an element initialised by `??=` before its fields are written) stands. VarTagUsagesNode carries the variable's type after the write for a rule to compare. For a generic `new`, the driver walks the body once more without the tag - from the first such declaration on, re-walking only the statements that read what changed - and the node carries the declared value with the template arguments that walk infers (Collection<int> from `$c->add(1)`), both generalized like inferred ones and precise. A statement invoking a closure whose by-ref uses hold a changed variable reads that variable too - the closure runs there. Behind the varTagsReflectUsages bleeding edge toggle. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VpbB99tJfUmeArX74xqvHv
1 parent 8dd80bc commit 765f907

23 files changed

Lines changed: 2872 additions & 807 deletions

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ parameters:
3030
unresolvedTemplateArguments: true
3131
closureSignaturesFromUsages: true
3232
staticVariablesFromUsages: true
33+
varTagsReflectUsages: true
3334
unusedVariable: true
3435
unusedParameters: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ parameters:
6262
unresolvedTemplateArguments: false
6363
closureSignaturesFromUsages: false
6464
staticVariablesFromUsages: false
65+
varTagsReflectUsages: false
6566
unusedVariable: false
6667
unusedParameters: false
6768
fileExtensions:

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ parametersSchema:
5959
unresolvedTemplateArguments: bool()
6060
closureSignaturesFromUsages: bool()
6161
staticVariablesFromUsages: bool()
62+
varTagsReflectUsages: bool()
6263
unusedVariable: bool()
6364
unusedParameters: bool()
6465
])

‎src/Analyser/ExprHandler/AssignHandler.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
use PHPStan\Analyser\ExprHandler\Helper\VirtualExprResultHelper;
3939
use PHPStan\Analyser\Generics\TemplateArgumentConstraints;
4040
use PHPStan\Analyser\Generics\TemplateArgumentObserver;
41+
use PHPStan\Analyser\Generics\VarTagUsagesInference;
4142
use PHPStan\Analyser\ImpurePoint;
4243
use PHPStan\Analyser\InternalThrowPoint;
4344
use PHPStan\Analyser\MutatingScope;
@@ -142,6 +143,7 @@ public function __construct(
142143
private PropertyHookThrowPointsResolver $propertyHookThrowPointsResolver,
143144
private StatementsHandler $statementsHandler,
144145
private ArrayUnpackingHelper $arrayUnpackingHelper,
146+
private VarTagUsagesInference $varTagUsagesInference,
145147
)
146148
{
147149
}
@@ -258,7 +260,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
258260
}
259261

260262
$vars = $nodeScopeResolver->getAssignedVariables($expr->var);
261-
if (count($vars) > 0) {
263+
// the walk that finds what the variable takes without its @var tag
264+
// (see VarTagUsagesInference) leaves the tag out
265+
if (count($vars) > 0 && !$this->varTagUsagesInference->isSuppressed($scope, $stmt)) {
262266
$varChangedScope = false;
263267
$scope = $this->varAnnotationProcessor->processVarAnnotation($scope, $vars, $stmt, $varChangedScope);
264268
if (!$varChangedScope) {

‎src/Analyser/Generics/TemplateArgumentFrame.php‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ public static function returnTypeOfCall(ParametersAcceptor $acceptor, MutatingSc
6666
* @param bool $observingClosures the template arguments are resolved, the closure signatures observed again
6767
* @param array<int, array{Expr\Closure, int, bool}> $byRefSites spl_object_id() of the closure node => the node, its statement index, whether every invocation was seen
6868
* @param array<int, array{Expr\Variable, Type, Type}> $staticVariableTypes spl_object_id() of a `static` variable node => the node, its phpdoc and native type - see StaticVariableInference
69+
* @param array<int, Node\Stmt> $suppressedVarTagStatements spl_object_id() of a statement => the statement whose @var tags the walk does not apply - see VarTagUsagesInference
6970
*/
7071
public function __construct(
7172
private readonly ?self $parent,
@@ -77,10 +78,39 @@ public function __construct(
7778
private readonly bool $observingClosures = false,
7879
private readonly array $byRefSites = [],
7980
private readonly array $staticVariableTypes = [],
81+
private readonly array $suppressedVarTagStatements = [],
8082
)
8183
{
8284
}
8385

86+
public function isVarTagSuppressed(Node\Stmt $stmt): bool
87+
{
88+
return ($this->suppressedVarTagStatements[spl_object_id($stmt)] ?? null) === $stmt;
89+
}
90+
91+
/**
92+
* The frame of a walk that does not apply the @var tags of the statements;
93+
* the statements are walked again.
94+
*
95+
* @param array<int, Node\Stmt> $suppressedVarTagStatements
96+
* @param array<int, true> $statementIndexes
97+
*/
98+
public function withSuppressedVarTags(array $suppressedVarTagStatements, array $statementIndexes): self
99+
{
100+
return new self(
101+
$this->parent,
102+
$this->resolutions,
103+
$this->siteStatementIndexes + $statementIndexes,
104+
$this->closureSignatureBody,
105+
$this->closureSignatureStmts,
106+
$this->settledClosureSites,
107+
$this->observingClosures,
108+
$this->byRefSites,
109+
$this->staticVariableTypes,
110+
$suppressedVarTagStatements,
111+
);
112+
}
113+
84114
/**
85115
* @return array{Type, Type}|null
86116
*/
@@ -113,6 +143,7 @@ public function withStaticVariableTypes(array $staticVariableTypes, array $state
113143
$this->observingClosures,
114144
$this->byRefSites,
115145
$staticVariableTypes,
146+
$this->suppressedVarTagStatements,
116147
);
117148
}
118149

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser\Generics;
4+
5+
use PhpParser\Node;
6+
use PhpParser\Node\Expr;
7+
use PHPStan\Analyser\MutatingScope;
8+
use PHPStan\DependencyInjection\AutowiredParameter;
9+
use PHPStan\DependencyInjection\AutowiredService;
10+
use PHPStan\Turbo\ShadowedByTurboExtension;
11+
use function array_fill_keys;
12+
use function array_keys;
13+
use function array_pop;
14+
use function count;
15+
use function is_array;
16+
use function is_string;
17+
use function preg_match;
18+
use function spl_object_id;
19+
20+
/**
21+
* Finds the `@var` declarations of a function-like body whose type the
22+
* assigned value does not decide - `null`, `[]`, a scalar, a `new` of a
23+
* generic class, and any `static` variable - and the writes to those
24+
* variables after them. Such a tag is the declared type of the variable:
25+
* every value the body writes to it has to fit, and the value of a generic
26+
* `new` has to fit with the template arguments the body infers when the tag
27+
* is left out (see StatementsHandler::processBodyStmtNodesTwoPass()).
28+
* VarTagReflectsUsagesRule checks both.
29+
*/
30+
#[AutowiredService]
31+
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/VarTagUsagesInference.cpp')]
32+
final class VarTagUsagesInference
33+
{
34+
35+
private const DECLARATIONS_ATTRIBUTE = 'varTagUsagesDeclarations';
36+
37+
private const WRITES_ATTRIBUTE = 'varTagUsagesWrites';
38+
39+
public function __construct(
40+
#[AutowiredParameter(ref: '%featureToggles.varTagsReflectUsages%')]
41+
private bool $enabled,
42+
)
43+
{
44+
}
45+
46+
/**
47+
* The top-level statements `/** @var T $x *\/ $x = <value>;` of the body
48+
* whose value does not decide the type and `/** @var T *\/ static $x;`,
49+
* with their index and the variable's name.
50+
*
51+
* @param Node\Stmt[] $stmts
52+
* @return list<array{Node\Stmt, int, string}>
53+
*/
54+
public function getDeclarations(Node $functionLike, array $stmts): array
55+
{
56+
if (!$this->enabled) {
57+
return [];
58+
}
59+
60+
/** @var list<array{Node\Stmt, int, string}>|null $cached */
61+
$cached = $functionLike->getAttribute(self::DECLARATIONS_ATTRIBUTE);
62+
if ($cached !== null) {
63+
return $cached;
64+
}
65+
66+
$declarations = [];
67+
foreach ($stmts as $index => $stmt) {
68+
$name = self::getDeclaredVariableName($stmt);
69+
if ($name === null) {
70+
continue;
71+
}
72+
$docComment = $stmt->getDocComment();
73+
if ($docComment === null || preg_match('~@(?:phpstan-|psalm-)?var\s~', $docComment->getText()) !== 1) {
74+
continue;
75+
}
76+
$declarations[] = [$stmt, $index, $name];
77+
}
78+
$functionLike->setAttribute(self::DECLARATIONS_ATTRIBUTE, $declarations);
79+
80+
return $declarations;
81+
}
82+
83+
/**
84+
* The writes to the declared variables after their declarations: the
85+
* assignments, compound assignments, increments and decrements of the
86+
* variable, of an offset in it, or destructuring into it - also in a
87+
* closure that uses the variable by reference - with the key of the
88+
* declaration in getDeclarations() and the variable's name.
89+
*
90+
* @param Node\Stmt[] $stmts
91+
* @return list<array{Expr, int, string}>
92+
*/
93+
public function getWrites(Node $functionLike, array $stmts): array
94+
{
95+
$declarations = $this->getDeclarations($functionLike, $stmts);
96+
if ($declarations === []) {
97+
return [];
98+
}
99+
100+
/** @var list<array{Expr, int, string}>|null $cached */
101+
$cached = $functionLike->getAttribute(self::WRITES_ATTRIBUTE);
102+
if ($cached !== null) {
103+
return $cached;
104+
}
105+
106+
$declarationsByName = [];
107+
$declaringAssigns = [];
108+
foreach ($declarations as $key => [$stmt, , $name]) {
109+
$declarationsByName[$name][] = [$stmt->getEndFilePos(), $key];
110+
if (!$stmt instanceof Node\Stmt\Expression) {
111+
continue;
112+
}
113+
$declaringAssigns[spl_object_id($stmt->expr)] = true;
114+
}
115+
$writes = [];
116+
$stack = [];
117+
$names = array_fill_keys(array_keys($declarationsByName), true);
118+
foreach ($stmts as $stmt) {
119+
$stack[] = [$stmt, $names];
120+
}
121+
while (count($stack) > 0) {
122+
[$node, $visibleNames] = array_pop($stack);
123+
if ($node instanceof Expr\Closure) {
124+
// its own variables, except those it uses by reference
125+
$byRefNames = [];
126+
foreach ($node->uses as $use) {
127+
if (!$use->byRef || !is_string($use->var->name) || !isset($visibleNames[$use->var->name])) {
128+
continue;
129+
}
130+
$byRefNames[$use->var->name] = true;
131+
}
132+
if ($byRefNames === []) {
133+
continue;
134+
}
135+
foreach ($node->stmts as $closureStmt) {
136+
$stack[] = [$closureStmt, $byRefNames];
137+
}
138+
continue;
139+
}
140+
if ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike) {
141+
continue;
142+
}
143+
$target = null;
144+
if (
145+
$node instanceof Expr\Assign
146+
|| $node instanceof Expr\AssignOp
147+
|| $node instanceof Expr\PreInc
148+
|| $node instanceof Expr\PreDec
149+
|| $node instanceof Expr\PostInc
150+
|| $node instanceof Expr\PostDec
151+
) {
152+
$target = $node->var;
153+
}
154+
if ($target !== null && !isset($declaringAssigns[spl_object_id($node)])) {
155+
foreach (self::getWrittenNames($target) as $name) {
156+
if (!isset($visibleNames[$name])) {
157+
continue;
158+
}
159+
$declarationKey = null;
160+
foreach ($declarationsByName[$name] as [$declarationEnd, $key]) {
161+
if ($declarationEnd >= $node->getStartFilePos()) {
162+
continue;
163+
}
164+
$declarationKey = $key;
165+
}
166+
if ($declarationKey === null) {
167+
continue;
168+
}
169+
$writes[] = [$node, $declarationKey, $name];
170+
}
171+
}
172+
foreach ($node->getSubNodeNames() as $subNodeName) {
173+
$subNode = $node->$subNodeName;
174+
if ($subNode instanceof Node) {
175+
$stack[] = [$subNode, $visibleNames];
176+
} elseif (is_array($subNode)) {
177+
foreach ($subNode as $item) {
178+
if (!$item instanceof Node) {
179+
continue;
180+
}
181+
$stack[] = [$item, $visibleNames];
182+
}
183+
}
184+
}
185+
}
186+
$functionLike->setAttribute(self::WRITES_ATTRIBUTE, $writes);
187+
188+
return $writes;
189+
}
190+
191+
/**
192+
* The variables a write target writes: the variable, an offset in it, or
193+
* the destructured ones.
194+
*
195+
* @return list<string>
196+
*/
197+
private static function getWrittenNames(Expr $target): array
198+
{
199+
while ($target instanceof Expr\ArrayDimFetch) {
200+
$target = $target->var;
201+
}
202+
if ($target instanceof Expr\Variable) {
203+
return is_string($target->name) ? [$target->name] : [];
204+
}
205+
if (!$target instanceof Expr\List_ && !$target instanceof Expr\Array_) {
206+
return [];
207+
}
208+
209+
$names = [];
210+
foreach ($target->items as $item) {
211+
if ($item === null) {
212+
continue;
213+
}
214+
foreach (self::getWrittenNames($item->value) as $name) {
215+
$names[] = $name;
216+
}
217+
}
218+
219+
return $names;
220+
}
221+
222+
/** Whether the walk leaves the @var tags of the statement out. */
223+
public function isSuppressed(MutatingScope $scope, Node\Stmt $stmt): bool
224+
{
225+
$frame = $scope->getCurrentTemplateArgumentFrame();
226+
227+
return $frame !== null && $frame->isVarTagSuppressed($stmt);
228+
}
229+
230+
private static function getDeclaredVariableName(Node\Stmt $stmt): ?string
231+
{
232+
if ($stmt instanceof Node\Stmt\Static_) {
233+
// what the previous calls left decides the type, not the default
234+
if (count($stmt->vars) !== 1 || !is_string($stmt->vars[0]->var->name)) {
235+
return null;
236+
}
237+
238+
return $stmt->vars[0]->var->name;
239+
}
240+
241+
if (
242+
!$stmt instanceof Node\Stmt\Expression
243+
|| !$stmt->expr instanceof Expr\Assign
244+
|| !$stmt->expr->var instanceof Expr\Variable
245+
|| !is_string($stmt->expr->var->name)
246+
|| !self::isUndecidingValue($stmt->expr->expr)
247+
) {
248+
return null;
249+
}
250+
251+
return $stmt->expr->var->name;
252+
}
253+
254+
private static function isUndecidingValue(Expr $expr): bool
255+
{
256+
return $expr instanceof Expr\ConstFetch
257+
|| $expr instanceof Node\Scalar
258+
|| ($expr instanceof Expr\Array_ && $expr->items === [])
259+
|| $expr instanceof Expr\New_;
260+
}
261+
262+
}

0 commit comments

Comments
 (0)