Skip to content
This repository was archived by the owner on Jan 4, 2026. It is now read-only.

Commit 3f9ec7a

Browse files
refactor: simplify stack manipulation in return and endFunction instructions
1 parent 9850198 commit 3f9ec7a

1 file changed

Lines changed: 24 additions & 28 deletions

File tree

src/runtime.rs

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,7 @@ impl Vm {
138138
Instruction::SetLocal(index) => {
139139
let value = stack_pop!(stack);
140140
let variable_index = stack_base_pointer + *index;
141-
let stack_len = stack.len();
142-
stack.get_mut(variable_index)
143-
.expect(format!("Local variable index out of bounds: {} >= {}", variable_index, stack_len).as_str())
144-
.clone_from(&value);
141+
stack[variable_index] = value;
145142
pc += 1;
146143
},
147144

@@ -466,34 +463,33 @@ impl Vm {
466463
},
467464

468465
Instruction::Return => {
469-
let Some(returning_value) = stack.pop() else {
470-
return runtime_error!("Return instruction without value");
471-
};
472-
473-
if let Some(parent_frame) = frames.pop() {
474-
475-
stack.resize(stack_base_pointer, Variant::Null);
476-
477-
pc = parent_frame.pc;
478-
stack_base_pointer = parent_frame.stack_base_pointer;
479-
480-
stack.push(returning_value);
481-
function_index = parent_frame.function_index;
482-
} else {
483-
result = Some(returning_value);
484-
break;
466+
let value = stack.pop().expect("Return value should not be empty");
467+
match frames.pop() {
468+
Some(parent_frame) => {
469+
stack.resize(stack_base_pointer, Variant::Null);
470+
stack.push(value);
471+
pc = parent_frame.pc;
472+
stack_base_pointer = parent_frame.stack_base_pointer;
473+
function_index = parent_frame.function_index;
474+
},
475+
None => {
476+
result = Some(value);
477+
break;
478+
}
485479
}
486480
}
487481

488482
Instruction::EndFunction => {
489-
if let Some(parent_frame) = frames.pop() {
490-
debug!("Returning from function {}", self.functions[function_index].name);
491-
stack.resize(stack_base_pointer, Variant::Null);
492-
pc = parent_frame.pc;
493-
stack_base_pointer = parent_frame.stack_base_pointer;
494-
function_index = parent_frame.function_index;
495-
} else {
496-
break;
483+
match frames.pop() {
484+
Some(parent_frame) => {
485+
stack.resize(stack_base_pointer, Variant::Null);
486+
pc = parent_frame.pc;
487+
stack_base_pointer = parent_frame.stack_base_pointer;
488+
function_index = parent_frame.function_index;
489+
},
490+
None => {
491+
break;
492+
}
497493
}
498494
}
499495

0 commit comments

Comments
 (0)