Skip to content

compiler: do not drop the loop condition at chunk offset 0 - #469

Merged
jow- merged 1 commit into
ucode-lang:masterfrom
dangowrt:compiler-for-cond-at-offset-zero
Oct 6, 2026
Merged

jow- merged 1 commit into
ucode-lang:masterfrom
dangowrt:compiler-for-cond-at-offset-zero

Conversation

@dangowrt

@dangowrt dangowrt commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

A counting for loop without an initializer that opens a function body never re-evaluates its condition. uc_compiler_compile_for_count() records where the condition starts in cond_off and treats 0 as "no condition", but when the loop is the first code in a function its condition does start at chunk offset 0, so the jump from the incrementer back to the condition is never emitted and the loop runs on after the condition has turned false:

function f(n) { for (; n > 0; n--) print(n); }
f(3);

prints 3, 2, 1, 0, -1, ... and never returns. Any statement before the loop, even let x;, moves the condition off offset 0 and hides the bug, which is why the existing for-loop test does not catch it.

The fix tests for the conditional jump instead, which is always emitted after at least one instruction of the condition and so is never at offset 0. The new regression test in 99_bugs fails with "runaway" on the old compiler instead of hanging, and the whole custom test suite passes.

uc_compiler_compile_for_count() records where the condition starts in
cond_off and treats 0 as "no condition". A counting for loop without an
initializer that opens a function body puts its condition at offset 0,
so the jump from the incrementer back to the condition is never emitted
and the loop keeps running after the condition turned false:

  function f(n) { for (; n > 0; n--) print(n); }

never returns. Test for the conditional jump instead, which is always
emitted after at least one instruction of the condition.

Fixes: 37568066a7d9 ("treewide: rewrite ucode interpreter")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
@dangowrt
dangowrt marked this pull request as ready for review October 5, 2026 23:49
@jow-
jow- merged commit 2f62a44 into ucode-lang:master Oct 6, 2026
2 checks passed
@jow-

jow- commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Merged, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants