Skip to content

Codegen: const + var in same function panics with duplicate variable #27

@mjm918

Description

@mjm918

Description

Declaring a const followed by a var in the same function causes a Cranelift panic: the variable var0 has been declared multiple times.

Steps to Reproduce

fn main() {
    const axx: int = 2;
    var x: int = 10;
}

Expected: Compiles and runs
Actual: Panic: the variable var0 has been declared multiple times

Root Cause

In namlc/src/codegen/cranelift/mod.rs:

  • Statement::Var correctly uses Variable::new(ctx.var_counter) and increments ctx.var_counter (line 1721-1722)
  • Statement::Const incorrectly uses Variable::new(ctx.variables.len()) and does NOT increment ctx.var_counter (line 2478)

When const is the first statement, variables.len() == 0 assigns Variable(0). Since var_counter is never incremented, the next var also gets Variable(0), causing the Cranelift panic.

Fix

Change Statement::Const to use ctx.var_counter and increment it, matching the Statement::Var pattern:

let var = Variable::new(ctx.var_counter);
ctx.var_counter += 1;

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