refactor(compiler): 拆分 oxide_emit 为独立 emit pass crate(依赖倒置)

This commit is contained in:
爱特每羊队
2026-08-05 20:13:18 +08:00
parent 9f02985a82
commit bbdfca1a1c
62 changed files with 1045 additions and 993 deletions
+1
View File
@@ -0,0 +1 @@
+124
View File
@@ -0,0 +1,124 @@
use crate::{CompileCtx, Emitter, FunctionBodyContext};
use oxide_ir::inst::Inst;
use oxide_ir::operand::Operand;
use oxide_bytecode::opcode::OpCode;
use oxide_parser::{Class, ClassElement, MethodDefinitionKind, PropertyKey};
impl Emitter {
pub(crate) fn emit_class(&self, class: &Class, ctx: &mut CompileCtx) -> Result<u8, String> {
let mut constructor_method = None;
let mut instance_fields = Vec::new();
let mut private_names = Vec::<(String, u32)>::new();
let is_derived = class.super_class.is_some();
for element in &class.body.body {
match element {
ClassElement::MethodDefinition(method) => {
let method = method.as_ref();
if let PropertyKey::PrivateIdentifier(private) = &method.key {
let name = private.name.as_str().to_string();
if private_names.iter().any(|(existing, _)| existing == &name) {
return Err(format!("duplicate private name #{name}"));
}
let id = ctx.scopes.next_private_name_id;
ctx.scopes.next_private_name_id = ctx.scopes.next_private_name_id.saturating_add(1);
private_names.push((name, id));
}
if method.kind == MethodDefinitionKind::Constructor {
if constructor_method.is_some() {
return Err("duplicate class constructor".into());
}
constructor_method = Some(method);
}
}
ClassElement::PropertyDefinition(prop) => {
let prop = prop.as_ref();
if let PropertyKey::PrivateIdentifier(private) = &prop.key {
let name = private.name.as_str().to_string();
if private_names.iter().any(|(existing, _)| existing == &name) {
return Err(format!("duplicate private name #{name}"));
}
let id = ctx.scopes.next_private_name_id;
ctx.scopes.next_private_name_id = ctx.scopes.next_private_name_id.saturating_add(1);
private_names.push((name, id));
}
if !prop.r#static {
instance_fields.push(prop);
}
}
ClassElement::AccessorProperty(_) => return Err("class accessor properties not yet supported".into()),
ClassElement::StaticBlock(_) | ClassElement::TSIndexSignature(_) => {}
}
}
let (ctor_reg, proto_reg, super_reg) = self.emit_class_header(class, ctx)?;
let ctor_name = class.id.as_ref().map(|id| id.name.to_string());
let self_binding = ctor_name.as_deref().map(|name| vec![(name, ctor_reg)]).unwrap_or_default();
let saved_derived = ctx.in_derived_constructor;
let saved_private_names = ctx.scopes.private_name_map.clone();
ctx.in_derived_constructor = is_derived;
ctx.scopes.private_name_map = private_names.clone();
let emit_instance_fields = |compiler: &Emitter, field_ctx: &mut CompileCtx| -> Result<(), String> {
for field in &instance_fields {
if let PropertyKey::PrivateIdentifier(private) = &field.key {
compiler.emit_private_field_init(Operand::This, private.name.as_str(), field.value.as_ref(), field_ctx)?;
} else {
compiler.emit_public_field_init(Operand::This, &field.key, field.computed, field.value.as_ref(), field_ctx)?;
}
}
Ok(())
};
let mut ctor_module = if let Some(method) = constructor_method {
let (param_names, body_stmts) = self.extract_function_parts(method.value.as_ref())?;
self.compile_function_body_with_field_hooks(
&param_names,
body_stmts,
ctx,
false,
&self_binding,
FunctionBodyContext::ClassElement,
Some(&emit_instance_fields),
is_derived,
)?
} else {
let mut module = self.compile_function_body_with_field_hooks(
&[],
&[],
ctx,
false,
&self_binding,
FunctionBodyContext::ClassElement,
Some(&emit_instance_fields),
is_derived,
)?;
if is_derived {
module.insts.clear();
module.constants.clear();
module.n_registers = 1;
module.insts.push(Inst::super_call(Operand::None, Operand::None, 0));
let mut field_ctx = CompileCtx::new();
field_ctx.scopes.private_name_map = private_names.clone();
emit_instance_fields(self, &mut field_ctx)?;
module.insts.extend(field_ctx.insts);
module.constants = field_ctx.constants;
module.n_registers = field_ctx.max_regs.max(1);
module.insts.push(Inst::new(OpCode::RETURN, Operand::None, Operand::None, Operand::None));
}
module
};
ctx.in_derived_constructor = saved_derived;
ctor_module.is_class_constructor = true;
ctor_module.is_derived_constructor = is_derived;
ctor_module.function_name = ctor_name.clone();
ctx.nested.push(ctor_module);
self.emit_class_prototype(ctor_reg, proto_reg, super_reg, ctx.nested.len() as u16, ctx)?;
self.emit_class_methods(&class.body.body, ctor_reg, proto_reg, &self_binding, ctx)?;
self.emit_class_static_elements(&class.body.body, ctor_reg, ctx)?;
ctx.scopes.private_name_map = saved_private_names;
Ok(ctor_reg)
}
}
+40
View File
@@ -0,0 +1,40 @@
use crate::{CompileCtx, Emitter};
use oxide_ir::operand::Operand;
use oxide_parser::{ClassElement, PropertyKey};
impl Emitter {
/// Emit static field initializers and static blocks in source order.
/// JS class semantics interleave them (e.g. `static x = 1; static {
/// this.y = 1 } static z = this.y + 1` must run in that order). Emitting
/// all fields before all blocks would make `z` read `y` before it is set.
pub(crate) fn emit_class_static_elements(
&self, elements: &[ClassElement], ctor_reg: u8, ctx: &mut CompileCtx,
) -> Result<(), String> {
let saved_static_this = ctx.static_block_this_reg;
ctx.static_block_this_reg = Some(ctor_reg);
for element in elements {
match element {
ClassElement::PropertyDefinition(prop) => {
let prop = prop.as_ref();
if prop.r#static {
if let PropertyKey::PrivateIdentifier(private) = &prop.key {
self.emit_private_field_init(Operand::Reg(ctor_reg as u32), private.name.as_str(), prop.value.as_ref(), ctx)?;
} else {
self.emit_public_field_init(Operand::Reg(ctor_reg as u32), &prop.key, prop.computed, prop.value.as_ref(), ctx)?;
}
}
}
ClassElement::StaticBlock(block) => {
ctx.push_scope();
for stmt in &block.body {
self.emit_statement(stmt, ctx)?;
}
ctx.pop_scope();
}
_ => {}
}
}
ctx.static_block_this_reg = saved_static_this;
Ok(())
}
}
+16
View File
@@ -0,0 +1,16 @@
use crate::{CompileCtx, Emitter};
impl Emitter {
pub(crate) fn emit_class_header(
&self, class: &oxide_parser::Class, ctx: &mut CompileCtx,
) -> Result<(u8, u8, Option<u8>), String> {
let ctor_reg = ctx.alloc_reg();
let proto_reg = ctx.alloc_reg();
let super_reg = if let Some(super_expr) = &class.super_class {
Some(self.emit_expression(super_expr, ctx)?)
} else {
None
};
Ok((ctor_reg, proto_reg, super_reg))
}
}
+97
View File
@@ -0,0 +1,97 @@
use crate::{CompileCtx, Emitter, FunctionBodyContext};
use oxide_ir::inst::Inst;
use oxide_ir::operand::Operand;
use oxide_bytecode::module::Constant;
use oxide_bytecode::opcode::OpCode;
use oxide_parser::{ClassElement, MethodDefinitionKind, PropertyKey};
impl Emitter {
pub(crate) fn emit_class_methods(
&self, elements: &[ClassElement], ctor_reg: u8, proto_reg: u8, self_binding: &[(&str, u8)],
ctx: &mut CompileCtx,
) -> Result<(), String> {
for element in elements {
match element {
ClassElement::MethodDefinition(method) => {
let method = method.as_ref();
if method.kind == MethodDefinitionKind::Constructor {
continue;
}
if matches!(method.key, PropertyKey::PrivateIdentifier(_)) {
let home_reg = if method.r#static { ctor_reg } else { proto_reg };
self.emit_private_method_init(Operand::Reg(home_reg as u32), method, Operand::Reg(home_reg as u32), ctx)?;
continue;
}
let home_reg = if method.r#static { ctor_reg } else { proto_reg };
let key_reg = self.emit_class_key_reg(&method.key, method.computed, ctx)?;
let method_name = if method.computed {
"<computed>".to_string()
} else {
self.class_property_name(&method.key)?
};
let accessor_reg =
self.emit_class_method_function(method, &method_name, Operand::Reg(home_reg as u32), ctx, self_binding)?;
match method.kind {
MethodDefinitionKind::Method => {
if method.computed {
ctx.inst(Inst::new(OpCode::SET_PROP_DYNAMIC, Operand::Reg(home_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(accessor_reg as u32)));
} else {
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(home_reg as u32), Operand::Reg(accessor_reg as u32), Operand::Reg(key_reg as u32)));
}
}
MethodDefinitionKind::Get | MethodDefinitionKind::Set => {
if method.computed {
return Err("computed class accessors not yet supported".into());
}
let undef_reg = self.emit_undefined(ctx);
let (get_reg, set_reg) = if method.kind == MethodDefinitionKind::Get {
(accessor_reg, undef_reg)
} else {
(undef_reg, accessor_reg)
};
let key_name = self.class_property_name(&method.key)?;
let key_idx = ctx.add_constant(Constant::String(key_name));
ctx.inst(Inst::define_accessor(
Operand::Reg(home_reg as u32),
Operand::Reg(get_reg as u32),
Operand::Reg(set_reg as u32),
key_idx as u32,
));
}
MethodDefinitionKind::Constructor => continue,
}
}
_ => {}
}
}
Ok(())
}
pub(crate) fn emit_class_method_function(
&self, method: &oxide_parser::MethodDefinition, method_name: &str, home_reg: Operand, ctx: &mut CompileCtx,
self_binding: &[(&str, u8)],
) -> Result<u8, String> {
let (param_names, body_stmts) = self.extract_function_parts(method.value.as_ref())?;
let saved_instance = ctx.in_instance_method;
let saved_static = ctx.in_static_method;
ctx.in_instance_method = !method.r#static;
ctx.in_static_method = method.r#static;
let mut method_module = self.compile_function_body_with_bindings(
&param_names,
body_stmts,
ctx,
false,
self_binding,
FunctionBodyContext::ClassElement,
)?;
ctx.in_instance_method = saved_instance;
ctx.in_static_method = saved_static;
method_module.function_name = Some(method_name.to_string());
method_module.needs_home_object = true;
ctx.nested.push(method_module);
let method_reg = ctx.alloc_reg();
ctx.inst(Inst::create_closure(Operand::Reg(method_reg as u32), ctx.nested.len() as u16));
ctx.inst(Inst::new(OpCode::SET_HOME_OBJECT, Operand::Reg(method_reg as u32), home_reg, Operand::None));
Ok(method_reg)
}
}
+6
View File
@@ -0,0 +1,6 @@
pub mod core;
pub mod emit;
pub mod field;
pub mod header;
pub mod method;
pub mod prototype;
+35
View File
@@ -0,0 +1,35 @@
use crate::{CompileCtx, Emitter};
use oxide_ir::inst::Inst;
use oxide_ir::operand::Operand;
use oxide_bytecode::module::Constant;
use oxide_bytecode::opcode::OpCode;
impl Emitter {
pub(crate) fn emit_class_prototype(
&self, ctor_reg: u8, proto_reg: u8, super_reg: Option<u8>, sub_idx: u16, ctx: &mut CompileCtx,
) -> Result<(), String> {
ctx.inst(Inst::create_closure(Operand::Reg(ctor_reg as u32), sub_idx));
ctx.inst(Inst::new(OpCode::NEW_OBJECT, Operand::Reg(proto_reg as u32), Operand::None, Operand::None));
if let Some(super_reg) = super_reg {
let proto_key_idx = ctx.add_constant(Constant::String("prototype".to_string()));
let parent_proto_key_reg = ctx.alloc_reg();
ctx.inst(Inst::load_const(Operand::Reg(parent_proto_key_reg as u32), proto_key_idx));
let parent_proto_reg = ctx.alloc_reg();
ctx.inst(Inst::new(OpCode::GET_PROP, Operand::Reg(super_reg as u32), Operand::Reg(parent_proto_reg as u32), Operand::Reg(parent_proto_key_reg as u32)));
let proto_link_idx = ctx.add_constant(Constant::String("__proto__".to_string()));
let proto_link_key_reg = ctx.alloc_reg();
ctx.inst(Inst::load_const(Operand::Reg(proto_link_key_reg as u32), proto_link_idx));
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(proto_reg as u32), Operand::Reg(parent_proto_reg as u32), Operand::Reg(proto_link_key_reg as u32)));
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(ctor_reg as u32), Operand::Reg(super_reg as u32), Operand::Reg(proto_link_key_reg as u32)));
}
let ctor_key_idx = ctx.add_constant(Constant::String("constructor".to_string()));
let ctor_key_reg = ctx.alloc_reg();
ctx.inst(Inst::load_const(Operand::Reg(ctor_key_reg as u32), ctor_key_idx));
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(proto_reg as u32), Operand::Reg(ctor_reg as u32), Operand::Reg(ctor_key_reg as u32)));
let proto_key_idx = ctx.add_constant(Constant::String("prototype".to_string()));
let proto_key_reg = ctx.alloc_reg();
ctx.inst(Inst::load_const(Operand::Reg(proto_key_reg as u32), proto_key_idx));
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(ctor_reg as u32), Operand::Reg(proto_reg as u32), Operand::Reg(proto_key_reg as u32)));
Ok(())
}
}