Skip to content

Commit be01378

Browse files
ondrejmirtesclaude
andcommitted
Device non-nullability of unpriceable chain links at the walk's completion
isset()/empty()/?? ensure the links of their operand's chain non-null before walking it. A link the scope cannot price from its state - a call with arguments, a ternary, a fetch spine over one - had no type ahead of the walk, so the ensure priced the node on demand: a second walk of a real node, and the guard's last non-nullability site. Such a link is now registered as pending on the ensure frame and deviced when its own walk completes, from the type that walk produced: the result's after-scope tracks it as non-null and its value is pinned to the ensured type, which is what a link walked on an ensured-ahead scope answered. The late device joins the frame's originals for the nullsafe handlers and is reverted with the frame. Links the scope does price from state (variables, fetch spines, argument-less instance calls, constants) keep the ahead-of-walk device; receivers that are never null (new, array and closure literals, scalars) skip the ensure altogether. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R7pqAkCx4xP6WYxBo2nMJE
1 parent 040f65e commit be01378

5 files changed

Lines changed: 253 additions & 5 deletions

File tree

‎src/Analyser/ExprHandler/Helper/NonNullabilityHelper.php‎

Lines changed: 148 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace PHPStan\Analyser\ExprHandler\Helper;
44

55
use Closure;
6+
use PhpParser\Node;
67
use PhpParser\Node\Expr;
78
use PhpParser\Node\Expr\ArrayDimFetch;
89
use PhpParser\Node\Expr\List_;
@@ -11,15 +12,19 @@
1112
use PhpParser\Node\Expr\Variable;
1213
use PHPStan\Analyser\EnsuredNonNullabilityResult;
1314
use PHPStan\Analyser\EnsuredNonNullabilityResultExpression;
15+
use PHPStan\Analyser\ExpressionResult;
1416
use PHPStan\Analyser\MutatingScope;
1517
use PHPStan\Analyser\PerFileAnalysisResettable;
1618
use PHPStan\DependencyInjection\AutowiredService;
1719
use PHPStan\Node\Printer\ExprPrinter;
1820
use PHPStan\TrinaryLogic;
1921
use PHPStan\Type\Type;
2022
use PHPStan\Type\TypeCombinator;
23+
use function array_merge;
2124
use function array_pop;
2225
use function count;
26+
use function get_class;
27+
use function is_string;
2328

2429
#[AutowiredService]
2530
final class NonNullabilityHelper implements PerFileAnalysisResettable
@@ -37,6 +42,25 @@ final class NonNullabilityHelper implements PerFileAnalysisResettable
3742
*/
3843
private array $activeEnsures = [];
3944

45+
/**
46+
* Chain links an ensure could not device ahead of the walk - the scope
47+
* cannot price them from its state (isPricedFromState()) - keyed by
48+
* printed expression, one frame per active ensure. applyPendingEnsure()
49+
* devices such a link when its walk completes, from the type the walk
50+
* produced.
51+
*
52+
* @var list<array{keys: array<string, true>, classes: array<class-string<Expr>, true>}>
53+
*/
54+
private array $pendingEnsures = [];
55+
56+
/**
57+
* The devices applied at walk completion, per frame - reverted together
58+
* with the frame's ahead-of-walk devices.
59+
*
60+
* @var list<list<EnsuredNonNullabilityResultExpression>>
61+
*/
62+
private array $lateEnsures = [];
63+
4064
public function __construct(private ExprPrinter $exprPrinter)
4165
{
4266
}
@@ -49,6 +73,8 @@ public function __construct(private ExprPrinter $exprPrinter)
4973
public function resetFileAnalysisState(): void
5074
{
5175
$this->activeEnsures = [];
76+
$this->pendingEnsures = [];
77+
$this->lateEnsures = [];
5278
}
5379

5480
/**
@@ -79,7 +105,10 @@ public function ensureShallowNonNullability(MutatingScope $scope, MutatingScope
79105
return $result;
80106
}
81107

82-
private function pushActiveEnsure(EnsuredNonNullabilityResult $result): void
108+
/**
109+
* @param array{keys: array<string, true>, classes: array<class-string<Expr>, true>} $pending
110+
*/
111+
private function pushActiveEnsure(EnsuredNonNullabilityResult $result, array $pending = ['keys' => [], 'classes' => []]): void
83112
{
84113
$originals = [];
85114
foreach ($result->getSpecifiedExpressions() as $specifiedExpression) {
@@ -89,6 +118,96 @@ private function pushActiveEnsure(EnsuredNonNullabilityResult $result): void
89118
];
90119
}
91120
$this->activeEnsures[] = $originals;
121+
$this->pendingEnsures[] = $pending;
122+
$this->lateEnsures[] = [];
123+
}
124+
125+
/**
126+
* Whether the scope prices the link from its state alone - a variable
127+
* read, a fetch spine over such reads, a constant - so an ensure can
128+
* device it ahead of the walk. Any other link (a call, a ternary, ...)
129+
* has no type before its walk and is deviced when the walk completes:
130+
* the state answer for an argument-less call would be its declared
131+
* return type, which lacks what the walk resolves.
132+
*/
133+
private function isPricedFromState(Expr $expr, MutatingScope $scope): bool
134+
{
135+
if ($expr instanceof Variable) {
136+
return is_string($expr->name);
137+
}
138+
if ($scope->hasExpressionType($expr)->yes()) {
139+
return true;
140+
}
141+
if ($expr instanceof ArrayDimFetch) {
142+
return $expr->dim !== null
143+
&& $this->isPricedFromState($expr->var, $scope)
144+
&& $this->isPricedFromState($expr->dim, $scope);
145+
}
146+
if ($expr instanceof PropertyFetch || $expr instanceof Expr\NullsafePropertyFetch) {
147+
return $expr->name instanceof Node\Identifier && $this->isPricedFromState($expr->var, $scope);
148+
}
149+
if ($expr instanceof StaticPropertyFetch) {
150+
return $expr->name instanceof Node\VarLikeIdentifier
151+
&& ($expr->class instanceof Node\Name || $this->isPricedFromState($expr->class, $scope));
152+
}
153+
return $expr instanceof Node\Scalar\String_
154+
|| $expr instanceof Node\Scalar\Int_
155+
|| $expr instanceof Node\Scalar\Float_
156+
|| $expr instanceof Expr\ConstFetch
157+
|| ($expr instanceof Expr\ClassConstFetch && $expr->class instanceof Node\Name && $expr->name instanceof Node\Identifier);
158+
}
159+
160+
/**
161+
* Devices a chain link ensureNonNullability() left pending, now that its
162+
* walk produced a type: the link's scopes track it as non-null, so its
163+
* result answers what a link walked on an ensured-ahead scope answered.
164+
* Any other node passes through untouched.
165+
*/
166+
public function applyPendingEnsure(Expr $expr, ExpressionResult $result): ExpressionResult
167+
{
168+
if ($this->pendingEnsures === []) {
169+
return $result;
170+
}
171+
172+
$key = null;
173+
for ($i = count($this->pendingEnsures) - 1; $i >= 0; $i--) {
174+
// the node class screens the common case before the node is printed
175+
if (!isset($this->pendingEnsures[$i]['classes'][get_class($expr)])) {
176+
continue;
177+
}
178+
$key ??= $this->exprPrinter->printExpr($expr);
179+
if (!isset($this->pendingEnsures[$i]['keys'][$key])) {
180+
continue;
181+
}
182+
183+
unset($this->pendingEnsures[$i]['keys'][$key]);
184+
$scope = $result->getScope();
185+
if ($scope->hasExpressionType($expr)->yes()) {
186+
// an earlier link printing the same way installed the device
187+
return $result;
188+
}
189+
190+
$type = $result->getType();
191+
if ($type->isNull()->yes()) {
192+
return $result;
193+
}
194+
$typeWithoutNull = TypeCombinator::removeNull($type);
195+
if ($type->equals($typeWithoutNull)) {
196+
return $result;
197+
}
198+
199+
$nativeType = $result->getNativeType();
200+
$nativeTypeWithoutNull = TypeCombinator::removeNull($nativeType);
201+
$this->activeEnsures[$i][$key] = [$type, $nativeType];
202+
$this->lateEnsures[$i][] = new EnsuredNonNullabilityResultExpression($expr, $type, $nativeType, TrinaryLogic::createYes());
203+
204+
return $result->onNonNullabilityDevicedScopes(
205+
$result->getBeforeScope()->specifyExpressionType($expr, $typeWithoutNull, $nativeTypeWithoutNull, TrinaryLogic::createYes()),
206+
$scope->specifyExpressionType($expr, $typeWithoutNull, $nativeTypeWithoutNull, TrinaryLogic::createYes()),
207+
);
208+
}
209+
210+
return $result;
92211
}
93212

94213
private function doEnsureShallowNonNullability(MutatingScope $scope, MutatingScope $originalScope, Expr $exprToSpecify): EnsuredNonNullabilityResult
@@ -159,8 +278,19 @@ private function doEnsureShallowNonNullability(MutatingScope $scope, MutatingSco
159278
public function ensureNonNullability(MutatingScope $scope, Expr $expr): EnsuredNonNullabilityResult
160279
{
161280
$specifiedExpressions = [];
281+
$pending = ['keys' => [], 'classes' => []];
162282
$originalScope = $scope;
163-
$scope = $this->lookForExpressionCallback($scope, $expr, function ($scope, $expr) use (&$specifiedExpressions, $originalScope) {
283+
$scope = $this->lookForExpressionCallback($scope, $expr, function ($scope, $expr) use (&$specifiedExpressions, &$pending, $originalScope) {
284+
// a link the scope cannot price from its state has no type before
285+
// its walk: device it when the walk completes instead of pricing
286+
// the node ahead of its turn
287+
if (!$this->isPricedFromState($expr, $scope)) {
288+
$pending['keys'][$this->exprPrinter->printExpr($expr)] = true;
289+
$pending['classes'][get_class($expr)] = true;
290+
291+
return $scope;
292+
}
293+
164294
$result = $this->doEnsureShallowNonNullability($scope, $originalScope, $expr);
165295
foreach ($result->getSpecifiedExpressions() as $specifiedExpression) {
166296
$specifiedExpressions[] = $specifiedExpression;
@@ -169,7 +299,7 @@ public function ensureNonNullability(MutatingScope $scope, Expr $expr): EnsuredN
169299
}, false);
170300

171301
$result = new EnsuredNonNullabilityResult($scope, $specifiedExpressions);
172-
$this->pushActiveEnsure($result);
302+
$this->pushActiveEnsure($result, $pending);
173303

174304
return $result;
175305
}
@@ -180,7 +310,9 @@ public function ensureNonNullability(MutatingScope $scope, Expr $expr): EnsuredN
180310
public function revertNonNullability(MutatingScope $scope, array $specifiedExpressions): MutatingScope
181311
{
182312
array_pop($this->activeEnsures);
183-
foreach ($specifiedExpressions as $specifiedExpressionResult) {
313+
array_pop($this->pendingEnsures);
314+
$lateEnsures = array_pop($this->lateEnsures) ?? [];
315+
foreach (array_merge($specifiedExpressions, $lateEnsures) as $specifiedExpressionResult) {
184316
if ($specifiedExpressionResult->getCertainty()->no()) {
185317
$scope = $scope->invalidateExpression($specifiedExpressionResult->getExpression());
186318
continue;
@@ -205,7 +337,18 @@ private function lookForExpressionCallback(MutatingScope $scope, Expr $expr, Clo
205337
// links non-null lets it be walked without spurious "possibly null" noise,
206338
// but the operand's own value must keep its real (nullable) type - that is
207339
// the type the isset/empty/?? verdict and narrowing read from its result.
208-
if ($includeExpr && (!$expr instanceof ArrayDimFetch || $expr->dim !== null)) {
340+
// a receiver the scope can never track and that is never null (a `new`,
341+
// an array/closure literal, a scalar) has nothing to ensure - and reading
342+
// its state would have to walk a node not processed yet
343+
if (
344+
$includeExpr
345+
&& (!$expr instanceof ArrayDimFetch || $expr->dim !== null)
346+
&& !$expr instanceof Expr\New_
347+
&& !$expr instanceof Expr\Array_
348+
&& !$expr instanceof Expr\Closure
349+
&& !$expr instanceof Expr\ArrowFunction
350+
&& !$expr instanceof Node\Scalar
351+
) {
209352
$scope = $callback($scope, $expr);
210353
}
211354

‎src/Analyser/ExpressionResult.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,28 @@ public function atAskPosition(MutatingScope $scope): self
742742
return $clone;
743743
}
744744

745+
/**
746+
* This result as if its walk had run on the given deviced scopes - the
747+
* ones a non-nullability ensure applied at the walk's completion tracks
748+
* the expression non-null on. The own type stays untouched: a read on the
749+
* deviced before-scope answers the tracked (non-null) holder, exactly like
750+
* a walk on an ensured-ahead scope did, while getTypeOnScope() on a scope
751+
* without the device (a rule's) still answers the expression's real,
752+
* nullable type. The scope memos derive from the deviced scopes on demand.
753+
*/
754+
public function onNonNullabilityDevicedScopes(MutatingScope $beforeScope, MutatingScope $scope): self
755+
{
756+
$clone = clone $this;
757+
$clone->beforeScope = $beforeScope;
758+
$clone->scope = $scope;
759+
$clone->cachedType = null;
760+
$clone->cachedNativeType = null;
761+
$clone->truthyScope = null;
762+
$clone->falseyScope = null;
763+
764+
return $clone;
765+
}
766+
745767
/**
746768
* @return list<string>
747769
*/

‎src/Analyser/NodeScopeResolver.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
use PhpParser\NodeFinder;
3333
use PHPStan\Analyser\ExprHandler\AssignHandler;
3434
use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
35+
use PHPStan\Analyser\ExprHandler\Helper\NonNullabilityHelper;
3536
use PHPStan\Analyser\ExprHandler\Helper\VirtualExprResultHelper;
3637
use PHPStan\DependencyInjection\AutowiredExtensions;
3738
use PHPStan\DependencyInjection\AutowiredParameter;
@@ -145,6 +146,8 @@ class NodeScopeResolver
145146
*/
146147
private bool $consumeStoredExpressionResults = false;
147148

149+
private ?NonNullabilityHelper $nonNullabilityHelper = null;
150+
148151
/**
149152
* Engine-feeding gatherer frames (return statements, execution ends,
150153
* impure points, ...), innermost last. callNodeCallback() feeds every
@@ -251,6 +254,11 @@ public function setAnalysedFiles(array $files): void
251254
* wiping the per-file caches there forces the outer file to rebuild them -
252255
* closure types re-converge, narrowing memos recompute.
253256
*/
257+
private function getNonNullabilityHelper(): NonNullabilityHelper
258+
{
259+
return $this->nonNullabilityHelper ??= $this->container->getByType(NonNullabilityHelper::class);
260+
}
261+
254262
public function resetPerFileAnalysisState(): void
255263
{
256264
foreach ($this->perFileAnalysisResettables->getAll() as $resettableService) {
@@ -1310,6 +1318,10 @@ private function processExprNodeInternal(
13101318
$exprHandler = ExprHandlerRegistry::resolve($expr, $this->container);
13111319
if ($exprHandler !== null) {
13121320
$expressionResult = $exprHandler->processExpr($this, $stmt, $expr, $scope, $storage, $nodeCallback, $context);
1321+
// a chain link an enclosing isset/empty/?? could not device ahead
1322+
// of its walk (an untracked call) is deviced now, from the type
1323+
// the walk produced
1324+
$expressionResult = $this->getNonNullabilityHelper()->applyPendingEnsure($expr, $expressionResult);
13131325
$this->storeExpressionResult($storage, $expr, $expressionResult);
13141326
// The node's own callback fires AFTER its result is stored, with the
13151327
// scope captured before processing. Rules observe the same (scope,

‎tests/PHPStan/Rules/Variables/NullCoalesceRuleTest.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,4 +676,15 @@ public function testBug12780(): void
676676
$this->analyse([__DIR__ . '/data/bug-12780.php'], []);
677677
}
678678

679+
#[RequiresPhp('>= 8.2.0')]
680+
public function testReadonlyPropertyOnNullableReceiver(): void
681+
{
682+
$this->analyse([__DIR__ . '/data/null-coalesce-readonly-property-nullable-receiver.php'], [
683+
[
684+
'Property NullCoalesceReadonlyPropertyNullableReceiver\PluginMapping::$snippetName (string) on left side of ?? is not nullable.',
685+
57,
686+
],
687+
]);
688+
}
689+
679690
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php declare(strict_types = 1); // lint >= 8.2
2+
3+
namespace NullCoalesceReadonlyPropertyNullableReceiver;
4+
5+
readonly class PluginMapping
6+
{
7+
8+
public function __construct(public string $pluginName, public string $snippetName)
9+
{
10+
}
11+
12+
}
13+
14+
/**
15+
* @template TElement
16+
* @template TKey of array-key = array-key
17+
*/
18+
abstract class Collection
19+
{
20+
21+
/** @var array<TKey, TElement> */
22+
protected array $elements = [];
23+
24+
/**
25+
* @param TKey $key
26+
* @return TElement|null
27+
*/
28+
public function get($key)
29+
{
30+
return $this->elements[$key] ?? null;
31+
}
32+
33+
}
34+
35+
/**
36+
* @extends Collection<PluginMapping>
37+
*/
38+
class PluginMappingCollection extends Collection
39+
{
40+
41+
}
42+
43+
class TranslationConfig
44+
{
45+
46+
public function __construct(public readonly PluginMappingCollection $pluginMapping)
47+
{
48+
}
49+
50+
public function getMappedPluginName(string $pluginName): string
51+
{
52+
return $this->pluginMapping->get($pluginName)->snippetName ?? $pluginName;
53+
}
54+
55+
public function getMappedPluginNameNonNullReceiver(PluginMapping $mapping): string
56+
{
57+
return $mapping->snippetName ?? 'default';
58+
}
59+
60+
}

0 commit comments

Comments
 (0)