iterator_count runs indefinitely if iterator doesn't complete
Description
The following code:
<?php
function fibonacci(): Generator
{
yield $a = 1;
yield $b = 2;
start:
yield $c = $a + $b;
$a = $b;
$b = $c;
goto start;
}
$gen = fibonacci();
iterator_count($gen);
Resulted in this output:
// None. Program stalls
But I expected this output instead:
// some sort of exception
When an iterator never finishes, the iterator_count method simply hangs. This is in contrast to the iterator_to_array method, which throws a fatal error when it runs out of memory. Since iterator_count will continue running, and eventually overflow, no exception is thrown.
This is obviously a tricky situation. But it would be useful if there were some way to detect that an iterator is unlikely to finish, and throw an exception of some sort, rather than simply allowing the program to hang.
I've observed this behavior in multiple versions of PHP (8.0+), as well as multiple operating systems (desktop Linux, Android, and macOS)
PHP Version
8.1.3
Operating System
Darwin 21.3.0
Normally this sort of "PHP code runs for a long time without running out of memory due to some infinite loop" problem is covered by the max_execution_time setting. Does that make sense as a solution here too?
Since iterator_count will continue running, and eventually overflow, no exception is thrown.
I think we need to bail out in case of overflow: https://github.com/php/php-src/blob/0ba92163a0a6927a1997e76c16adfc83488c27af/ext/spl/spl_iterators.c#L3130
While that may not happen in practice, wrapping around certainly makes no sense.