Implement functional add example

This commit is contained in:
Sofia 2026-03-15 00:52:38 +02:00
parent 08e9b00b5c
commit 46de03858a
2 changed files with 19 additions and 14 deletions

View File

@ -1,8 +1,8 @@
function add(x) function add(x)
return function test() return function (y)
return x return x + y
end end
end end
local d = add(5 + 7) local d = add(5)
global c = print(d() + 10) global c = print(d(7))

View File

@ -241,7 +241,7 @@ impl Expression {
let (instr, registers) = expr.kind.compile(state, scope, 1); let (instr, registers) = expr.kind.compile(state, scope, 1);
instructions.extend(instr); instructions.extend(instr);
let function_register = registers.first().unwrap(); let old_function_reg = registers.first().unwrap();
let mut original_param_regs = Vec::new(); let mut original_param_regs = Vec::new();
for param in params.kind.0.iter() { for param in params.kind.0.iter() {
@ -249,20 +249,25 @@ impl Expression {
instructions.extend(instr); instructions.extend(instr);
original_param_regs.extend(registers); original_param_regs.extend(registers);
} }
let function_reg = scope.register_counter.next();
let mut param_regs = Vec::new(); let mut param_regs = Vec::new();
for param_reg in original_param_regs { for _ in &original_param_regs {
let new_reg = scope.register_counter.next(); param_regs.push(scope.register_counter.next());
if param_reg != new_reg {
instructions.push(Instruction::Move(new_reg, param_reg));
}
param_regs.push(new_reg);
} }
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(); let mut return_regs = Vec::new();
for i in 0..expected_values { 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 { if return_reg > *last_param_reg {
return_regs.push(scope.register_counter.next()); return_regs.push(scope.register_counter.next());
} else { } else {
@ -271,7 +276,7 @@ impl Expression {
} }
instructions.push(Instruction::Call( instructions.push(Instruction::Call(
*function_register, *&function_reg,
param_regs.len() as u16, param_regs.len() as u16,
return_regs.len() as u16 + 1, return_regs.len() as u16 + 1,
)); ));