feat: 搭建字节码函数调用基础设施

This commit is contained in:
2026-06-07 16:18:20 +08:00
parent 546d9db338
commit a232cb6969
5 changed files with 183 additions and 8 deletions
+5
View File
@@ -167,6 +167,10 @@ impl CompileCtx {
self.switch_stack.last()
}
pub(crate) fn is_builtin(&self, name: &str) -> bool {
self.builtin_reg_map.iter().any(|(n, _)| n == name)
}
pub(crate) fn pre_register_builtins(&mut self) {
let builtins = [
"NaN",
@@ -235,6 +239,7 @@ impl Compiler {
constants: ctx.constants,
n_registers: ctx.max_regs,
builtin_reg_map: ctx.builtin_reg_map,
sub_modules: Vec::new(),
})
}
}
+7 -6
View File
@@ -791,12 +791,13 @@ impl Compiler {
} else {
arg_regs[0]
};
ctx.emit(opcode::encode(
OpCode::CALL,
callee_reg,
this_reg,
first_arg_reg,
));
let op = match &call.callee {
Expression::Identifier(ident) if ctx.is_builtin(ident.name.as_str()) => {
OpCode::CALL_NATIVE
}
_ => OpCode::CALL,
};
ctx.emit(opcode::encode(op, callee_reg, this_reg, first_arg_reg));
ctx.emit(arg_regs.len() as u32);
Ok(0u8)
}
+20 -1
View File
@@ -10,6 +10,7 @@ pub enum Constant {
Boolean(bool),
Null,
Undefined,
BytecodeFunc(u32),
}
pub struct CompiledModule {
@@ -17,6 +18,19 @@ pub struct CompiledModule {
pub constants: Vec<Constant>,
pub n_registers: u8,
pub builtin_reg_map: Vec<(String, u8)>,
pub sub_modules: Vec<CompiledModule>,
}
impl Clone for CompiledModule {
fn clone(&self) -> Self {
Self {
bytecode: self.bytecode.clone(),
constants: self.constants.clone(),
n_registers: self.n_registers,
builtin_reg_map: self.builtin_reg_map.clone(),
sub_modules: self.sub_modules.clone(),
}
}
}
impl fmt::Display for CompiledModule {
@@ -24,7 +38,12 @@ impl fmt::Display for CompiledModule {
writeln!(f, "; n_registers = {}", self.n_registers)?;
writeln!(f, "; constants:")?;
for (i, c) in self.constants.iter().enumerate() {
writeln!(f, "; [{i}] = {:?}", c)?;
match c {
Constant::BytecodeFunc(idx) => {
writeln!(f, "; [{i}] = BytecodeFunc(sub_module[{idx}])")?
}
other => writeln!(f, "; [{i}] = {other:?}")?,
}
}
writeln!(f)?;
for (offset, &instr) in self.bytecode.iter().enumerate() {
+7 -1
View File
@@ -60,9 +60,11 @@ pub enum OpCode {
STORE_VAR = 0x31,
LOAD_CONST = 0x32,
// ── Call (0x40-0x4F) ──
// -- Call (0x40-0x4F) --
CALL = 0x40,
RETURN = 0x41,
CALL_NATIVE = 0x42,
NEW_EXPRESSION = 0x43,
// ── Object Property (0x50-0x5F) ──
IC_GET_PROP = 0x50,
@@ -165,6 +167,8 @@ impl TryFrom<u8> for OpCode {
0x32 => Ok(OpCode::LOAD_CONST),
0x40 => Ok(OpCode::CALL),
0x41 => Ok(OpCode::RETURN),
0x42 => Ok(OpCode::CALL_NATIVE),
0x43 => Ok(OpCode::NEW_EXPRESSION),
0x50 => Ok(OpCode::IC_GET_PROP),
0x51 => Ok(OpCode::IC_SET_PROP),
0x52 => Ok(OpCode::GET_PROP),
@@ -244,6 +248,8 @@ impl fmt::Display for OpCode {
OpCode::LOAD_CONST => "LOAD_CONST",
OpCode::CALL => "CALL",
OpCode::RETURN => "RETURN",
OpCode::CALL_NATIVE => "CALL_NATIVE",
OpCode::NEW_EXPRESSION => "NEW_EXPRESSION",
OpCode::IC_GET_PROP => "IC_GET_PROP",
OpCode::IC_SET_PROP => "IC_SET_PROP",
OpCode::GET_PROP => "GET_PROP",