Fix issue with for loops in generators

The old code generated an invalid state machine for certain combinations of for loops with empty headers. This fixes the code and tries to clean it up so that there are less branches that were spread out all over the function, making it hard to reason about.

We had tests for all the combinations before but the test didn't call next enough times to actually verify that the behavior was correct. This expands on the tests to make sure we actually run the generator a few times.

Fixes #802, #331