Skip to content

Multiple for loops with the same variable name in one function corrupt register allocation #146

Closed

Description

@davydog187

Severity: High
Area: Compiler — scope resolver / codegen

Description

When a function contains two or more numeric for loops that use the same loop variable name (e.g., i), the scope resolver's locals map is keyed by name. The second loop's for variable overwrites the first loop's entry, so the first loop's loop_var_reg points to the wrong register at code generation time. This causes incorrect values to be used as the loop counter in earlier loops.

Reproduction

function run(n)
  local sum = 0
  for i = 1, n do
    sum = sum + i      -- 'i' register is misassigned
  end
  for i = 1, n do
    sum = sum + i
  end
  return sum
end
return run(5)
-- Expected: 30
-- Actual: wrong value or crash

Workaround

Use distinct variable names for each loop:

for i = 1, n do ... end
for j = 1, n do ... end
for k = 1, n do ... end

Activity

  1. davydog187 commented on May 4, 2026

    @davydog187
    ContributorAuthor

    Regression confirmed on main (835de36).

    This was originally fixed in PR #141 (Phase 17), but the perf rewrites that followed (likely PR #156 — fully tail-recursive CPS executor) reintroduced the bug. Minimal repro:

    local sum = 0
    for i = 1, 3 do sum = sum + i end
    for i = 1, 3 do sum = sum + i end
    return sum

    Single loop works fine; the second loop's i register collides with the first loop's residual state.

    Adding to the Direction A queue as a new plan file. Will be picked up via /next-plan after the high-leverage A1 fix lands. Tracking under milestone 0.5.0.

  2. added
    direction:ADirection A: suite triage to 0.5.0
    regressionBehavior that worked before now broken
    on May 4, 2026
  3. added this to the milestone on May 4, 2026
  4. davydog187 commented on May 4, 2026

    @davydog187
    ContributorAuthor

    Plan filed: .agents/plans/A14-for-loop-register-regression.md (will be picked up via /next-plan).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingdirection:ADirection A: suite triage to 0.5.0regressionBehavior that worked before now broken

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions