Skip to content

fix(loop): a foreach that is entered holds what an iteration ends with, at a continue too - #14418

Merged
orklah merged 1 commit into
vimeo:masterfrom
jirkace:fix/14262-foreach-continue-runs-once
Nov 21, 2026
Merged

orklah merged 1 commit into
vimeo:masterfrom
jirkace:fix/14262-foreach-continue-runs-once

Conversation

@jirkace

@jirkace jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

A foreach over a non-empty array whose body has a continue is treated as possibly running zero times, so a variable every iteration sets keeps its value from before the loop.

Before

/** @param non-empty-array<Flag> $items */
function withContinue(array $items): Flag {
    $last = null;
    foreach ($items as $item) {
        if ($last === null) {
            $last = $item;
            continue;
        }
        if (!$last->equals($item)) {
            return new Flag();
        }
    }
    return $last; // NullableReturnStatement, InvalidNullableReturnType
}

After

    return $last; // no issue

Fixes #14262

…h, at a continue too vimeo#14262

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • After a foreach that is always entered (a non-empty array), a variable defined before the loop holds what an iteration ends with, at the end of the body or at a continue, instead of being combined with its value before the loop. Before, this only held without a continue. New ForeachTest case (fails on master), with guards: a possibly empty array keeps the value before the loop (Flag|null), and a variable that only some iterations change stays the union (bool).
  • Only foreach (a loop without a condition): while/for/do keep combining with the parent context, as their exit condition narrows it (DoTest::doWhileWithContinueIsLeftWhenItsConditionIsFalse fails otherwise).
  • Existing test changed: ForeachTest::falseToBoolExplicitContinue expected bool for $a = false; foreach (["a", "b", "c"] as $tag) { $a = true; continue; }; it is true now, as the same loop without the continue already gives on master.
  • Self-analysis: the more precise types made six defensive checks of Psalm's own code redundant (RedundantCondition/TypeDoesNotContainType on emptiness checks after a loop over a non-empty array that adds an item on every path: UnaryPlusMinusAnalyzer, Clause, Populator::resolveTypeAliases, ClosedInheritanceToUnion, TypeExpander, TypeVariableResolver); they are removed in this PR. Users with such defensive checks will see the same new issues.
  • Benchmarks (local, psalm_full.xml, --threads=1, fresh master runs): laravel 28106 vs 28106, symfony 11820 vs 11820; one symfony message prints non-empty-array instead of array. Not run: the full suite (CI).

@github-actions

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 768 73.0 $\color{gray}{\textsf{-0.9\%}}$ 25 926 53 513 682
✅ symfony 3 606 201.8 $\color{gray}{\textsf{-0.6\%}}$ 50 607 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-1}}$ 98 402 1 528
✅ doctrine-orm 393 20.6 $\color{gray}{\textsf{+0.3\%}}$ 3 480 6 161 0
✅ psl 632 26.2 $\color{gray}{\textsf{+0.3\%}}$ 1 299 5 455 1
✅ phpunit 471 20.9 $\color{gray}{\textsf{-0.4\%}}$ 1 744 3 459 18
✅ php-parser 236 14.1 $\color{gray}{\textsf{+0.9\%}}$ 17 133 21 035 0
✅ tempest 905 36.9 5 042 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 10 502 $\color{green}{\textsf{-3}}$ 252
✅ amphp-amp 61 1.8 29 49 0
✅ webmozarts-assert 288 4.1 $\color{gray}{\textsf{+0.5\%}}$ 577 2 720 0
✅ guzzle-promises 56 1.8 $\color{gray}{\textsf{-0.6\%}}$ 154 427 2
✅ monolog 153 4.8 $\color{gray}{\textsf{-0.4\%}}$ 903 2 403 10
✅ drupal 4 851 180.8 $\color{gray}{\textsf{-0.1\%}}$ 97 526 169 112 583
Total 13 420 586.8 $\color{gray}{\textsf{-0.3\%}}$ 204 420 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-2}}$ 373 238 $\color{green}{\textsf{-3}}$ 3 076
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +20 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Thresholds apply per project, not to the total.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.
✅ symfony: issues +1 −1

Memory 3 606 → 3 606 MB (<0.1 %) · Wall 202.9 → 201.8 s (−0.6 %)

Issue type added removed
InvalidArgument 1 1

Added (1)

  • src/Symfony/Component/HttpFoundation/HeaderUtils.php:244 InvalidArgument (error): Argument 2 of implode expects array<array-key, null|object{__tostring()}|scalar>, but non-empty-array<int<0, max>|string, non-empty-list<string>|string> provided

Removed (1)

  • src/Symfony/Component/HttpFoundation/HeaderUtils.php:244 InvalidArgument (error): Argument 2 of implode expects array<array-key, null|object{__tostring()}|scalar>, but array<int<0, max>|string, non-empty-list<string>|string> provided
✅ tempest: issues +0 −1

Memory 905 → 905 MB (+0.0 %) · Wall 36.9 → 36.9 s (<0.1 %)

Weighted 10 505 → 10 502 (−3, −0.03 %): L3 −1

Issue type added removed
PossiblyNullArgument 0 1

Removed (1)

  • packages/view/src/Parser/TempestViewCompiler.php:409 PossiblyNullArgument (error): Argument 1 of Tempest\View\Parser\TempestViewCompiler::createLineMapEntry cannot be null, possibly null value provided

head 348efba · base 1552477 (merge-base) · workflow run

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 21, 2026
@orklah
orklah merged commit 96953a3 into vimeo:master Nov 21, 2026
71 of 72 checks passed
@orklah

orklah commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks @jirkace!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

foreach over a non-empty array loses "runs at least once" when the body has a continue

2 participants