Skip to content

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

@davydog187

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions