Skip to content

fix(foreach): the iterated expression is analysed once for getIterator() - #14370

Merged
orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14297-foreach-coalesce-assign
Nov 22, 2026
Merged

orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14297-foreach-coalesce-assign

Conversation

@jirkace

@jirkace jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

foreach over an expression with side effects, such as ??=, reports RedundantCondition and TypeDoesNotContainType, because the virtual getIterator() call analyses the iterated expression a second time.

Before

final class Holder {
    private ?Items $items = null;

    public function names(): void {
        foreach (($this->items ??= new Items()) as $name) { // RedundantCondition: Type Items for $this->items is always isset
            echo $name;
        }
    }
}

After

        foreach (($this->items ??= new Items()) as $name) { // no issue

Fixes #14297

…r() vimeo#14297

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: unchanged

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 751 71.6 $\color{gray}{\textsf{+0.4\%}}$ 25 908 53 462 682
✅ symfony 3 600 188.8 $\color{gray}{\textsf{-0.3\%}}$ 50 611 98 405 1 528
✅ doctrine-orm 381 13.0 $\color{gray}{\textsf{-1.7\%}}$ 3 481 6 143 0
✅ psl 617 16.2 $\color{gray}{\textsf{-0.2\%}}$ 1 375 5 615 1
✅ phpunit 455 12.0 $\color{gray}{\textsf{-1.2\%}}$ 1 731 3 410 18
✅ php-parser 226 7.8 $\color{gray}{\textsf{-0.5\%}}$ 17 132 21 025 0
✅ tempest 895 23.7 $\color{gray}{\textsf{+0.4\%}}$ 5 047 10 528 252
✅ amphp-amp 68 1.9 $\color{gray}{\textsf{-0.5\%}}$ 29 49 0
✅ webmozarts-assert 272 4.7 $\color{gray}{\textsf{+0.4\%}}$ 577 2 720 0
✅ guzzle-promises 44 1.6 $\color{gray}{\textsf{-0.6\%}}$ 155 434 2
✅ monolog 135 5.6 $\color{gray}{\textsf{-0.7\%}}$ 913 2 479 10
✅ drupal 4 841 145.7 $\color{gray}{\textsf{+2.0\%}}$ 97 591 169 293 583
Total 13 285 492.5 $\color{gray}{\textsf{+0.4\%}}$ 204 550 373 563 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.

head 9ff1fbb · base c5f4dfd (merge-base) · workflow run

# Conflicts:
#	tests/Loop/ForeachTest.php

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the receiver_analyzed change in getFakeMethodCallType() is the right place. One path still analyses the iterated expression twice: an IteratorAggregate whose getIterator() returns an iterator without template params goes through handleIterable() with a new VirtualMethodCall(getIterator) (ForeachAnalyzer.php:1690). That node has no type, so receiver_analyzed falls back to analysing it, which analyses $foreach_expr again:

final class RawIt implements Iterator {
    public function current(): string { return "a"; }
    public function key(): int { return 0; }
    public function next(): void {}
    public function rewind(): void {}
    public function valid(): bool { return false; }
}
final class AggRaw implements IteratorAggregate {
    public function getIterator(): RawIt { return new RawIt(); }
}
final class H {
    private ?AggRaw $aggRaw = null;
    public function a(): void {
        foreach (($this->aggRaw ??= new AggRaw()) as $v) { echo $v; } // still RedundantCondition + TypeDoesNotContainType
    }
    public function b(): Generator {
        yield from ($this->aggRaw ??= new AggRaw()); // same
    }
}

Giving the virtual call the type already known for getIterator() fixes both (checked locally):

$get_iterator_call = new VirtualMethodCall(
    $foreach_expr,
    new VirtualIdentifier('getIterator', $foreach_expr->getAttributes()),
);
$statements_analyzer->node_data->setType($get_iterator_call, new Union([$array_atomic_type]));

self::handleIterable(
    $statements_analyzer,
    $array_atomic_type,
    $get_iterator_call,
    // ...

Could you add that, plus test cases for this shape and for yield from ($this->items ??= new Items()) (the other caller of the helper)?

@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@orklah thanks, done in a231c35: the virtual getIterator() call built in handleIterable() now gets the type already known for it (setType($get_iterator_call, new Union([$array_atomic_type]))), so receiver_analyzed no longer analyses $foreach_expr a second time.

  • ForeachTest::foreachAndYieldFromAnAggregateOfARawIteratorGivenByACoalesceAssignment is your RawIt/AggRaw/H shape (foreach and yield from over $this->aggRaw ??= new AggRaw()): on the commit before the fix it reports RedundantCondition: Type AggRaw for $this->aggRaw is always isset, on the current head nothing.
  • yieldFromAnIteratorAggregateGivenByACoalesceAssignment covers yield from ($this->items ??= new Items()); it already passed before this commit (the earlier receiver_analyzed change fixed it), so it is a guard.

CI is green apart from label. PHPUnit suite not run locally.

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 22, 2026

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jirkace!

@orklah
orklah merged commit f24bd68 into vimeo:master Nov 22, 2026
71 of 72 checks passed
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.

RedundantCondition and TypeDoesNotContainType on foreach over a ??= expression (iterated expression analysed several times)

2 participants