From 46de03858a8a77810c365521dae9020d4067652b Mon Sep 17 00:00:00 2001 From: Sofia Date: Sun, 15 Mar 2026 00:52:38 +0200 Subject: [PATCH] Implement functional add example --- examples/test.lua | 8 ++++---- src/compile.rs | 25 +++++++++++++++---------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/examples/test.lua b/examples/test.lua index c1d677a..7fe7924 100644 --- a/examples/test.lua +++ b/examples/test.lua @@ -1,8 +1,8 @@ function add(x) - return function test() - return x + return function (y) + return x + y end end -local d = add(5 + 7) -global c = print(d() + 10) \ No newline at end of file +local d = add(5) +global c = print(d(7)) \ No newline at end of file diff --git a/src/compile.rs b/src/compile.rs index 4423d71..b095b10 100644 --- a/src/compile.rs +++ b/src/compile.rs @@ -241,7 +241,7 @@ impl Expression { let (instr, registers) = expr.kind.compile(state, scope, 1); instructions.extend(instr); - let function_register = registers.first().unwrap(); + let old_function_reg = registers.first().unwrap(); let mut original_param_regs = Vec::new(); for param in params.kind.0.iter() { @@ -249,20 +249,25 @@ impl Expression { instructions.extend(instr); original_param_regs.extend(registers); } + let function_reg = scope.register_counter.next(); let mut param_regs = Vec::new(); - for param_reg in original_param_regs { - let new_reg = scope.register_counter.next(); - if param_reg != new_reg { - instructions.push(Instruction::Move(new_reg, param_reg)); - } - param_regs.push(new_reg); + for _ in &original_param_regs { + param_regs.push(scope.register_counter.next()); } - let last_param_reg = param_regs.last().unwrap_or(function_register); + for (i, param_reg) in original_param_regs.iter().enumerate().rev() { + let new_reg = param_regs.get(i).unwrap(); + if param_reg != new_reg { + instructions.push(Instruction::Move(*new_reg, *param_reg)); + } + } + instructions.push(Instruction::Move(function_reg, *old_function_reg)); + + let last_param_reg = param_regs.last().unwrap_or(&function_reg); let mut return_regs = Vec::new(); for i in 0..expected_values { - let return_reg = i as u16 + function_register; + let return_reg = i as u16 + function_reg; if return_reg > *last_param_reg { return_regs.push(scope.register_counter.next()); } else { @@ -271,7 +276,7 @@ impl Expression { } instructions.push(Instruction::Call( - *function_register, + *&function_reg, param_regs.len() as u16, return_regs.len() as u16 + 1, ));