Repository navigation
fix(foreach): the iterated expression is analysed once for getIterator() - #14370
Conversation
…r() vimeo#14297 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
✅ Performance: unchanged · Types: unchanged
How to read this table
head 9ff1fbb · base c5f4dfd (merge-base) · workflow run |
# Conflicts: # tests/Loop/ForeachTest.php
orklah
left a comment
There was a problem hiding this comment.
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)?
…eo#14297 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@orklah thanks, done in a231c35: the virtual
CI is green apart from |
foreachover an expression with side effects, such as??=, reportsRedundantConditionandTypeDoesNotContainType, because the virtualgetIterator()call analyses the iterated expression a second time.Before
After
Fixes #14297