33namespace PHPStan \Analyser \ExprHandler \Helper ;
44
55use Closure ;
6+ use PhpParser \Node ;
67use PhpParser \Node \Expr ;
78use PhpParser \Node \Expr \ArrayDimFetch ;
89use PhpParser \Node \Expr \List_ ;
1112use PhpParser \Node \Expr \Variable ;
1213use PHPStan \Analyser \EnsuredNonNullabilityResult ;
1314use PHPStan \Analyser \EnsuredNonNullabilityResultExpression ;
15+ use PHPStan \Analyser \ExpressionResult ;
1416use PHPStan \Analyser \MutatingScope ;
1517use PHPStan \Analyser \PerFileAnalysisResettable ;
1618use PHPStan \DependencyInjection \AutowiredService ;
1719use PHPStan \Node \Printer \ExprPrinter ;
1820use PHPStan \TrinaryLogic ;
1921use PHPStan \Type \Type ;
2022use PHPStan \Type \TypeCombinator ;
23+ use function array_merge ;
2124use function array_pop ;
2225use function count ;
26+ use function get_class ;
27+ use function is_string ;
2328
2429#[AutowiredService]
2530final 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
0 commit comments