Add bytecode function creation with defaults and shared closures
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 6m28s

This commit is contained in:
2026-10-19 02:29:39 +08:00
parent e52d2e1e4b
commit e24909a56e
14 changed files with 610 additions and 21 deletions
+32 -1
View File
@@ -1,6 +1,6 @@
use crate::code::jump_target;
use crate::frame::StackEntry;
use crate::instruction::{compare_operation, invalid};
use crate::instruction::{compare_operation, function_counts, invalid};
use crate::{
CompareOp, EndorCellObject, EndorCodeObject, EndorFrame, EndorFunctionObject,
EndorStringObject, ExecutionLimits, ExecutionLocation, ObjectRef, Opcode, Value, Vm, VmError,
@@ -314,6 +314,31 @@ impl Vm {
Ok(dictionary)
}
fn make_function(&mut self, frame: &EndorFrame, argument: u32) -> Result<ObjectRef, VmError> {
let (default_count, closure_count) = function_counts(argument);
let Value::Object(code) = Self::top_value(frame)? else {
return Err(VmError::ObjectKindMismatch("code"));
};
let name = self
.payload::<EndorCodeObject>(code, "code")?
.code()
.name()
.to_owned();
let start = frame.stack.len() - default_count - closure_count - 1;
let defaults = (start..start + default_count)
.map(|index| Self::stack_value(frame, index))
.collect::<Result<Vec<_>, _>>()?;
let closure = (start + default_count..frame.stack.len() - 1)
.map(|index| match Self::stack_value(frame, index)? {
Value::Object(cell) => Ok(cell),
_ => Err(VmError::ObjectKindMismatch("cell")),
})
.collect::<Result<Vec<_>, _>>()?;
// Keep every input root on the stack until allocation has validated
// and retained all function edges. Failure leaves cleanup to the frame.
self.new_function(name, code, frame.globals, defaults, closure)
}
fn eval_frames(
&mut self,
frames: &mut Vec<EndorFrame>,
@@ -528,6 +553,12 @@ impl Vm {
.stack
.push(StackEntry::Value(Value::Object(dictionary)));
}
Opcode::MakeFunction => {
let function = self.make_function(frame, decoded.instruction.argument)?;
let (defaults, closure) = function_counts(decoded.instruction.argument);
self.discard(frame, defaults + closure + 1);
frame.stack.push(StackEntry::Value(Value::Object(function)));
}
Opcode::ExtendedArg => unreachable!("EXTENDED_ARG was decoded before evaluation"),
}
}