[php-src] Issue #11591: Inconsistent behaviour with AppendIterator and empty generators

From: Date: Tue, 04 Jul 2023 10:35:07 +0000
Subject: [php-src] Issue #11591: Inconsistent behaviour with AppendIterator and empty generators
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-244874@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/11591 Author: sips-richard ### Description I've encountered inconsistent behaviour in the handling of empty generators with AppendIterator. Please can you confirm whether this is a bug or some weird expected behaviour. **Scenario 1** When iterating over a generator that yields nothing, foreach has no items to iterate over so var_dump isn't called, as expected. ```php <?php function yieldEmpty() { yield from []; } foreach (yieldEmpty() as $item) { var_dump($item); } ``` **Scenario 2** When attaching a generator yielding items and a generator yielding nothing and attaching both to an AppendIterator, foreach iterates over the items from the former and the three values are output, as expected. ```php <?php function yieldRows() { yield from ['one', 'two', 'three']; } function yieldEmpty() { yield from []; } $iterator = new AppendIterator(); $iterator->append(yieldRows()); $iterator->append(yieldEmpty()); foreach ($iterator as $item) { var_dump($item); } ``` Outputs (as expected): ``` string(3) "one" string(3) "two" string(5) "three" ``` **Test 3** When attaching ONLY a generator yielding nothing and attaching it to an AppendIterator, foreach unexpectedly fails with an exception. ```php <?php function yieldEmpty() { yield from []; } $iterator = new AppendIterator(); $iterator->append(yieldEmpty()); foreach ($iterator as $item) { var_dump($item); } ``` Expected output (following on from scenario 1 and 2): ``` string(3) "one" string(3) "two" string(5) "three" ``` Actual output: ``` PHP Fatal error: Uncaught Exception: Cannot traverse an already closed generator in /Users/richard.coupland/test3.php:11 Stack trace: #0 /Users/richard.coupland/test3.php(11): AppendIterator->rewind() #1 {main} thrown in /Users/richard.coupland/test3.php on line 11 Fatal error: Uncaught Exception: Cannot traverse an already closed generator in /Users/richard.coupland/test3.php:11 Stack trace: #0 /Users/richard.coupland/test3.php(11): AppendIterator->rewind() #1 {main} thrown in /Users/richard.coupland/test3.php on line 11 ``` ### PHP Version 8.2.7 ### Operating System _No response_

« previous php.bugs (#244874) next »