Skip to content

Foreach loop causes infinite loop when iterating over generators #99

@miadey

Description

@miadey

Description

When using a foreach loop to iterate over a generator, the loop runs infinitely and never terminates.

Current Behavior

  • Generators work correctly with manual iteration using next(), current(), and valid() methods
  • However, when using foreach to iterate over a generator, it causes an infinite loop

Expected Behavior

Foreach loops should properly iterate through all yielded values and then terminate.

Test Case to Reproduce

<?php
function gen() {
    yield 1;
    yield 2;
    yield 3;
}

$g = gen();
echo "Starting foreach:\n";
foreach ($g as $value) {
    echo "Got: $value\n";
}
echo "Done\n";
?>

This code should output:

Starting foreach:
Got: 1
Got: 2
Got: 3
Done

But instead it runs infinitely.

Investigation Notes

  • The issue appears to be in the foreach generator handling in interpreter.rs around line 15604-15622
  • The loop advances the generator first, then checks validity
  • The validity check or loop termination condition may be incorrect
  • Manual iteration works correctly, so the generator state management is functioning

Related Issues

  • This was discovered while fixing #722 (broken generator functionality)
  • The core generator issue has been fixed, but foreach iteration remains broken

Priority

High - foreach is the primary way to iterate over generators in PHP

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions