refactor(compiler): 拆分 oxide_emit 为独立 emit pass crate(依赖倒置)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -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(
|
||||
¶m_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)
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
¶m_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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod core;
|
||||
pub mod emit;
|
||||
pub mod field;
|
||||
pub mod header;
|
||||
pub mod method;
|
||||
pub mod prototype;
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use oxide_bytecode::module::UpvalueCapture;
|
||||
use oxide_parser::{Expression, Statement};
|
||||
|
||||
use crate::Emitter;
|
||||
|
||||
impl Emitter {
|
||||
|
||||
fn collect_fn_param_names(&self, params: &oxide_parser::FormalParameters) -> HashSet<String> {
|
||||
let mut names = HashSet::new();
|
||||
for p in ¶ms.items {
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = &p.pattern {
|
||||
names.insert(bi.name.to_string());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// 收集当前函数作用域声明的绑定名(参数 + 变量/函数声明,含嵌套 block,不含嵌套函数体)。
|
||||
pub(crate) fn collect_own_binding_names(&self, param_names: &[&str], stmts: &[Statement]) -> HashSet<String> {
|
||||
let mut names = HashSet::new();
|
||||
for p in param_names {
|
||||
names.insert(p.to_string());
|
||||
}
|
||||
self.collect_decl_names_stmt(stmts, &mut names);
|
||||
names
|
||||
}
|
||||
|
||||
fn collect_decl_names_stmt(&self, stmts: &[Statement], out: &mut HashSet<String>) {
|
||||
for stmt in stmts {
|
||||
match stmt {
|
||||
Statement::VariableDeclaration(vd) => {
|
||||
for d in &vd.declarations {
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
out.insert(bi.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::FunctionDeclaration(fd) => {
|
||||
if let Some(id) = &fd.id {
|
||||
out.insert(id.name.to_string());
|
||||
}
|
||||
}
|
||||
Statement::BlockStatement(b) => self.collect_decl_names_stmt(&b.body, out),
|
||||
Statement::IfStatement(is) => {
|
||||
self.collect_decl_names_stmt(std::slice::from_ref(&is.consequent), out);
|
||||
if let Some(alt) = &is.alternate {
|
||||
self.collect_decl_names_stmt(std::slice::from_ref(alt), out);
|
||||
}
|
||||
}
|
||||
Statement::WhileStatement(w) => self.collect_decl_names_stmt(std::slice::from_ref(&w.body), out),
|
||||
Statement::DoWhileStatement(d) => self.collect_decl_names_stmt(std::slice::from_ref(&d.body), out),
|
||||
Statement::ForStatement(f) => {
|
||||
if let Some(oxide_parser::ForStatementInit::VariableDeclaration(vd)) = &f.init {
|
||||
for d in &vd.declarations {
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
out.insert(bi.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.collect_decl_names_stmt(std::slice::from_ref(&f.body), out);
|
||||
}
|
||||
Statement::SwitchStatement(sw) => {
|
||||
for case in &sw.cases {
|
||||
self.collect_decl_names_stmt(&case.consequent, out);
|
||||
}
|
||||
}
|
||||
Statement::TryStatement(ts) => {
|
||||
self.collect_decl_names_stmt(&ts.block.body, out);
|
||||
if let Some(h) = &ts.handler {
|
||||
self.collect_decl_names_stmt(&h.body.body, out);
|
||||
}
|
||||
if let Some(f) = &ts.finalizer {
|
||||
self.collect_decl_names_stmt(&f.body, out);
|
||||
}
|
||||
}
|
||||
Statement::LabeledStatement(ls) => self.collect_decl_names_stmt(std::slice::from_ref(&ls.body), out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 扫描 stmts 内(含任意深度嵌套函数)对 `ref_set` 的引用,写入 out。
|
||||
/// 递归进入嵌套函数时累加其局部绑定为遮蔽集,避免把内层局部误判为捕获。
|
||||
fn collect_capture_names(&self, stmts: &[Statement], ref_set: &HashSet<String>, out: &mut HashSet<String>) {
|
||||
let shadow = HashSet::new();
|
||||
self.collect_capture_names_shadowed(stmts, ref_set, &shadow, out);
|
||||
}
|
||||
|
||||
fn collect_capture_names_shadowed(
|
||||
&self, stmts: &[Statement], ref_set: &HashSet<String>, shadow: &HashSet<String>, out: &mut HashSet<String>,
|
||||
) {
|
||||
for stmt in stmts {
|
||||
self.collect_capture_names_stmt(stmt, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_capture_names_stmt(
|
||||
&self, stmt: &Statement, ref_set: &HashSet<String>, shadow: &HashSet<String>, out: &mut HashSet<String>,
|
||||
) {
|
||||
match stmt {
|
||||
Statement::ExpressionStatement(es) => self.collect_capture_names_expr(&es.expression, ref_set, shadow, out),
|
||||
Statement::ReturnStatement(rs) => {
|
||||
if let Some(a) = &rs.argument {
|
||||
self.collect_capture_names_expr(a, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
Statement::VariableDeclaration(vd) => {
|
||||
for d in &vd.declarations {
|
||||
if let Some(init) = &d.init {
|
||||
self.collect_capture_names_expr(init, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::FunctionDeclaration(fd) => {
|
||||
let body: &[Statement] = fd.body.as_ref().map(|b| &b.statements[..]).unwrap_or(&[]);
|
||||
let mut inner = shadow.clone();
|
||||
inner.extend(self.collect_fn_param_names(&fd.params));
|
||||
inner.extend(self.collect_own_binding_names(&[], body));
|
||||
self.collect_capture_names_shadowed(body, ref_set, &inner, out);
|
||||
}
|
||||
Statement::IfStatement(is) => {
|
||||
self.collect_capture_names_expr(&is.test, ref_set, shadow, out);
|
||||
self.collect_capture_names_stmt(&is.consequent, ref_set, shadow, out);
|
||||
if let Some(alt) = &is.alternate {
|
||||
self.collect_capture_names_stmt(alt, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
Statement::ForStatement(fs) => {
|
||||
if let Some(init) = &fs.init {
|
||||
if let Some(e) = init.as_expression() {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
if let oxide_parser::ForStatementInit::VariableDeclaration(vd) = init {
|
||||
for d in &vd.declarations {
|
||||
if let Some(i) = &d.init {
|
||||
self.collect_capture_names_expr(i, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = &fs.test {
|
||||
self.collect_capture_names_expr(t, ref_set, shadow, out);
|
||||
}
|
||||
if let Some(u) = &fs.update {
|
||||
self.collect_capture_names_expr(u, ref_set, shadow, out);
|
||||
}
|
||||
self.collect_capture_names_stmt(&fs.body, ref_set, shadow, out);
|
||||
}
|
||||
Statement::WhileStatement(w) => {
|
||||
self.collect_capture_names_expr(&w.test, ref_set, shadow, out);
|
||||
self.collect_capture_names_stmt(&w.body, ref_set, shadow, out);
|
||||
}
|
||||
Statement::DoWhileStatement(d) => {
|
||||
self.collect_capture_names_stmt(&d.body, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&d.test, ref_set, shadow, out);
|
||||
}
|
||||
Statement::ForInStatement(fi) => {
|
||||
self.collect_capture_names_expr(&fi.right, ref_set, shadow, out);
|
||||
self.collect_capture_names_stmt(&fi.body, ref_set, shadow, out);
|
||||
}
|
||||
Statement::ForOfStatement(fo) => {
|
||||
self.collect_capture_names_expr(&fo.right, ref_set, shadow, out);
|
||||
self.collect_capture_names_stmt(&fo.body, ref_set, shadow, out);
|
||||
}
|
||||
Statement::BlockStatement(b) => self.collect_capture_names_shadowed(&b.body, ref_set, shadow, out),
|
||||
Statement::TryStatement(ts) => {
|
||||
for s in &ts.block.body {
|
||||
self.collect_capture_names_stmt(s, ref_set, shadow, out);
|
||||
}
|
||||
if let Some(h) = &ts.handler {
|
||||
for s in &h.body.body {
|
||||
self.collect_capture_names_stmt(s, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
if let Some(f) = &ts.finalizer {
|
||||
for s in &f.body {
|
||||
self.collect_capture_names_stmt(s, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ThrowStatement(ts) => self.collect_capture_names_expr(&ts.argument, ref_set, shadow, out),
|
||||
Statement::SwitchStatement(sw) => {
|
||||
self.collect_capture_names_expr(&sw.discriminant, ref_set, shadow, out);
|
||||
for case in &sw.cases {
|
||||
for s in &case.consequent {
|
||||
self.collect_capture_names_stmt(s, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::LabeledStatement(ls) => self.collect_capture_names_stmt(&ls.body, ref_set, shadow, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_capture_names_expr(
|
||||
&self, expr: &Expression, ref_set: &HashSet<String>, shadow: &HashSet<String>, out: &mut HashSet<String>,
|
||||
) {
|
||||
match expr {
|
||||
Expression::Identifier(id) => {
|
||||
let name = id.name.as_str();
|
||||
if ref_set.contains(name) && !shadow.contains(name) {
|
||||
out.insert(id.name.to_string());
|
||||
}
|
||||
}
|
||||
Expression::AssignmentExpression(ae) => {
|
||||
if let oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(ati) = &ae.left {
|
||||
let name = ati.name.as_str();
|
||||
if ref_set.contains(name) && !shadow.contains(name) {
|
||||
out.insert(ati.name.to_string());
|
||||
}
|
||||
}
|
||||
self.collect_capture_names_expr(&ae.right, ref_set, shadow, out);
|
||||
}
|
||||
Expression::UpdateExpression(ue) => {
|
||||
if let oxide_parser::SimpleAssignmentTarget::AssignmentTargetIdentifier(ati) = &ue.argument {
|
||||
let name = ati.name.as_str();
|
||||
if ref_set.contains(name) && !shadow.contains(name) {
|
||||
out.insert(ati.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::FunctionExpression(fe) => {
|
||||
let body: &[Statement] = fe.body.as_ref().map(|b| &b.statements[..]).unwrap_or(&[]);
|
||||
let mut inner = shadow.clone();
|
||||
inner.extend(self.collect_fn_param_names(&fe.params));
|
||||
inner.extend(self.collect_own_binding_names(&[], body));
|
||||
self.collect_capture_names_shadowed(body, ref_set, &inner, out);
|
||||
}
|
||||
Expression::ArrowFunctionExpression(ae) => {
|
||||
let mut inner = shadow.clone();
|
||||
inner.extend(self.collect_fn_param_names(&ae.params));
|
||||
inner.extend(self.collect_own_binding_names(&[], &ae.body.statements));
|
||||
self.collect_capture_names_shadowed(&ae.body.statements, ref_set, &inner, out);
|
||||
}
|
||||
Expression::BinaryExpression(be) => {
|
||||
self.collect_capture_names_expr(&be.left, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&be.right, ref_set, shadow, out);
|
||||
}
|
||||
Expression::UnaryExpression(ue) => self.collect_capture_names_expr(&ue.argument, ref_set, shadow, out),
|
||||
Expression::CallExpression(ce) => {
|
||||
self.collect_capture_names_expr(&ce.callee, ref_set, shadow, out);
|
||||
for a in &ce.arguments {
|
||||
if let Some(e) = a.as_expression() {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::NewExpression(ne) => {
|
||||
self.collect_capture_names_expr(&ne.callee, ref_set, shadow, out);
|
||||
for a in &ne.arguments {
|
||||
if let Some(e) = a.as_expression() {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::SequenceExpression(se) => {
|
||||
for e in &se.expressions {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
Expression::ConditionalExpression(ce) => {
|
||||
self.collect_capture_names_expr(&ce.test, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&ce.consequent, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&ce.alternate, ref_set, shadow, out);
|
||||
}
|
||||
Expression::ArrayExpression(ae) => {
|
||||
for e in &ae.elements {
|
||||
if let Some(e) = e.as_expression() {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::LogicalExpression(le) => {
|
||||
self.collect_capture_names_expr(&le.left, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&le.right, ref_set, shadow, out);
|
||||
}
|
||||
Expression::ComputedMemberExpression(m) => {
|
||||
self.collect_capture_names_expr(&m.object, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&m.expression, ref_set, shadow, out);
|
||||
}
|
||||
Expression::StaticMemberExpression(m) => self.collect_capture_names_expr(&m.object, ref_set, shadow, out),
|
||||
Expression::PrivateFieldExpression(m) => self.collect_capture_names_expr(&m.object, ref_set, shadow, out),
|
||||
Expression::ParenthesizedExpression(p) => self.collect_capture_names_expr(&p.expression, ref_set, shadow, out),
|
||||
Expression::TemplateLiteral(tl) => {
|
||||
for e in &tl.expressions {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
Expression::TaggedTemplateExpression(tt) => {
|
||||
self.collect_capture_names_expr(&tt.tag, ref_set, shadow, out);
|
||||
for e in &tt.quasi.expressions {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
Expression::ObjectExpression(o) => {
|
||||
for prop in &o.properties {
|
||||
if let oxide_parser::ObjectPropertyKind::ObjectProperty(p) = prop {
|
||||
self.collect_capture_names_expr(&p.value, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::ChainExpression(c) => self.collect_capture_names_chain(&c.expression, ref_set, shadow, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_capture_names_chain(
|
||||
&self, element: &oxide_parser::ChainElement, ref_set: &HashSet<String>, shadow: &HashSet<String>,
|
||||
out: &mut HashSet<String>,
|
||||
) {
|
||||
match element {
|
||||
oxide_parser::ChainElement::StaticMemberExpression(m) => {
|
||||
self.collect_capture_names_expr(&m.object, ref_set, shadow, out);
|
||||
}
|
||||
oxide_parser::ChainElement::ComputedMemberExpression(m) => {
|
||||
self.collect_capture_names_expr(&m.object, ref_set, shadow, out);
|
||||
self.collect_capture_names_expr(&m.expression, ref_set, shadow, out);
|
||||
}
|
||||
oxide_parser::ChainElement::PrivateFieldExpression(m) => {
|
||||
self.collect_capture_names_expr(&m.object, ref_set, shadow, out);
|
||||
}
|
||||
oxide_parser::ChainElement::CallExpression(call) => {
|
||||
self.collect_capture_names_expr(&call.callee, ref_set, shadow, out);
|
||||
for a in &call.arguments {
|
||||
if let Some(e) = a.as_expression() {
|
||||
self.collect_capture_names_expr(e, ref_set, shadow, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 分析本函数:哪些绑定被任意深度嵌套函数捕获 → captured_bindings。
|
||||
pub(crate) fn collect_captured_bindings(&self, stmts: &[Statement], own: &HashSet<String>) -> BTreeMap<String, u8> {
|
||||
let mut names = HashSet::new();
|
||||
for stmt in stmts {
|
||||
self.collect_captured_stmt(stmt, own, &mut names);
|
||||
}
|
||||
// 名字排序分配 cell_idx(稳定跨 run,父 MAKE_CELL 与子 upvalue 统一引用)
|
||||
let mut sorted: Vec<String> = names.into_iter().collect();
|
||||
sorted.sort();
|
||||
sorted
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, n)| (n, i as u8))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 只从嵌套函数节点进入扫描(本函数直接引用不算捕获)。
|
||||
fn collect_captured_stmt(&self, stmt: &Statement, own: &HashSet<String>, out: &mut HashSet<String>) {
|
||||
match stmt {
|
||||
Statement::FunctionDeclaration(fd) => {
|
||||
let body: &[Statement] = fd.body.as_ref().map(|b| &b.statements[..]).unwrap_or(&[]);
|
||||
self.collect_capture_names(body, own, out);
|
||||
}
|
||||
Statement::ExpressionStatement(es) => self.collect_captured_expr(&es.expression, own, out),
|
||||
Statement::ReturnStatement(rs) => {
|
||||
if let Some(a) = &rs.argument {
|
||||
self.collect_captured_expr(a, own, out);
|
||||
}
|
||||
}
|
||||
Statement::VariableDeclaration(vd) => {
|
||||
for d in &vd.declarations {
|
||||
if let Some(init) = &d.init {
|
||||
self.collect_captured_expr(init, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::IfStatement(is) => {
|
||||
self.collect_captured_expr(&is.test, own, out);
|
||||
self.collect_captured_stmt(&is.consequent, own, out);
|
||||
if let Some(alt) = &is.alternate {
|
||||
self.collect_captured_stmt(alt, own, out);
|
||||
}
|
||||
}
|
||||
Statement::ForStatement(fs) => {
|
||||
if let Some(init) = &fs.init {
|
||||
if let Some(e) = init.as_expression() {
|
||||
self.collect_captured_expr(e, own, out);
|
||||
}
|
||||
}
|
||||
if let Some(t) = &fs.test {
|
||||
self.collect_captured_expr(t, own, out);
|
||||
}
|
||||
if let Some(u) = &fs.update {
|
||||
self.collect_captured_expr(u, own, out);
|
||||
}
|
||||
self.collect_captured_stmt(&fs.body, own, out);
|
||||
}
|
||||
Statement::WhileStatement(w) => {
|
||||
self.collect_captured_expr(&w.test, own, out);
|
||||
self.collect_captured_stmt(&w.body, own, out);
|
||||
}
|
||||
Statement::DoWhileStatement(d) => {
|
||||
self.collect_captured_stmt(&d.body, own, out);
|
||||
self.collect_captured_expr(&d.test, own, out);
|
||||
}
|
||||
Statement::ForInStatement(fi) => {
|
||||
self.collect_captured_expr(&fi.right, own, out);
|
||||
self.collect_captured_stmt(&fi.body, own, out);
|
||||
}
|
||||
Statement::ForOfStatement(fo) => {
|
||||
self.collect_captured_expr(&fo.right, own, out);
|
||||
self.collect_captured_stmt(&fo.body, own, out);
|
||||
}
|
||||
Statement::BlockStatement(b) => {
|
||||
for s in &b.body {
|
||||
self.collect_captured_stmt(s, own, out);
|
||||
}
|
||||
}
|
||||
Statement::TryStatement(ts) => {
|
||||
for s in &ts.block.body {
|
||||
self.collect_captured_stmt(s, own, out);
|
||||
}
|
||||
if let Some(h) = &ts.handler {
|
||||
for s in &h.body.body {
|
||||
self.collect_captured_stmt(s, own, out);
|
||||
}
|
||||
}
|
||||
if let Some(f) = &ts.finalizer {
|
||||
for s in &f.body {
|
||||
self.collect_captured_stmt(s, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ThrowStatement(ts) => self.collect_captured_expr(&ts.argument, own, out),
|
||||
Statement::SwitchStatement(sw) => {
|
||||
self.collect_captured_expr(&sw.discriminant, own, out);
|
||||
for case in &sw.cases {
|
||||
for s in &case.consequent {
|
||||
self.collect_captured_stmt(s, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::LabeledStatement(ls) => self.collect_captured_stmt(&ls.body, own, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_captured_expr(&self, expr: &Expression, own: &HashSet<String>, out: &mut HashSet<String>) {
|
||||
match expr {
|
||||
Expression::FunctionExpression(fe) => {
|
||||
let body: &[Statement] = fe.body.as_ref().map(|b| &b.statements[..]).unwrap_or(&[]);
|
||||
let mut inner = self.collect_fn_param_names(&fe.params);
|
||||
inner.extend(self.collect_own_binding_names(&[], body));
|
||||
self.collect_capture_names_shadowed(body, own, &inner, out);
|
||||
}
|
||||
Expression::ArrowFunctionExpression(ae) => {
|
||||
let mut inner = self.collect_fn_param_names(&ae.params);
|
||||
inner.extend(self.collect_own_binding_names(&[], &ae.body.statements));
|
||||
self.collect_capture_names_shadowed(&ae.body.statements, own, &inner, out);
|
||||
}
|
||||
Expression::CallExpression(ce) => {
|
||||
self.collect_captured_expr(&ce.callee, own, out);
|
||||
for a in &ce.arguments {
|
||||
if let Some(e) = a.as_expression() {
|
||||
self.collect_captured_expr(e, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::BinaryExpression(be) => {
|
||||
self.collect_captured_expr(&be.left, own, out);
|
||||
self.collect_captured_expr(&be.right, own, out);
|
||||
}
|
||||
Expression::UnaryExpression(ue) => self.collect_captured_expr(&ue.argument, own, out),
|
||||
Expression::LogicalExpression(le) => {
|
||||
self.collect_captured_expr(&le.left, own, out);
|
||||
self.collect_captured_expr(&le.right, own, out);
|
||||
}
|
||||
Expression::ConditionalExpression(ce) => {
|
||||
self.collect_captured_expr(&ce.test, own, out);
|
||||
self.collect_captured_expr(&ce.consequent, own, out);
|
||||
self.collect_captured_expr(&ce.alternate, own, out);
|
||||
}
|
||||
Expression::SequenceExpression(se) => {
|
||||
for e in &se.expressions {
|
||||
self.collect_captured_expr(e, own, out);
|
||||
}
|
||||
}
|
||||
Expression::AssignmentExpression(ae) => self.collect_captured_expr(&ae.right, own, out),
|
||||
Expression::ArrayExpression(ae) => {
|
||||
for e in &ae.elements {
|
||||
if let Some(e) = e.as_expression() {
|
||||
self.collect_captured_expr(e, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 分析子函数 body:引用父级绑定的名字 → upvalue_captures(enclosing_reg 由父 emit 完成后填充)。
|
||||
/// 分析子函数 body:引用父级被捕获绑定的名字 → upvalue_captures。
|
||||
/// cell_idx 直接取父 captured_bindings 映射(父 emit 前已确定,索引一致);
|
||||
/// enclosing_reg 由父 emit 完成后填充(assemble_ir)。
|
||||
pub(crate) fn collect_upvalue_names(
|
||||
&self, body_stmts: &[Statement], parent_captured: &BTreeMap<String, u8>, sub_own: &HashSet<String>,
|
||||
) -> Vec<UpvalueCapture> {
|
||||
let parent_names: HashSet<String> = parent_captured.keys().cloned().collect();
|
||||
let mut names = HashSet::new();
|
||||
self.collect_capture_names_shadowed(body_stmts, &parent_names, sub_own, &mut names);
|
||||
names
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let cell_idx = parent_captured.get(&name).copied().unwrap_or(0);
|
||||
UpvalueCapture {
|
||||
name,
|
||||
enclosing_reg: 0, // assemble_ir 时从父符号表填充
|
||||
cell_idx,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,903 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use oxide_bytecode::module::UpvalueCapture;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::{LabelId, Operand};
|
||||
use oxide_ir::IRFunction;
|
||||
|
||||
use crate::emit_ctx::{LabelCtx, ScopeCtx};
|
||||
use crate::symbol_table::{Binding, ScopeKind, SymbolTable};
|
||||
|
||||
pub use oxide_bytecode::module::Constant;
|
||||
pub use oxide_parser::VariableDeclarationKind;
|
||||
pub use oxide_parser::{AssignmentOperator, BinaryOperator, Expression, Statement, UnaryOperator};
|
||||
|
||||
pub struct Emitter;
|
||||
|
||||
pub fn is_int_literal(value: f64) -> bool {
|
||||
value.fract() == 0.0 && value >= i32::MIN as f64 && value <= i32::MAX as f64
|
||||
}
|
||||
|
||||
pub fn is_side_effect_free(expr: &Expression) -> bool {
|
||||
let mut stack = vec![expr];
|
||||
while let Some(expr) = stack.pop() {
|
||||
match expr {
|
||||
Expression::NumericLiteral(_)
|
||||
| Expression::StringLiteral(_)
|
||||
| Expression::BooleanLiteral(_)
|
||||
| Expression::NullLiteral(_)
|
||||
| Expression::Identifier(_)
|
||||
| Expression::RegExpLiteral(_)
|
||||
| Expression::ThisExpression(_) => {}
|
||||
Expression::ParenthesizedExpression(p) => stack.push(&p.expression),
|
||||
Expression::BinaryExpression(bin) => {
|
||||
stack.push(&bin.left);
|
||||
stack.push(&bin.right);
|
||||
}
|
||||
Expression::UnaryExpression(un) if !matches!(un.operator, UnaryOperator::Delete) => {
|
||||
stack.push(&un.argument);
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
const BUILTIN_GLOBALS: &[&str] = &[
|
||||
"NaN",
|
||||
"undefined",
|
||||
"Infinity",
|
||||
"globalThis",
|
||||
"Object",
|
||||
"Array",
|
||||
"String",
|
||||
"Number",
|
||||
"Boolean",
|
||||
"Function",
|
||||
"Error",
|
||||
"TypeError",
|
||||
"ReferenceError",
|
||||
"RangeError",
|
||||
"SyntaxError",
|
||||
"URIError",
|
||||
"EvalError",
|
||||
"Math",
|
||||
"JSON",
|
||||
"Promise",
|
||||
"Date",
|
||||
"Set",
|
||||
"Map",
|
||||
"RegExp",
|
||||
"Symbol",
|
||||
"parseInt",
|
||||
"parseFloat",
|
||||
"isNaN",
|
||||
"isFinite",
|
||||
"Proxy",
|
||||
"WeakMap",
|
||||
"WeakSet",
|
||||
"WeakRef",
|
||||
"FinalizationRegistry",
|
||||
"Atomics",
|
||||
"SharedArrayBuffer",
|
||||
"ArrayBuffer",
|
||||
"DataView",
|
||||
"Iterator",
|
||||
"BigInt",
|
||||
"Int8Array",
|
||||
"Uint8Array",
|
||||
"Uint8ClampedArray",
|
||||
"Int16Array",
|
||||
"Uint16Array",
|
||||
"Int32Array",
|
||||
"Uint32Array",
|
||||
"Float32Array",
|
||||
"Float64Array",
|
||||
"BigInt64Array",
|
||||
"BigUint64Array",
|
||||
"Reflect",
|
||||
"escape",
|
||||
"unescape",
|
||||
"encodeURI",
|
||||
"decodeURI",
|
||||
"encodeURIComponent",
|
||||
"decodeURIComponent",
|
||||
];
|
||||
|
||||
pub(crate) struct FieldBuffer {
|
||||
pub(crate) insts: Vec<Inst>,
|
||||
pub(crate) labels: Vec<(LabelId, usize)>,
|
||||
}
|
||||
|
||||
/// A labeled-statement scope active during emission. `break label` targets
|
||||
/// `break_label`; `continue label` targets `continue_label` (only set when the
|
||||
/// labeled statement directly wraps an iteration statement).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LabelScope {
|
||||
pub(crate) name: String,
|
||||
pub(crate) break_label: LabelId,
|
||||
pub(crate) continue_label: Option<LabelId>,
|
||||
}
|
||||
|
||||
pub struct CompileCtx {
|
||||
pub(crate) insts: Vec<Inst>,
|
||||
pub(crate) constants: Vec<Constant>,
|
||||
constant_map: HashMap<ConstantKey, u16>,
|
||||
next_reg: u8,
|
||||
pub(crate) max_regs: u8,
|
||||
reserved_reg_start: u8,
|
||||
pub(crate) labels: LabelCtx,
|
||||
pub(crate) scopes: ScopeCtx,
|
||||
pub(crate) nested: Vec<IRFunction>,
|
||||
/// Register holding `this` in the enclosing function context.
|
||||
/// Used by arrow functions to capture lexical `this`.
|
||||
/// Initialized to 254 (conventional this register) at the top level.
|
||||
pub(crate) enclosing_this_reg: u8,
|
||||
pub(crate) in_derived_constructor: bool,
|
||||
pub(crate) in_instance_method: bool,
|
||||
pub(crate) in_static_method: bool,
|
||||
pub(crate) static_block_this_reg: Option<u8>,
|
||||
pub(crate) field_buffer: Option<FieldBuffer>,
|
||||
pub(crate) current_upvalue_captures: Vec<UpvalueCapture>,
|
||||
/// 本函数作用域声明的绑定名(参数 + 变量/函数声明,AST 收集,emit 前确定)。
|
||||
pub(crate) own_bindings: HashSet<String>,
|
||||
/// 本函数被嵌套函数捕获的绑定名 → cell_idx(名字排序分配,稳定跨 run)。
|
||||
/// 捕获判断(MAKE_CELL / CELL_GET / CELL_SET)与子函数 upvalue cell_idx 统一查此映射,
|
||||
/// 消除符号表时序依赖与 cell 索引错位。
|
||||
pub(crate) captured_bindings: BTreeMap<String, u8>,
|
||||
/// Set when alloc_reg() overflows into the reserved this/new.target range (≥254).
|
||||
/// Checked after each emit phase to produce a compile error rather than silent corruption.
|
||||
pub(crate) reg_overflow: bool,
|
||||
pub(crate) const_overflow: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum FunctionBodyContext {
|
||||
Ordinary,
|
||||
Arrow,
|
||||
ClassElement,
|
||||
}
|
||||
|
||||
pub enum ParamSpec<'a> {
|
||||
Identifier(String),
|
||||
Pattern {
|
||||
synthetic_name: String,
|
||||
pattern: &'a oxide_parser::BindingPattern<'a>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ParamSpec<'_> {
|
||||
pub(crate) fn register_name(&self) -> &str {
|
||||
match self {
|
||||
Self::Identifier(name) => name,
|
||||
Self::Pattern { synthetic_name, .. } => synthetic_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum ConstantKey {
|
||||
Number(u64),
|
||||
Int(i32),
|
||||
String(String),
|
||||
Boolean(bool),
|
||||
Null,
|
||||
Undefined,
|
||||
}
|
||||
|
||||
impl CompileCtx {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
insts: Vec::new(),
|
||||
constants: Vec::new(),
|
||||
constant_map: HashMap::new(),
|
||||
next_reg: 1,
|
||||
max_regs: 1,
|
||||
reserved_reg_start: 1,
|
||||
labels: LabelCtx {
|
||||
label_pos: Vec::new(),
|
||||
loop_stack: Vec::new(),
|
||||
switch_stack: Vec::new(),
|
||||
label_scopes: Vec::new(),
|
||||
pending_loop_labels: Vec::new(),
|
||||
label_counter: 0,
|
||||
},
|
||||
scopes: ScopeCtx {
|
||||
symbols: SymbolTable::new(),
|
||||
builtin_reg_map: Vec::new(),
|
||||
private_name_map: Vec::new(),
|
||||
next_private_name_id: 1,
|
||||
},
|
||||
nested: Vec::new(),
|
||||
enclosing_this_reg: 254, // conventional this register at top level
|
||||
in_derived_constructor: false,
|
||||
in_instance_method: false,
|
||||
in_static_method: false,
|
||||
static_block_this_reg: None,
|
||||
field_buffer: None,
|
||||
current_upvalue_captures: Vec::new(),
|
||||
own_bindings: HashSet::new(),
|
||||
captured_bindings: BTreeMap::new(),
|
||||
reg_overflow: false,
|
||||
const_overflow: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn inst(&mut self, inst: Inst) {
|
||||
self.insts.push(inst);
|
||||
}
|
||||
|
||||
pub(crate) fn alloc_reg(&mut self) -> u8 {
|
||||
let r = self.next_reg;
|
||||
// Registers 254 (this) and 255 (new.target) are reserved by the VM.
|
||||
// Allocating into them silently corrupts the call convention, turning
|
||||
// method calls' `this` into garbage. Clamp to 253 and set a flag so
|
||||
// the compiler can surface a proper error after the emit pass.
|
||||
if r >= 254 {
|
||||
self.reg_overflow = true;
|
||||
return 253; // clamp to last safe register; emit continues but reg_overflow triggers error
|
||||
}
|
||||
self.next_reg = self.next_reg.wrapping_add(1);
|
||||
if self.next_reg > self.max_regs {
|
||||
self.max_regs = self.next_reg;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub(crate) fn reset_regs(&mut self) {
|
||||
self.next_reg = self.builtin_reg_floor().max(self.reserved_reg_start);
|
||||
self.labels.label_counter = 0;
|
||||
}
|
||||
|
||||
pub(crate) fn reg_checkpoint(&self) -> u8 {
|
||||
self.next_reg
|
||||
}
|
||||
|
||||
pub(crate) fn restore_reg_checkpoint(&mut self, checkpoint: u8) {
|
||||
self.next_reg = checkpoint;
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_reg(&mut self, reg: u8) {
|
||||
let next = reg.wrapping_add(1);
|
||||
if self.next_reg <= reg {
|
||||
self.next_reg = next;
|
||||
}
|
||||
if self.max_regs < next {
|
||||
self.max_regs = next;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn add_constant(&mut self, c: Constant) -> u16 {
|
||||
if let Some(key) = ConstantKey::from_constant(&c) {
|
||||
if let Some(&idx) = self.constant_map.get(&key) {
|
||||
return idx;
|
||||
}
|
||||
|
||||
if self.constants.len() >= u16::MAX as usize {
|
||||
self.const_overflow = true;
|
||||
return u16::MAX;
|
||||
}
|
||||
let idx = self.constants.len() as u16;
|
||||
self.constants.push(c);
|
||||
self.constant_map.insert(key, idx);
|
||||
return idx;
|
||||
}
|
||||
|
||||
let idx = self.constants.len();
|
||||
if idx >= u16::MAX as usize {
|
||||
self.const_overflow = true;
|
||||
return u16::MAX;
|
||||
}
|
||||
self.constants.push(c);
|
||||
idx as u16
|
||||
}
|
||||
|
||||
pub(crate) fn push_scope(&mut self) {
|
||||
self.scopes.symbols.push_scope();
|
||||
}
|
||||
|
||||
pub(crate) fn pop_scope(&mut self) {
|
||||
self.scopes.symbols.pop_scope();
|
||||
}
|
||||
|
||||
pub(crate) fn declare(
|
||||
&mut self, name: &str, reg: u8, kind: VariableDeclarationKind, is_const: bool,
|
||||
) -> Result<(), String> {
|
||||
self.scopes.symbols.declare(name, reg, kind, is_const)
|
||||
}
|
||||
|
||||
pub(crate) fn declare_initialized(
|
||||
&mut self, name: &str, reg: u8, kind: VariableDeclarationKind, is_const: bool,
|
||||
) -> Result<(), String> {
|
||||
self.scopes.symbols.declare_initialized(name, reg, kind, is_const)
|
||||
}
|
||||
|
||||
pub(crate) fn push_scope_with_kind(&mut self, kind: ScopeKind) {
|
||||
self.scopes.symbols.push_scope_with_kind(kind);
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(&self, name: &str) -> Result<u8, String> {
|
||||
self.scopes.symbols.lookup(name)
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_or_builtin(&mut self, name: &str) -> Result<u8, String> {
|
||||
match self.scopes.symbols.lookup(name) {
|
||||
Ok(reg) => Ok(reg),
|
||||
Err(err) if Self::is_known_builtin(name) && err.contains("is not defined") => {
|
||||
let reg = self.alloc_reg();
|
||||
self.scopes.symbols.pre_register_global(name, reg);
|
||||
self.scopes.builtin_reg_map.push((name.to_string(), reg));
|
||||
Ok(reg)
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_or_global(&mut self, name: &str) -> u8 {
|
||||
if let Some(reg) = self.scopes.symbols.lookup_any(name) {
|
||||
return reg;
|
||||
}
|
||||
let reg = self.alloc_reg();
|
||||
self.scopes.symbols.lookup_or_global(name, reg)
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_const_flag(&self, name: &str) -> bool {
|
||||
self.scopes.symbols.lookup_is_const(name)
|
||||
}
|
||||
|
||||
pub(crate) fn init_var(&mut self, name: &str) {
|
||||
self.scopes.symbols.init_var(name);
|
||||
}
|
||||
|
||||
pub(crate) fn next_label_id(&mut self) -> u32 {
|
||||
let id = self.labels.label_counter;
|
||||
self.labels.label_counter += 1;
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn push_loop(&mut self, break_label: LabelId, continue_label: LabelId) {
|
||||
self.labels.loop_stack.push((break_label, continue_label));
|
||||
}
|
||||
|
||||
pub(crate) fn pop_loop(&mut self) {
|
||||
self.labels.loop_stack.pop();
|
||||
}
|
||||
|
||||
pub(crate) fn current_loop(&self) -> Option<&(LabelId, LabelId)> {
|
||||
self.labels.loop_stack.last()
|
||||
}
|
||||
|
||||
pub(crate) fn push_switch(&mut self, break_label: LabelId) {
|
||||
self.labels.switch_stack.push(break_label);
|
||||
}
|
||||
|
||||
pub(crate) fn pop_switch(&mut self) {
|
||||
self.labels.switch_stack.pop();
|
||||
}
|
||||
|
||||
pub(crate) fn current_switch(&self) -> Option<&LabelId> {
|
||||
self.labels.switch_stack.last()
|
||||
}
|
||||
|
||||
pub(crate) fn push_label_scope(
|
||||
&mut self, name: &str, break_label: LabelId, continue_label: Option<LabelId>,
|
||||
) -> Result<(), String> {
|
||||
if self.labels.label_scopes.iter().any(|s| s.name == name) {
|
||||
return Err(format!("SyntaxError: Label '{name}' has already been declared"));
|
||||
}
|
||||
self.labels.label_scopes.push(LabelScope {
|
||||
name: name.to_string(),
|
||||
break_label,
|
||||
continue_label,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pop_label_scope(&mut self) {
|
||||
self.labels.label_scopes.pop();
|
||||
}
|
||||
|
||||
pub(crate) fn find_label(&self, name: &str) -> Option<&LabelScope> {
|
||||
self.labels.label_scopes.iter().rev().find(|s| s.name == name)
|
||||
}
|
||||
|
||||
/// Queue a label name to be bound to the continue target of the next loop
|
||||
/// emitted as the labeled statement's body. Rejects duplicates in the active
|
||||
/// or pending sets.
|
||||
pub(crate) fn queue_loop_label(&mut self, name: &str) -> Result<(), String> {
|
||||
if self.labels.label_scopes.iter().any(|s| s.name == name)
|
||||
|| self.labels.pending_loop_labels.iter().any(|n| n == name)
|
||||
{
|
||||
return Err(format!("SyntaxError: Label '{name}' has already been declared"));
|
||||
}
|
||||
self.labels.pending_loop_labels.push(name.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drain queued loop labels into active scopes bound to this loop's break and
|
||||
/// continue targets. Returns how many scopes were pushed (to pop after).
|
||||
pub(crate) fn take_pending_loop_labels(&mut self, break_label: LabelId, continue_label: LabelId) -> usize {
|
||||
let names = std::mem::take(&mut self.labels.pending_loop_labels);
|
||||
let count = names.len();
|
||||
for name in names {
|
||||
self.labels.label_scopes.push(LabelScope {
|
||||
name,
|
||||
break_label,
|
||||
continue_label: Some(continue_label),
|
||||
});
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
pub(crate) fn pop_label_scopes(&mut self, n: usize) {
|
||||
for _ in 0..n {
|
||||
self.labels.label_scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_builtin(&self, name: &str) -> bool {
|
||||
self.scopes.builtin_reg_map.iter().any(|(n, _)| n == name)
|
||||
}
|
||||
|
||||
pub(crate) fn is_known_builtin(name: &str) -> bool {
|
||||
BUILTIN_GLOBALS.contains(&name)
|
||||
}
|
||||
|
||||
fn builtin_reg_floor(&self) -> u8 {
|
||||
self.scopes
|
||||
.builtin_reg_map
|
||||
.iter()
|
||||
.map(|(_, reg)| reg.saturating_add(1))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn pre_register_builtins(&mut self) {
|
||||
// Builtin globals are resolved lazily by lookup_or_builtin(). Keeping this
|
||||
// hook preserves the compile pipeline without reserving ~60 registers in
|
||||
// every module.
|
||||
}
|
||||
|
||||
/// 组装 IRFunction(两出口共用),take 走编译产物状态。
|
||||
/// `parent_ctx` 用于补全 upvalue_captures 的 enclosing_reg(父符号表在父 emit 完成后完整)。
|
||||
fn assemble_ir(&mut self, param_layout: oxide_ir::ParamLayout, parent_ctx: Option<&CompileCtx>) -> IRFunction {
|
||||
let upvalue_captures = self
|
||||
.current_upvalue_captures
|
||||
.iter()
|
||||
.map(|u| {
|
||||
let enclosing_reg = parent_ctx
|
||||
.and_then(|p| p.scopes.symbols.lookup_any(u.name.as_str()))
|
||||
.unwrap_or(0);
|
||||
UpvalueCapture {
|
||||
name: u.name.clone(),
|
||||
enclosing_reg,
|
||||
cell_idx: u.cell_idx,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
IRFunction {
|
||||
insts: std::mem::take(&mut self.insts),
|
||||
label_pos: std::mem::take(&mut self.labels.label_pos),
|
||||
label_count: self.labels.label_counter,
|
||||
constants: std::mem::take(&mut self.constants),
|
||||
param_layout,
|
||||
builtin_reg_map: std::mem::take(&mut self.scopes.builtin_reg_map),
|
||||
upvalue_captures,
|
||||
cells_needed: self.captured_bindings.len() as u8,
|
||||
n_registers: self.max_regs,
|
||||
is_arrow: false,
|
||||
is_class_constructor: false,
|
||||
is_derived_constructor: false,
|
||||
needs_home_object: false,
|
||||
captured_this_const_idx: 0,
|
||||
function_name: None,
|
||||
reg_overflow: self.reg_overflow,
|
||||
const_overflow: self.const_overflow,
|
||||
nested: std::mem::take(&mut self.nested),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConstantKey {
|
||||
fn from_constant(value: &Constant) -> Option<Self> {
|
||||
match value {
|
||||
Constant::Number(v) => Some(Self::Number(v.to_bits())),
|
||||
Constant::Int(v) => Some(Self::Int(*v)),
|
||||
Constant::String(v) => Some(Self::String(v.clone())),
|
||||
Constant::Boolean(v) => Some(Self::Boolean(*v)),
|
||||
Constant::Null => Some(Self::Null),
|
||||
Constant::Undefined => Some(Self::Undefined),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Emitter {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
// ── 闭包捕获分析(AST 级,时序无关)──
|
||||
|
||||
/// 收集函数参数的绑定名(BindingIdentifier 形态)。
|
||||
|
||||
|
||||
pub(crate) fn extract_function_parts<'a>(
|
||||
&self, function: &'a oxide_parser::Function<'a>,
|
||||
) -> Result<(Vec<ParamSpec<'a>>, &'a [Statement<'a>]), String> {
|
||||
let mut param_specs = Vec::new();
|
||||
for (idx, param) in function.params.items.iter().enumerate() {
|
||||
match ¶m.pattern {
|
||||
oxide_parser::BindingPattern::BindingIdentifier(bi) => {
|
||||
param_specs.push(ParamSpec::Identifier(bi.name.to_string()));
|
||||
}
|
||||
pattern => {
|
||||
param_specs.push(ParamSpec::Pattern {
|
||||
synthetic_name: format!("@@param_{idx}"),
|
||||
pattern,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let body_stmts: &[Statement] = if let Some(body) = &function.body { &body.statements } else { &[] };
|
||||
Ok((param_specs, body_stmts))
|
||||
}
|
||||
|
||||
/// Compile a function body (used for FD, FE, and arrow functions).
|
||||
/// This performs both counting and emitting in one pass.
|
||||
/// When `is_expression_body` is true (arrow function with expression body),
|
||||
/// the last expression's value is returned instead of undefined.
|
||||
/// `is_arrow` controls whether super flags are inherited from the parent scope
|
||||
/// (true for arrow functions, which have lexical super) or reset to false
|
||||
/// (false for regular functions, which create a new super scope).
|
||||
pub(crate) fn compile_function_body<'a>(
|
||||
&self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx,
|
||||
is_expression_body: bool, is_arrow: bool,
|
||||
) -> Result<IRFunction, String> {
|
||||
let body_context = if is_arrow {
|
||||
FunctionBodyContext::Arrow
|
||||
} else {
|
||||
FunctionBodyContext::Ordinary
|
||||
};
|
||||
self.compile_function_body_with_bindings(
|
||||
param_specs,
|
||||
body_stmts,
|
||||
parent_ctx,
|
||||
is_expression_body,
|
||||
&[],
|
||||
body_context,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn compile_function_body_with_bindings<'a>(
|
||||
&self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx,
|
||||
is_expression_body: bool, extra_bindings: &[(&str, u8)], body_context: FunctionBodyContext,
|
||||
) -> Result<IRFunction, String> {
|
||||
self.compile_function_body_with_field_hooks(
|
||||
param_specs,
|
||||
body_stmts,
|
||||
parent_ctx,
|
||||
is_expression_body,
|
||||
extra_bindings,
|
||||
body_context,
|
||||
None::<fn(&Emitter, &mut CompileCtx) -> Result<(), String>>,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/// Pre-register all builtin identifiers referenced anywhere in this body
|
||||
/// (expressions, member objects, call args, class fields, etc.) so their
|
||||
/// register slots are reserved *before* any temporary register is emitted.
|
||||
///
|
||||
/// Without this, single-pass emission lazily allocates builtin slots via
|
||||
/// `lookup_or_builtin` at first use, which can collide with a temporary
|
||||
/// register already reused by `restore_reg_checkpoint`. Pre-scanning moves
|
||||
/// builtin slot allocation ahead of the temporary register pool.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn compile_function_body_with_field_hooks<'a, E>(
|
||||
&self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx,
|
||||
is_expression_body: bool, extra_bindings: &[(&str, u8)], body_context: FunctionBodyContext,
|
||||
mut emit_fields: Option<E>, fields_after_super: bool,
|
||||
) -> Result<IRFunction, String>
|
||||
where
|
||||
E: FnMut(&Emitter, &mut CompileCtx) -> Result<(), String>,
|
||||
{
|
||||
let mut ctx = CompileCtx::new();
|
||||
|
||||
// Inherit parent's builtin_reg_map so builtin identifiers (Math, Object, etc.)
|
||||
// resolve to the correct pre-allocated registers in the sub-module's register file.
|
||||
ctx.scopes.builtin_reg_map = parent_ctx.scopes.builtin_reg_map.clone();
|
||||
ctx.scopes.private_name_map = parent_ctx.scopes.private_name_map.clone();
|
||||
ctx.scopes.next_private_name_id = parent_ctx.scopes.next_private_name_id;
|
||||
|
||||
// Propagate enclosing_this_reg so nested arrow functions capture the correct `this`.
|
||||
ctx.enclosing_this_reg = parent_ctx.enclosing_this_reg;
|
||||
// Arrow functions inherit lexical super. Class method bodies also need the
|
||||
// class-provided super context for their top-level body compilation.
|
||||
if matches!(body_context, FunctionBodyContext::Arrow | FunctionBodyContext::ClassElement) {
|
||||
ctx.in_derived_constructor = parent_ctx.in_derived_constructor;
|
||||
ctx.in_instance_method = parent_ctx.in_instance_method;
|
||||
ctx.in_static_method = parent_ctx.in_static_method;
|
||||
} else {
|
||||
ctx.in_derived_constructor = false;
|
||||
ctx.in_instance_method = false;
|
||||
ctx.in_static_method = false;
|
||||
}
|
||||
|
||||
// Inherit parent's global scope entries so previously-declared function names
|
||||
// are visible from within the body.
|
||||
let mut inherited_reg_start = 1u8.max(ctx.builtin_reg_floor());
|
||||
for (name, binding) in &parent_ctx.scopes.symbols.scopes[0].bindings {
|
||||
ctx.scopes.symbols.scopes[0].bindings.insert(
|
||||
name.clone(),
|
||||
Binding {
|
||||
reg: binding.reg,
|
||||
initialized: binding.initialized,
|
||||
is_const: binding.is_const,
|
||||
},
|
||||
);
|
||||
inherited_reg_start = inherited_reg_start.max(binding.reg.saturating_add(1));
|
||||
}
|
||||
for (name, reg) in extra_bindings {
|
||||
ctx.scopes.symbols.scopes[0].bindings.insert(
|
||||
(*name).to_string(),
|
||||
Binding {
|
||||
reg: *reg,
|
||||
initialized: true,
|
||||
is_const: true,
|
||||
},
|
||||
);
|
||||
inherited_reg_start = inherited_reg_start.max(reg.saturating_add(1));
|
||||
}
|
||||
ctx.reserved_reg_start = inherited_reg_start.max(1);
|
||||
|
||||
// Align next_reg with builtin count so both count and emit passes start at the
|
||||
// same register offset (params go after builtin slots).
|
||||
ctx.reset_regs();
|
||||
|
||||
let param_base = self.emit_params_prologue(param_specs, body_stmts, parent_ctx, &mut ctx, body_context)?;
|
||||
|
||||
self.predeclare_function_declarations(body_stmts, &mut ctx);
|
||||
|
||||
// Pre-register builtin identifier references before emitting any temporary
|
||||
// register, so builtin slots never collide with reused temporaries.
|
||||
self.pre_register_builtin_references(body_stmts, &mut ctx);
|
||||
|
||||
// Pre-declare `var` names so hoisted function declarations (emitted in the
|
||||
// first sub-pass below) can resolve the outer vars they close over.
|
||||
self.predeclare_var_declarations(body_stmts, &mut ctx);
|
||||
|
||||
if let Some(emit) = emit_fields.as_mut() {
|
||||
if fields_after_super {
|
||||
let mut parent_insts = Vec::new();
|
||||
let mut parent_label_pos = Vec::new();
|
||||
std::mem::swap(&mut ctx.insts, &mut parent_insts);
|
||||
std::mem::swap(&mut ctx.labels.label_pos, &mut parent_label_pos);
|
||||
emit(self, &mut ctx)?;
|
||||
let field_buffer = FieldBuffer {
|
||||
insts: std::mem::take(&mut ctx.insts),
|
||||
labels: std::mem::take(&mut ctx.labels.label_pos)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(id, pos)| pos.map(|p| (id as LabelId, p)))
|
||||
.collect(),
|
||||
};
|
||||
ctx.insts = parent_insts;
|
||||
ctx.labels.label_pos = parent_label_pos;
|
||||
ctx.field_buffer = Some(field_buffer);
|
||||
} else {
|
||||
emit(self, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Emit body statements(先函数声明 hoisting,再其余)。
|
||||
let last_result_reg = self.emit_body_stmts(body_stmts, &mut ctx)?;
|
||||
|
||||
// Emit implicit RETURN: expression body returns the last expression,
|
||||
// statement body returns undefined.
|
||||
if is_expression_body {
|
||||
if let Some(reg) = last_result_reg {
|
||||
ctx.inst(Inst::new(OpCode::RETURN, Operand::Reg(reg as u32), Operand::None, Operand::None));
|
||||
} else {
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
let undef_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(undef_reg as u32), undef_idx));
|
||||
ctx.inst(Inst::new(OpCode::RETURN, Operand::Reg(undef_reg as u32), Operand::None, Operand::None));
|
||||
}
|
||||
} else {
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
let undef_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(undef_reg as u32), undef_idx));
|
||||
ctx.inst(Inst::new(OpCode::RETURN, Operand::Reg(undef_reg as u32), Operand::None, Operand::None));
|
||||
}
|
||||
|
||||
let ir = ctx.assemble_ir(
|
||||
oxide_ir::ParamLayout {
|
||||
base: param_base as u32,
|
||||
count: param_specs.len() as u32,
|
||||
},
|
||||
Some(parent_ctx),
|
||||
);
|
||||
Ok(ir)
|
||||
}
|
||||
|
||||
/// 参数 prologue:函数作用域 + 参数声明/解构 + 闭包捕获与 upvalue 分析。返回 param_base。
|
||||
fn emit_params_prologue<'a>(
|
||||
&self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx,
|
||||
ctx: &mut CompileCtx, body_context: FunctionBodyContext,
|
||||
) -> Result<u8, String> {
|
||||
ctx.push_scope_with_kind(ScopeKind::FunctionScope);
|
||||
let param_base = ctx.next_reg;
|
||||
|
||||
// Emit parameters and destructuring prologue.
|
||||
for spec in param_specs {
|
||||
let name = spec.register_name();
|
||||
let reg = ctx.alloc_reg();
|
||||
ctx.declare_initialized(name, reg, VariableDeclarationKind::Var, false)?;
|
||||
}
|
||||
|
||||
for spec in param_specs {
|
||||
if let ParamSpec::Pattern { synthetic_name, pattern } = spec {
|
||||
let src_reg = ctx.lookup(synthetic_name)?;
|
||||
self.emit_binding_pattern(pattern, src_reg, VariableDeclarationKind::Var, false, ctx)?;
|
||||
}
|
||||
}
|
||||
|
||||
// 闭包捕获分析(AST 级,emit 前确定,时序无关)
|
||||
let param_names: Vec<&str> = param_specs.iter().map(|s| s.register_name()).collect();
|
||||
ctx.own_bindings = self.collect_own_binding_names(¶m_names, body_stmts);
|
||||
ctx.captured_bindings = self.collect_captured_bindings(body_stmts, &ctx.own_bindings);
|
||||
|
||||
// Free variable analysis for upvalue capture (Ordinary + Arrow functions only)
|
||||
if matches!(body_context, FunctionBodyContext::Ordinary | FunctionBodyContext::Arrow) {
|
||||
ctx.current_upvalue_captures =
|
||||
self.collect_upvalue_names(body_stmts, &parent_ctx.captured_bindings, &ctx.own_bindings);
|
||||
}
|
||||
|
||||
Ok(param_base)
|
||||
}
|
||||
|
||||
/// 双 sub-pass emit body:先函数声明(hoisting),再其余语句。返回最后结果寄存器。
|
||||
fn emit_body_stmts(&self, body_stmts: &[Statement], ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let mut last_result_reg = None;
|
||||
for stmt in body_stmts {
|
||||
if matches!(stmt, Statement::FunctionDeclaration(_)) {
|
||||
if let Some(reg) = self.emit_statement(stmt, ctx)? {
|
||||
last_result_reg = Some(reg);
|
||||
}
|
||||
}
|
||||
}
|
||||
for stmt in body_stmts {
|
||||
if matches!(stmt, Statement::FunctionDeclaration(_)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(reg) = self.emit_statement(stmt, ctx)? {
|
||||
last_result_reg = Some(reg);
|
||||
}
|
||||
}
|
||||
Ok(last_result_reg)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::ExpressionStatement(_) | Statement::ReturnStatement(_) | Statement::EmptyStatement(_) => {
|
||||
self.emit_basic_domain(stmt, ctx)
|
||||
}
|
||||
Statement::BlockStatement(_) => self.emit_block_domain(stmt, ctx),
|
||||
Statement::VariableDeclaration(_) | Statement::FunctionDeclaration(_) | Statement::ClassDeclaration(_) => {
|
||||
self.emit_declaration_domain(stmt, ctx)
|
||||
}
|
||||
Statement::IfStatement(_) => self.emit_control_domain(stmt, ctx),
|
||||
Statement::WhileStatement(_)
|
||||
| Statement::DoWhileStatement(_)
|
||||
| Statement::ForStatement(_)
|
||||
| Statement::ForInStatement(_)
|
||||
| Statement::ForOfStatement(_) => self.emit_iteration_domain(stmt, ctx),
|
||||
Statement::SwitchStatement(_) => self.emit_switch_domain(stmt, ctx),
|
||||
Statement::ThrowStatement(_) | Statement::TryStatement(_) => self.emit_exception_domain(stmt, ctx),
|
||||
Statement::BreakStatement(b) => self.emit_break_statement(b, ctx),
|
||||
Statement::ContinueStatement(c) => self.emit_continue_statement(c, ctx),
|
||||
Statement::LabeledStatement(ls) => self.emit_labeled_statement(ls, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_expression(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::NumericLiteral(_)
|
||||
| Expression::StringLiteral(_)
|
||||
| Expression::BooleanLiteral(_)
|
||||
| Expression::NullLiteral(_)
|
||||
| Expression::RegExpLiteral(_) => self.emit_literal(expr, ctx),
|
||||
Expression::BinaryExpression(_)
|
||||
| Expression::PrivateInExpression(_)
|
||||
| Expression::UnaryExpression(_)
|
||||
| Expression::ConditionalExpression(_)
|
||||
| Expression::LogicalExpression(_)
|
||||
| Expression::UpdateExpression(_) => self.emit_operator(expr, ctx),
|
||||
Expression::StaticMemberExpression(_)
|
||||
| Expression::ComputedMemberExpression(_)
|
||||
| Expression::PrivateFieldExpression(_)
|
||||
| Expression::ChainExpression(_) => self.emit_member_domain(expr, ctx),
|
||||
Expression::ObjectExpression(_) | Expression::ArrayExpression(_) => self.emit_object_domain(expr, ctx),
|
||||
Expression::AssignmentExpression(assign) => self.emit_assignment_expression(assign, ctx),
|
||||
Expression::TemplateLiteral(_) | Expression::TaggedTemplateExpression(_) => {
|
||||
self.emit_template_domain(expr, ctx)
|
||||
}
|
||||
Expression::ArrowFunctionExpression(_)
|
||||
| Expression::FunctionExpression(_)
|
||||
| Expression::ClassExpression(_)
|
||||
| Expression::NewExpression(_) => self.emit_function_domain(expr, ctx),
|
||||
Expression::Identifier(ident) => self.emit_identifier_expression(ident, ctx),
|
||||
Expression::CallExpression(_) => self.emit_call_domain(expr, ctx),
|
||||
Expression::ThisExpression(_) => self.emit_this_expression(ctx),
|
||||
Expression::SequenceExpression(seq) => self.emit_sequence_expression(seq, ctx),
|
||||
Expression::ParenthesizedExpression(p) => self.emit_parenthesized_expression(p, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit a full program into an IRFunction (top-level module body).
|
||||
/// Split from the original `Compiler::compile`: this is the emit half;
|
||||
/// oxide_compiler::Compiler::compile calls this then `oxide_ir::lower::lower`.
|
||||
pub fn emit_program(&self, program: &oxide_parser::Program) -> Result<IRFunction, String> {
|
||||
let mut ctx = CompileCtx::new();
|
||||
ctx.pre_register_builtins();
|
||||
self.predeclare_function_declarations(&program.body, &mut ctx);
|
||||
|
||||
// Pre-register builtin identifier references before any temporary register
|
||||
// is emitted, keeping builtin slots clear of the temporary register pool.
|
||||
self.pre_register_builtin_references(&program.body, &mut ctx);
|
||||
|
||||
// Pre-declare top-level `var` names so hoisted function declarations
|
||||
// (emitted in the first sub-pass below) can resolve the outer vars.
|
||||
self.predeclare_var_declarations(&program.body, &mut ctx);
|
||||
|
||||
// 闭包捕获分析(AST 级,emit 前确定)
|
||||
ctx.own_bindings = self.collect_own_binding_names(&[], &program.body);
|
||||
ctx.captured_bindings = self.collect_captured_bindings(&program.body, &ctx.own_bindings);
|
||||
|
||||
// First sub-pass: emit FunctionDeclarations (hoisting)
|
||||
// This ensures function objects are available before any code runs.
|
||||
for stmt in &program.body {
|
||||
if matches!(stmt, Statement::FunctionDeclaration(_)) {
|
||||
self.emit_statement(stmt, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Second sub-pass: emit all other statements
|
||||
let mut last_result: Option<u8> = None;
|
||||
for stmt in &program.body {
|
||||
if matches!(stmt, Statement::FunctionDeclaration(_)) {
|
||||
continue; // Already emitted above
|
||||
}
|
||||
match self.emit_statement(stmt, &mut ctx)? {
|
||||
Some(r) => last_result = Some(r),
|
||||
None => last_result = None,
|
||||
}
|
||||
}
|
||||
if let Some(r) = last_result {
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::None, Operand::Reg(r as u32), Operand::None));
|
||||
} else {
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
ctx.inst(Inst::load_const(Operand::None, undef_idx));
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::HALT, Operand::None, Operand::None, Operand::None));
|
||||
|
||||
let ir = ctx.assemble_ir(
|
||||
oxide_ir::ParamLayout {
|
||||
base: ctx.scopes.builtin_reg_map.len() as u32,
|
||||
count: 0,
|
||||
},
|
||||
None,
|
||||
);
|
||||
Ok(ir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Emitter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Grouped `CompileCtx` sub-contexts.
|
||||
//!
|
||||
//! Splits the compiler's central `CompileCtx` so syntax-domain workers borrow
|
||||
//! only the slice they need: `LabelCtx` for jump-target resolution, `ScopeCtx`
|
||||
//! for identifier binding. `PatternCtx` is reserved for destructuring work.
|
||||
//! Execution-stream fields (insts, registers, pc, …) stay flat on
|
||||
//! `CompileCtx`.
|
||||
|
||||
use crate::symbol_table::SymbolTable;
|
||||
use crate::LabelScope;
|
||||
use oxide_ir::operand::LabelId;
|
||||
|
||||
/// Jump-target / labeled-statement resolution state.
|
||||
pub(crate) struct LabelCtx {
|
||||
/// label id → 指令下标。id 连续递增,Vec 索引即 id;写入前须扩容。
|
||||
pub(crate) label_pos: Vec<Option<usize>>,
|
||||
pub(crate) loop_stack: Vec<(LabelId, LabelId)>,
|
||||
pub(crate) switch_stack: Vec<LabelId>,
|
||||
/// Active labeled-statement scopes (resolves `break label` / `continue label`).
|
||||
pub(crate) label_scopes: Vec<LabelScope>,
|
||||
/// Label names awaiting binding to the next emitted loop's continue target.
|
||||
pub(crate) pending_loop_labels: Vec<String>,
|
||||
pub(crate) label_counter: u32,
|
||||
}
|
||||
|
||||
impl LabelCtx {
|
||||
/// 按 id 扩容后写入 label 定义位置。
|
||||
pub(crate) fn set_label_pos(&mut self, id: LabelId, pos: usize) {
|
||||
if id as usize >= self.label_pos.len() {
|
||||
self.label_pos.resize(id as usize + 1, None);
|
||||
}
|
||||
self.label_pos[id as usize] = Some(pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifier-binding state: symbols, builtin registers, private names.
|
||||
pub(crate) struct ScopeCtx {
|
||||
pub(crate) symbols: SymbolTable,
|
||||
pub(crate) builtin_reg_map: Vec<(String, u8)>,
|
||||
pub(crate) private_name_map: Vec<(String, u32)>,
|
||||
pub(crate) next_private_name_id: u32,
|
||||
}
|
||||
|
||||
/// Reserved for destructuring-pattern state (Phase 15). Intentionally empty
|
||||
/// today; named so future pattern work has a home without touching `ScopeCtx`.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct PatternCtx;
|
||||
@@ -0,0 +1,174 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::AssignmentOperator;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_assignment_expression(
|
||||
&self, assign: &oxide_parser::AssignmentExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
if let oxide_parser::AssignmentTarget::StaticMemberExpression(member) = &assign.left {
|
||||
if let Some(logical_op) = assign.operator.to_logical_operator() {
|
||||
let store_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let prop_name = member.property.name.as_str();
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::ic_get(Operand::Reg(result_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
self.emit_logical_assign_test(logical_op, result_reg, store_label, end_label, ctx)?;
|
||||
ctx.labels.set_label_pos(store_label, ctx.insts.len());
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
ctx.inst(Inst::ic_set(Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(val_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
return Ok(result_reg);
|
||||
}
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
let prop_name = member.property.name.as_str();
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
if assign.operator != AssignmentOperator::Assign {
|
||||
let obj = Operand::Reg(obj_reg as u32);
|
||||
let val = Operand::Reg(val_reg as u32);
|
||||
let key = Operand::Reg(key_reg as u32);
|
||||
match assign.operator {
|
||||
AssignmentOperator::Addition => ctx.inst(Inst::compound_member_add(obj, val, key)),
|
||||
AssignmentOperator::Subtraction => ctx.inst(Inst::compound_member_sub(obj, val, key)),
|
||||
AssignmentOperator::Multiplication => ctx.inst(Inst::compound_member_mul(obj, val, key)),
|
||||
AssignmentOperator::Division => ctx.inst(Inst::compound_member_div(obj, val, key)),
|
||||
AssignmentOperator::Remainder => ctx.inst(Inst::compound_member_mod(obj, val, key)),
|
||||
AssignmentOperator::Exponential => ctx.inst(Inst::compound_member_exp(obj, val, key)),
|
||||
_ => return Err(format!("compound assignment operator {:?} not supported", assign.operator)),
|
||||
}
|
||||
Ok(val_reg)
|
||||
} else {
|
||||
ctx.inst(Inst::ic_set(Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(val_reg)
|
||||
}
|
||||
} else if let oxide_parser::AssignmentTarget::ComputedMemberExpression(member) = &assign.left {
|
||||
if let Some(logical_op) = assign.operator.to_logical_operator() {
|
||||
let store_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(result_reg as u32)));
|
||||
self.emit_logical_assign_test(logical_op, result_reg, store_label, end_label, ctx)?;
|
||||
ctx.labels.set_label_pos(store_label, ctx.insts.len());
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::SET_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(val_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
return Ok(result_reg);
|
||||
}
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::SET_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
Ok(val_reg)
|
||||
} else if let oxide_parser::AssignmentTarget::PrivateFieldExpression(member) = &assign.left {
|
||||
if assign.operator != AssignmentOperator::Assign {
|
||||
return Err("compound assignment to private fields not supported".into());
|
||||
}
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::SET_PRIVATE, Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(val_reg)
|
||||
} else if let oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(id_ref) = &assign.left {
|
||||
if assign.operator != AssignmentOperator::Assign {
|
||||
if let Some(logical_op) = assign.operator.to_logical_operator() {
|
||||
let store_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let name = id_ref.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(var_reg as u32), Operand::None));
|
||||
self.emit_logical_assign_test(logical_op, result_reg, store_label, end_label, ctx)?;
|
||||
ctx.labels.set_label_pos(store_label, ctx.insts.len());
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
let is_const = ctx.lookup_const_flag(name);
|
||||
let const_flag = if is_const { 1 } else { 0 };
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(val_reg as u32), Operand::Imm(const_flag)));
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(val_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
Ok(result_reg)
|
||||
} else if assign.operator == AssignmentOperator::Addition
|
||||
|| assign.operator == AssignmentOperator::Subtraction
|
||||
|| assign.operator == AssignmentOperator::Multiplication
|
||||
|| assign.operator == AssignmentOperator::Division
|
||||
|| assign.operator == AssignmentOperator::Remainder
|
||||
|| assign.operator == AssignmentOperator::Exponential
|
||||
|| assign.operator == AssignmentOperator::BitwiseAnd
|
||||
|| assign.operator == AssignmentOperator::BitwiseOR
|
||||
|| assign.operator == AssignmentOperator::BitwiseXOR
|
||||
|| assign.operator == AssignmentOperator::ShiftLeft
|
||||
|| assign.operator == AssignmentOperator::ShiftRight
|
||||
|| assign.operator == AssignmentOperator::ShiftRightZeroFill
|
||||
{
|
||||
let rhs = self.emit_expression(&assign.right, ctx)?;
|
||||
let name = id_ref.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
let op = match assign.operator {
|
||||
AssignmentOperator::Addition => OpCode::COMPOUND_ADD,
|
||||
AssignmentOperator::Subtraction => OpCode::COMPOUND_SUB,
|
||||
AssignmentOperator::Multiplication => OpCode::COMPOUND_MUL,
|
||||
AssignmentOperator::Division => OpCode::COMPOUND_DIV,
|
||||
AssignmentOperator::Remainder => OpCode::COMPOUND_MOD,
|
||||
AssignmentOperator::Exponential => OpCode::COMPOUND_EXP,
|
||||
AssignmentOperator::BitwiseAnd => OpCode::COMPOUND_AND,
|
||||
AssignmentOperator::BitwiseOR => OpCode::COMPOUND_OR,
|
||||
AssignmentOperator::BitwiseXOR => OpCode::COMPOUND_XOR,
|
||||
AssignmentOperator::ShiftLeft => OpCode::COMPOUND_SHL,
|
||||
AssignmentOperator::ShiftRight => OpCode::COMPOUND_SHR,
|
||||
AssignmentOperator::ShiftRightZeroFill => OpCode::COMPOUND_USHR,
|
||||
_ => return Err(format!("compound assignment operator {:?} not supported", assign.operator)),
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(var_reg as u32), Operand::Reg(rhs as u32), Operand::None));
|
||||
Ok(var_reg)
|
||||
} else {
|
||||
Err(format!("compound assignment operator {:?} not supported", assign.operator))
|
||||
}
|
||||
} else {
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
let name = id_ref.name.as_str();
|
||||
// Check if target is an upvalue reference
|
||||
if let Some(uv_idx) = ctx.current_upvalue_captures.iter().position(|u| u.name == name) {
|
||||
ctx.inst(Inst::new(OpCode::STORE_UPVALUE, Operand::None, Operand::Reg(val_reg as u32), Operand::Imm(uv_idx as u16)));
|
||||
return Ok(val_reg);
|
||||
}
|
||||
// Check if target is a captured cell
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(name) {
|
||||
ctx.inst(Inst::new(OpCode::CELL_SET, Operand::None, Operand::Reg(val_reg as u32), Operand::Imm(cell_idx as u16)));
|
||||
return Ok(val_reg);
|
||||
}
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
let is_const = ctx.lookup_const_flag(name);
|
||||
let const_flag = if is_const { 1 } else { 0 };
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(val_reg as u32), Operand::Imm(const_flag)));
|
||||
Ok(val_reg)
|
||||
}
|
||||
} else if matches!(
|
||||
&assign.left,
|
||||
oxide_parser::AssignmentTarget::ArrayAssignmentTarget(_)
|
||||
| oxide_parser::AssignmentTarget::ObjectAssignmentTarget(_)
|
||||
) {
|
||||
if assign.operator != AssignmentOperator::Assign {
|
||||
return Err("compound destructuring assignment not supported".into());
|
||||
}
|
||||
let val_reg = self.emit_expression(&assign.right, ctx)?;
|
||||
self.emit_assign_target(&assign.left, val_reg, ctx)?;
|
||||
Ok(val_reg)
|
||||
} else {
|
||||
Err("assignment target not supported".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Expression;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_call_expression(&self, call: &oxide_parser::CallExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
if matches!(&call.callee, Expression::Super(_)) {
|
||||
if !ctx.in_derived_constructor {
|
||||
return Err("super() only supported in derived constructors".into());
|
||||
}
|
||||
let mut arg_regs = Vec::new();
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
arg_regs.push(self.emit_expression(expr, ctx)?);
|
||||
}
|
||||
}
|
||||
let first_arg_reg = if arg_regs.is_empty() { 0u8 } else { arg_regs[0] };
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::super_call(
|
||||
Operand::Reg(result_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
if let Some(mut field_buffer) = ctx.field_buffer.take() {
|
||||
let insert_inst = ctx.insts.len();
|
||||
ctx.insts.append(&mut field_buffer.insts);
|
||||
for (label, relative) in field_buffer.labels {
|
||||
ctx.labels.set_label_pos(label, insert_inst + relative);
|
||||
}
|
||||
}
|
||||
return Ok(result_reg);
|
||||
}
|
||||
let (callee_reg, this_reg) = match &call.callee {
|
||||
Expression::PrivateFieldExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
let callee_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PRIVATE, Operand::Reg(callee_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
(callee_reg, obj_reg)
|
||||
}
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
let is_super_member = matches!(&member.object, Expression::Super(_));
|
||||
let obj_reg = if is_super_member {
|
||||
let this_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(this_reg as u32), Operand::This, Operand::None));
|
||||
this_reg
|
||||
} else {
|
||||
self.emit_expression(&member.object, ctx)?
|
||||
};
|
||||
let prop_name = member.property.name.as_str();
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
let callee_reg = ctx.alloc_reg();
|
||||
if is_super_member {
|
||||
if !ctx.in_instance_method && !ctx.in_static_method && !ctx.in_derived_constructor {
|
||||
return Err("super property only supported in class methods".into());
|
||||
}
|
||||
let op = if ctx.in_static_method {
|
||||
OpCode::SUPER_STATIC_GET_PROP
|
||||
} else {
|
||||
OpCode::SUPER_GET_PROP
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(callee_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(callee_reg as u32), Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::ic_get(Operand::Reg(callee_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
}
|
||||
(callee_reg, obj_reg)
|
||||
}
|
||||
_ => {
|
||||
let callee_reg = self.emit_expression(&call.callee, ctx)?;
|
||||
let this_idx = ctx.add_constant(Constant::Undefined);
|
||||
let this_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(this_reg as u32), this_idx));
|
||||
(callee_reg, this_reg)
|
||||
}
|
||||
};
|
||||
let mut arg_regs = Vec::new();
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
arg_regs.push(self.emit_expression(expr, ctx)?);
|
||||
}
|
||||
}
|
||||
let first_arg_reg = if arg_regs.is_empty() { 0u8 } else { arg_regs[0] };
|
||||
let op = match &call.callee {
|
||||
Expression::Identifier(ident) if ctx.is_builtin(ident.name.as_str()) => OpCode::CALL_NATIVE,
|
||||
_ => OpCode::CALL,
|
||||
};
|
||||
match op {
|
||||
OpCode::CALL => {
|
||||
ctx.inst(Inst::call(
|
||||
Operand::Reg(callee_reg as u32),
|
||||
Operand::Reg(this_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
}
|
||||
OpCode::CALL_NATIVE => {
|
||||
ctx.inst(Inst::call_native(
|
||||
Operand::Reg(callee_reg as u32),
|
||||
Operand::Reg(this_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::None, Operand::None));
|
||||
Ok(result_reg)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_call_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::CallExpression(call) => self.emit_call_expression(call, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use crate::{CompileCtx, Emitter, ParamSpec};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_parser::{Class, Expression, Statement};
|
||||
|
||||
impl Emitter {
|
||||
fn emit_arrow_function_expression(
|
||||
&self, arrow: &oxide_parser::ArrowFunctionExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
// Rest params not yet supported
|
||||
if let Some(_rest) = &arrow.params.rest {
|
||||
return Err("rest params in arrow functions not yet supported".into());
|
||||
}
|
||||
|
||||
// Extract param names (same pattern as FunctionExpression)
|
||||
let mut param_names = Vec::new();
|
||||
for (idx, param) in arrow.params.items.iter().enumerate() {
|
||||
match ¶m.pattern {
|
||||
oxide_parser::BindingPattern::BindingIdentifier(bi) => {
|
||||
param_names.push(ParamSpec::Identifier(bi.name.to_string()));
|
||||
}
|
||||
pattern => {
|
||||
param_names.push(ParamSpec::Pattern {
|
||||
synthetic_name: format!("@@param_{idx}"),
|
||||
pattern,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Expression body: pass body statements directly with is_expression_body=true.
|
||||
// Statement body: pass body statements with is_expression_body=false.
|
||||
let body_stmts = &arrow.body.statements;
|
||||
let is_expr_body = arrow.expression;
|
||||
|
||||
let mut sub_module = self.compile_function_body(¶m_names, body_stmts, ctx, is_expr_body, true)?;
|
||||
sub_module.is_arrow = true;
|
||||
|
||||
ctx.nested.push(sub_module);
|
||||
// 1-indexed: 0 = no sub_module (sentinel)
|
||||
let sub_idx = ctx.nested.len() as u16;
|
||||
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::create_closure(Operand::Reg(r as u32), sub_idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_function_expression(&self, fe: &oxide_parser::Function, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
// FunctionExpression: compile body, emit LOAD_CONST(BytecodeFunc)
|
||||
let mut param_names = Vec::new();
|
||||
for (idx, param) in fe.params.items.iter().enumerate() {
|
||||
match ¶m.pattern {
|
||||
oxide_parser::BindingPattern::BindingIdentifier(bi) => {
|
||||
param_names.push(ParamSpec::Identifier(bi.name.to_string()));
|
||||
}
|
||||
pattern => {
|
||||
param_names.push(ParamSpec::Pattern {
|
||||
synthetic_name: format!("@@param_{idx}"),
|
||||
pattern,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let body_stmts: &[Statement] = if let Some(body) = &fe.body { &body.statements } else { &[] };
|
||||
|
||||
let mut sub_module = self.compile_function_body(¶m_names, body_stmts, ctx, false, false)?;
|
||||
if let Some(id) = &fe.id {
|
||||
sub_module.function_name = Some(id.name.to_string());
|
||||
}
|
||||
ctx.nested.push(sub_module);
|
||||
// 1-indexed: 0 = no sub_module (sentinel)
|
||||
let sub_idx = ctx.nested.len() as u16;
|
||||
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::create_closure(Operand::Reg(r as u32), sub_idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_class_expression(&self, class: &Class, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
self.emit_class(class, ctx)
|
||||
}
|
||||
|
||||
fn emit_new_expression(&self, ne: &oxide_parser::NewExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let constructor_reg = self.emit_expression(&ne.callee, ctx)?;
|
||||
let mut arg_regs = Vec::new();
|
||||
for arg in &ne.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
arg_regs.push(self.emit_expression(expr, ctx)?);
|
||||
}
|
||||
}
|
||||
let first_arg_reg = if arg_regs.is_empty() { 0u8 } else { arg_regs[0] };
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new_expression(
|
||||
Operand::Reg(r as u32),
|
||||
Operand::Reg(constructor_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_function_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::ArrowFunctionExpression(arrow) => self.emit_arrow_function_expression(arrow, ctx),
|
||||
Expression::FunctionExpression(fe) => self.emit_function_expression(fe, ctx),
|
||||
Expression::ClassExpression(class) => self.emit_class_expression(class, ctx),
|
||||
Expression::NewExpression(ne) => self.emit_new_expression(ne, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_identifier_expression(
|
||||
&self, ident: &oxide_parser::IdentifierReference, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let name = ident.name.as_str();
|
||||
|
||||
for (uv_idx, up) in ctx.current_upvalue_captures.iter().enumerate() {
|
||||
if up.name == name {
|
||||
let r = ctx.alloc_reg();
|
||||
let idx = uv_idx as u8;
|
||||
ctx.inst(Inst::new(OpCode::LOAD_UPVALUE, Operand::Reg(r as u32), Operand::Reg(idx as u32), Operand::None));
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(name) {
|
||||
let r = ctx.alloc_reg();
|
||||
if let Some((binding, _)) = ctx.scopes.symbols.lookup_any_binding(name) {
|
||||
ctx.inst(Inst::new(OpCode::CELL_GET, Operand::Reg(r as u32), Operand::Reg(binding.reg as u32), Operand::Imm(cell_idx as u16)));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::CELL_GET, Operand::Reg(r as u32), Operand::None, Operand::Imm(cell_idx as u16)));
|
||||
}
|
||||
return Ok(r);
|
||||
}
|
||||
|
||||
let var_reg = ctx.lookup_or_builtin(name)?;
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(r as u32), Operand::Reg(var_reg as u32), Operand::None));
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use crate::{is_int_literal, CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Expression;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_literal(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::NumericLiteral(n) => self.emit_numeric_literal_expression(n, ctx),
|
||||
Expression::StringLiteral(s) => self.emit_string_literal_expression(s, ctx),
|
||||
Expression::BooleanLiteral(b) => self.emit_boolean_literal_expression(b, ctx),
|
||||
Expression::NullLiteral(_) => self.emit_null_literal_expression(ctx),
|
||||
Expression::RegExpLiteral(lit) => self.emit_reg_exp_literal_expression(lit, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_numeric_literal_expression(
|
||||
&self, n: &oxide_parser::NumericLiteral, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let idx = if is_int_literal(n.value) {
|
||||
ctx.add_constant(Constant::Int(n.value as i32))
|
||||
} else {
|
||||
ctx.add_constant(Constant::Number(n.value))
|
||||
};
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(r as u32), idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_string_literal_expression(
|
||||
&self, s: &oxide_parser::StringLiteral, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let idx = ctx.add_constant(Constant::String(s.value.to_string()));
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(r as u32), idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_boolean_literal_expression(
|
||||
&self, b: &oxide_parser::BooleanLiteral, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let idx = ctx.add_constant(Constant::Boolean(b.value));
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(r as u32), idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_null_literal_expression(&self, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let idx = ctx.add_constant(Constant::Null);
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(r as u32), idx));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_reg_exp_literal_expression(
|
||||
&self, lit: &oxide_parser::RegExpLiteral, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
if let Some(raw) = &lit.raw {
|
||||
let raw_str = raw.to_string();
|
||||
if raw_str.len() >= 2 && raw_str.starts_with('/') {
|
||||
let last_slash = raw_str.rfind('/').unwrap_or(raw_str.len() - 1);
|
||||
let pattern = raw_str[1..last_slash].to_string();
|
||||
let flags = raw_str[last_slash + 1..].to_string();
|
||||
let pat_ci = ctx.add_constant(Constant::String(pattern));
|
||||
let pat_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(pat_reg as u32), pat_ci));
|
||||
let flags_ci = ctx.add_constant(Constant::String(flags));
|
||||
let flags_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(flags_reg as u32), flags_ci));
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::CREATE_REGEXP, Operand::Reg(r as u32), Operand::Reg(pat_reg as u32), Operand::Reg(flags_reg as u32)));
|
||||
Ok(r)
|
||||
} else {
|
||||
Err(format!("unsupported regexp literal: {:?}", lit))
|
||||
}
|
||||
} else {
|
||||
Err(format!("unsupported regexp literal: {:?}", lit))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Expression;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_static_member_expression(
|
||||
&self, member: &oxide_parser::StaticMemberExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
if matches!(&member.object, Expression::Super(_)) {
|
||||
if !ctx.in_instance_method && !ctx.in_static_method && !ctx.in_derived_constructor {
|
||||
return Err("super property only supported in class methods".into());
|
||||
}
|
||||
let prop_name = member.property.name.as_str();
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
let this_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(this_reg as u32), Operand::This, Operand::None));
|
||||
let result_reg = ctx.alloc_reg();
|
||||
let op = if ctx.in_static_method {
|
||||
OpCode::SUPER_STATIC_GET_PROP
|
||||
} else {
|
||||
OpCode::SUPER_GET_PROP
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(result_reg as u32), Operand::Reg(this_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
return Ok(result_reg);
|
||||
}
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let prop_name = member.property.name.as_str();
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
ctx.inst(Inst::ic_get(Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(obj_reg)
|
||||
}
|
||||
|
||||
fn emit_computed_member_expression(
|
||||
&self, member: &oxide_parser::ComputedMemberExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(r as u32)));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_private_field_expression(
|
||||
&self, member: &oxide_parser::PrivateFieldExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
let r = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PRIVATE, Operand::Reg(r as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn emit_chain_expression(&self, chain: &oxide_parser::ChainExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let short_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let value_reg = self.emit_chain_element(&chain.expression, Some(short_label), ctx)?;
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(value_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
ctx.labels.set_label_pos(short_label, ctx.insts.len());
|
||||
let undefined_idx = ctx.add_constant(Constant::Undefined);
|
||||
ctx.inst(Inst::load_const(Operand::Reg(result_reg as u32), undefined_idx));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
Ok(result_reg)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_member_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::StaticMemberExpression(member) => self.emit_static_member_expression(member, ctx),
|
||||
Expression::ComputedMemberExpression(member) => self.emit_computed_member_expression(member, ctx),
|
||||
Expression::PrivateFieldExpression(member) => self.emit_private_field_expression(member, ctx),
|
||||
Expression::ChainExpression(chain) => self.emit_chain_expression(chain, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Expression;
|
||||
|
||||
pub mod assignment;
|
||||
pub mod call;
|
||||
pub mod function;
|
||||
pub mod identifier;
|
||||
pub mod literal;
|
||||
pub mod member;
|
||||
pub mod object;
|
||||
pub mod operator;
|
||||
pub mod parenthesized;
|
||||
pub mod template;
|
||||
pub mod this;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_unsupported_expression(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let _ = ctx;
|
||||
Err(format!("unsupported expression type: {:?}", expr))
|
||||
}
|
||||
|
||||
pub(crate) fn emit_sequence_expression(
|
||||
&self, seq: &oxide_parser::SequenceExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let mut last = 0u8;
|
||||
for e in &seq.expressions {
|
||||
last = self.emit_expression(e, ctx)?;
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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_array_expression(
|
||||
&self, arr: &oxide_parser::ArrayExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let arr_reg = ctx.alloc_reg();
|
||||
let n = arr.elements.len() as u16;
|
||||
ctx.inst(Inst::new(OpCode::NEW_ARRAY, Operand::Reg(arr_reg as u32), Operand::Imm(n), Operand::None));
|
||||
let elem_checkpoint = ctx.reg_checkpoint();
|
||||
for (i, elem) in arr.elements.iter().enumerate() {
|
||||
let Some(e) = elem.as_expression() else {
|
||||
return Err("spread not supported".into());
|
||||
};
|
||||
let val_reg = self.emit_expression(e, ctx)?;
|
||||
let idx_reg = ctx.alloc_reg();
|
||||
let idx = ctx.add_constant(Constant::Int(i as i32));
|
||||
ctx.inst(Inst::load_const(Operand::Reg(idx_reg as u32), idx));
|
||||
ctx.inst(Inst::new(OpCode::SET_ELEM, Operand::Reg(arr_reg as u32), Operand::Reg(idx_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
ctx.restore_reg_checkpoint(elem_checkpoint);
|
||||
}
|
||||
Ok(arr_reg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Expression;
|
||||
|
||||
mod array;
|
||||
mod object_literal;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_object_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::ObjectExpression(obj) => self.emit_object_expression(obj, ctx),
|
||||
Expression::ArrayExpression(arr) => self.emit_array_expression(arr, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{Expression, ObjectPropertyKind, PropertyKey, PropertyKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_object_expression(
|
||||
&self, obj: &oxide_parser::ObjectExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let obj_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::NEW_OBJECT, Operand::Reg(obj_reg as u32), Operand::None, Operand::None));
|
||||
let prop_checkpoint = ctx.reg_checkpoint();
|
||||
for prop in &obj.properties {
|
||||
let ObjectPropertyKind::ObjectProperty(p) = prop else {
|
||||
return Err("spread properties not yet supported".into());
|
||||
};
|
||||
let prop_name = match &p.key {
|
||||
PropertyKey::StaticIdentifier(ident) => ident.name.as_str().to_string(),
|
||||
PropertyKey::StringLiteral(s) => s.value.to_string(),
|
||||
_ => return Err("unsupported object property key type".into()),
|
||||
};
|
||||
match p.kind {
|
||||
PropertyKind::Get | PropertyKind::Set => {
|
||||
let accessor_reg = self.emit_expression(&p.value, ctx)?;
|
||||
if let Some(sub_mod) = ctx.nested.last_mut() {
|
||||
sub_mod.function_name = Some(prop_name.to_string());
|
||||
}
|
||||
let undef_reg = self.emit_undefined(ctx);
|
||||
let (get_reg, set_reg) = if p.kind == PropertyKind::Get {
|
||||
(accessor_reg, undef_reg)
|
||||
} else {
|
||||
(undef_reg, accessor_reg)
|
||||
};
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
ctx.inst(Inst::define_accessor(
|
||||
Operand::Reg(obj_reg as u32),
|
||||
Operand::Reg(get_reg as u32),
|
||||
Operand::Reg(set_reg as u32),
|
||||
idx as u32,
|
||||
));
|
||||
ctx.restore_reg_checkpoint(prop_checkpoint);
|
||||
}
|
||||
_ => {
|
||||
let idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
let val_reg = self.emit_expression(&p.value, ctx)?;
|
||||
if matches!(&p.value, Expression::ArrowFunctionExpression(_)) {
|
||||
if let Some(sub_mod) = ctx.nested.last_mut() {
|
||||
sub_mod.function_name = Some(prop_name.to_string());
|
||||
}
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::SET_PROP, Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
ctx.restore_reg_checkpoint(prop_checkpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(obj_reg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
use crate::{is_side_effect_free, BinaryOperator, CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{ChainElement, Expression, LogicalOperator, SimpleAssignmentTarget, UnaryOperator, UpdateOperator};
|
||||
|
||||
impl Emitter {
|
||||
fn emit_private_in_expression(
|
||||
&self, pin: &oxide_parser::PrivateInExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let obj_reg = self.emit_expression(&pin.right, ctx)?;
|
||||
let key_reg = self.emit_private_id_reg(pin.left.name.as_str(), ctx)?;
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::PRIVATE_BRAND_IN, Operand::Reg(result_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(result_reg)
|
||||
}
|
||||
|
||||
fn emit_binary_expression(&self, bin: &oxide_parser::BinaryExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let checkpoint = ctx.reg_checkpoint();
|
||||
let left = self.emit_expression(&bin.left, ctx)?;
|
||||
let right = self.emit_expression(&bin.right, ctx)?;
|
||||
let op = match bin.operator {
|
||||
BinaryOperator::Addition => OpCode::ADD,
|
||||
BinaryOperator::Subtraction => OpCode::SUB,
|
||||
BinaryOperator::Multiplication => OpCode::MUL,
|
||||
BinaryOperator::Division => OpCode::DIV,
|
||||
BinaryOperator::Remainder => OpCode::MOD,
|
||||
BinaryOperator::BitwiseAnd => OpCode::BIT_AND,
|
||||
BinaryOperator::BitwiseOR => OpCode::BIT_OR,
|
||||
BinaryOperator::BitwiseXOR => OpCode::BIT_XOR,
|
||||
BinaryOperator::ShiftLeft => OpCode::SHL,
|
||||
BinaryOperator::ShiftRight => OpCode::SHR,
|
||||
BinaryOperator::ShiftRightZeroFill => OpCode::USHR,
|
||||
BinaryOperator::Equality => OpCode::EQ,
|
||||
BinaryOperator::Inequality => OpCode::NEQ,
|
||||
BinaryOperator::LessThan => OpCode::LT,
|
||||
BinaryOperator::GreaterThan => OpCode::GT,
|
||||
BinaryOperator::LessEqualThan => OpCode::LTE,
|
||||
BinaryOperator::GreaterEqualThan => OpCode::GTE,
|
||||
BinaryOperator::In => OpCode::IN,
|
||||
BinaryOperator::Instanceof => OpCode::INSTANCEOF,
|
||||
BinaryOperator::StrictEquality => OpCode::STRICT_EQ,
|
||||
BinaryOperator::StrictInequality => OpCode::STRICT_NEQ,
|
||||
_ => return Err(format!("unsupported binary operator: {:?}", bin.operator)),
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(left as u32), Operand::Reg(left as u32), Operand::Reg(right as u32)));
|
||||
if is_side_effect_free(&bin.left) && is_side_effect_free(&bin.right) {
|
||||
ctx.restore_reg_checkpoint(checkpoint.saturating_add(1).max(left.saturating_add(1)));
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn emit_unary_expression(&self, un: &oxide_parser::UnaryExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
if matches!(un.operator, UnaryOperator::Delete) {
|
||||
return match &un.argument {
|
||||
Expression::Identifier(_) => {
|
||||
Err("SyntaxError: delete of an unqualified identifier in strict mode".into())
|
||||
}
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let prop_name = member.property.name.as_str();
|
||||
let const_idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
ctx.inst(Inst::delete_prop_static(Operand::Reg(obj_reg as u32), const_idx as u32));
|
||||
Ok(obj_reg)
|
||||
}
|
||||
Expression::ComputedMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::DELETE_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(obj_reg)
|
||||
}
|
||||
Expression::ChainExpression(chain) => {
|
||||
let short_label = ctx.next_label_id();
|
||||
let result_reg = match &chain.expression {
|
||||
ChainElement::StaticMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
if member.optional {
|
||||
let dup_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::jmp_if_nullish(dup_reg, short_label));
|
||||
}
|
||||
let prop_name = member.property.name.as_str();
|
||||
let const_idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
ctx.inst(Inst::delete_prop_static(Operand::Reg(obj_reg as u32), const_idx as u32));
|
||||
obj_reg
|
||||
}
|
||||
ChainElement::ComputedMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
if member.optional {
|
||||
let dup_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::jmp_if_nullish(dup_reg, short_label));
|
||||
}
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::DELETE_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
obj_reg
|
||||
}
|
||||
_ => return Err("invalid delete target".into()),
|
||||
};
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
ctx.labels.set_label_pos(short_label, ctx.insts.len());
|
||||
let true_idx = ctx.add_constant(Constant::Boolean(true));
|
||||
ctx.inst(Inst::load_const(Operand::Reg(result_reg as u32), true_idx));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
Ok(result_reg)
|
||||
}
|
||||
_ => Err("invalid delete target".into()),
|
||||
};
|
||||
}
|
||||
let arg = self.emit_expression(&un.argument, ctx)?;
|
||||
match un.operator {
|
||||
UnaryOperator::UnaryNegation => {
|
||||
ctx.inst(Inst::new(OpCode::NEG, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::Typeof => {
|
||||
ctx.inst(Inst::new(OpCode::TYPEOF, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::Void => {
|
||||
ctx.inst(Inst::new(OpCode::VOID, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::LogicalNot => {
|
||||
ctx.inst(Inst::new(OpCode::NOT, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::BitwiseNot => {
|
||||
ctx.inst(Inst::new(OpCode::BIT_NOT, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::UnaryPlus => {
|
||||
ctx.inst(Inst::new(OpCode::UNARY_PLUS, Operand::Reg(arg as u32), Operand::Reg(arg as u32), Operand::None));
|
||||
Ok(arg)
|
||||
}
|
||||
UnaryOperator::Delete => Err("invalid delete target".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_conditional_expression(
|
||||
&self, cond: &oxide_parser::ConditionalExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let else_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
|
||||
let test_reg = self.emit_expression(&cond.test, ctx)?;
|
||||
ctx.inst(Inst::jmp_if_false(test_reg, else_label));
|
||||
|
||||
let cons_reg = self.emit_expression(&cond.consequent, ctx)?;
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(cons_reg as u32), Operand::None));
|
||||
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
|
||||
ctx.labels.set_label_pos(else_label, ctx.insts.len());
|
||||
let alt_reg = self.emit_expression(&cond.alternate, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(alt_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
|
||||
Ok(result_reg)
|
||||
}
|
||||
|
||||
fn emit_logical_expression(
|
||||
&self, log: &oxide_parser::LogicalExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let left_reg = self.emit_expression(&log.left, ctx)?;
|
||||
|
||||
if is_side_effect_free(&log.left) && is_side_effect_free(&log.right) {
|
||||
let right_reg = self.emit_expression(&log.right, ctx)?;
|
||||
let r = ctx.alloc_reg();
|
||||
let op = match log.operator {
|
||||
LogicalOperator::And => OpCode::AND,
|
||||
LogicalOperator::Or => OpCode::OR,
|
||||
LogicalOperator::Coalesce => OpCode::NULLISH,
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(r as u32), Operand::Reg(left_reg as u32), Operand::Reg(right_reg as u32)));
|
||||
return Ok(r);
|
||||
}
|
||||
|
||||
if matches!(log.operator, LogicalOperator::Coalesce) {
|
||||
let rhs_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let dup_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(left_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::jmp_if_nullish(dup_reg, rhs_label));
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
ctx.labels.set_label_pos(rhs_label, ctx.insts.len());
|
||||
let right_reg = self.emit_expression(&log.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(right_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
return Ok(dup_reg);
|
||||
}
|
||||
|
||||
let skip_label = match log.operator {
|
||||
LogicalOperator::And => ctx.next_label_id(),
|
||||
LogicalOperator::Or => ctx.next_label_id(),
|
||||
LogicalOperator::Coalesce => return Err("invalid logical operator dispatch".into()),
|
||||
};
|
||||
let dup_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(left_reg as u32), Operand::None));
|
||||
|
||||
match log.operator {
|
||||
LogicalOperator::And => ctx.inst(Inst::jmp_if_false(dup_reg, skip_label)),
|
||||
LogicalOperator::Or => ctx.inst(Inst::jmp_if_true(dup_reg, skip_label)),
|
||||
LogicalOperator::Coalesce => return Err("invalid logical operator dispatch".into()),
|
||||
}
|
||||
|
||||
let right_reg = self.emit_expression(&log.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(right_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(skip_label, ctx.insts.len());
|
||||
|
||||
Ok(dup_reg)
|
||||
}
|
||||
|
||||
fn emit_update_expression(
|
||||
&self, update: &oxide_parser::UpdateExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
match &update.argument {
|
||||
SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
|
||||
let name = id.name.as_str();
|
||||
// Check if this is an upvalue or captured cell reference
|
||||
let uv_idx = ctx.current_upvalue_captures.iter().position(|u| u.name == name);
|
||||
let captured_cell = ctx.captured_bindings.get(name).copied();
|
||||
if let Some(uv) = uv_idx {
|
||||
// Upvalue: LOAD_UPVALUE + CONST(1) + ADD/SUB + STORE_UPVALUE
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_UPVALUE, Operand::Reg(val_reg as u32), Operand::Imm(uv as u16), Operand::None));
|
||||
let one_idx = ctx.add_constant(Constant::Int(1));
|
||||
let one_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(one_reg as u32), one_idx));
|
||||
let op = if update.operator == UpdateOperator::Increment {
|
||||
OpCode::ADD
|
||||
} else {
|
||||
OpCode::SUB
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(val_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(one_reg as u32)));
|
||||
ctx.inst(Inst::new(OpCode::STORE_UPVALUE, Operand::None, Operand::Reg(val_reg as u32), Operand::Imm(uv as u16)));
|
||||
Ok(val_reg)
|
||||
} else if let Some(cell_idx) = captured_cell {
|
||||
// Captured cell: CELL_GET + CONST(1) + ADD/SUB + CELL_SET
|
||||
let val_reg = ctx.alloc_reg();
|
||||
if let Some((binding, _)) = ctx.scopes.symbols.lookup_any_binding(name) {
|
||||
ctx.inst(Inst::new(OpCode::CELL_GET, Operand::Reg(val_reg as u32), Operand::Reg(binding.reg as u32), Operand::Imm(cell_idx as u16)));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::CELL_GET, Operand::Reg(val_reg as u32), Operand::None, Operand::Imm(cell_idx as u16)));
|
||||
}
|
||||
let one_idx = ctx.add_constant(Constant::Int(1));
|
||||
let one_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(one_reg as u32), one_idx));
|
||||
let op = if update.operator == UpdateOperator::Increment {
|
||||
OpCode::ADD
|
||||
} else {
|
||||
OpCode::SUB
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(val_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(one_reg as u32)));
|
||||
ctx.inst(Inst::new(OpCode::CELL_SET, Operand::None, Operand::Reg(val_reg as u32), Operand::Imm(cell_idx as u16)));
|
||||
Ok(val_reg)
|
||||
} else {
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
let result_reg = ctx.alloc_reg();
|
||||
let op = match (update.operator, update.prefix) {
|
||||
(UpdateOperator::Increment, true) => OpCode::INC_PRE,
|
||||
(UpdateOperator::Increment, false) => OpCode::INC_POST,
|
||||
(UpdateOperator::Decrement, true) => OpCode::DEC_PRE,
|
||||
(UpdateOperator::Decrement, false) => OpCode::DEC_POST,
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(var_reg as u32), Operand::Reg(result_reg as u32), Operand::Reg(result_reg as u32)));
|
||||
Ok(result_reg)
|
||||
}
|
||||
}
|
||||
SimpleAssignmentTarget::StaticMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let prop_name = member.property.name.as_str();
|
||||
let key_idx = ctx.add_constant(Constant::String(prop_name.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), key_idx));
|
||||
let val_reg = ctx.alloc_reg();
|
||||
let op = match update.operator {
|
||||
UpdateOperator::Increment => OpCode::MEMBER_INC,
|
||||
UpdateOperator::Decrement => OpCode::MEMBER_DEC,
|
||||
};
|
||||
match op {
|
||||
OpCode::MEMBER_INC => {
|
||||
ctx.inst(Inst::member_inc(Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
}
|
||||
OpCode::MEMBER_DEC => {
|
||||
ctx.inst(Inst::member_dec(Operand::Reg(obj_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(val_reg)
|
||||
}
|
||||
SimpleAssignmentTarget::ComputedMemberExpression(member) => {
|
||||
let obj_reg = self.emit_expression(&member.object, ctx)?;
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
let val_reg = ctx.alloc_reg();
|
||||
let op = match update.operator {
|
||||
UpdateOperator::Increment => OpCode::DYN_MEMBER_INC,
|
||||
UpdateOperator::Decrement => OpCode::DYN_MEMBER_DEC,
|
||||
};
|
||||
ctx.inst(Inst::new(op, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
Ok(val_reg)
|
||||
}
|
||||
_ => Err("member update not yet supported".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_operator(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::BinaryExpression(bin) => self.emit_binary_expression(bin, ctx),
|
||||
Expression::PrivateInExpression(pin) => self.emit_private_in_expression(pin, ctx),
|
||||
Expression::UnaryExpression(un) => self.emit_unary_expression(un, ctx),
|
||||
Expression::ConditionalExpression(cond) => self.emit_conditional_expression(cond, ctx),
|
||||
Expression::LogicalExpression(log) => self.emit_logical_expression(log, ctx),
|
||||
Expression::UpdateExpression(update) => self.emit_update_expression(update, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_parenthesized_expression(
|
||||
&self, p: &oxide_parser::ParenthesizedExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
self.emit_expression(&p.expression, ctx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Expression;
|
||||
|
||||
mod tagged;
|
||||
mod template_literal;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_template_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::TemplateLiteral(tl) => self.emit_template_literal_expression(tl, ctx),
|
||||
Expression::TaggedTemplateExpression(tt) => self.emit_tagged_template_expression(tt, ctx),
|
||||
_ => self.emit_unsupported_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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_tagged_template_expression(
|
||||
&self, tt: &oxide_parser::TaggedTemplateExpression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let quasis = &tt.quasi.quasis;
|
||||
let expressions = &tt.quasi.expressions;
|
||||
|
||||
let tag_reg = self.emit_expression(&tt.tag, ctx)?;
|
||||
|
||||
let cooked_temp = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::NEW_ARRAY, Operand::Reg(cooked_temp as u32), Operand::Imm(quasis.len() as u16), Operand::None));
|
||||
for (i, quasi) in quasis.iter().enumerate() {
|
||||
let s = quasi.value.cooked.as_ref().map(|c| c.to_string()).unwrap_or_default();
|
||||
let const_idx = ctx.add_constant(Constant::String(s));
|
||||
let str_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(str_reg as u32), const_idx));
|
||||
let idx_const = ctx.add_constant(Constant::Int(i as i32));
|
||||
let idx_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(idx_reg as u32), idx_const));
|
||||
ctx.inst(Inst::new(OpCode::SET_ELEM, Operand::Reg(cooked_temp as u32), Operand::Reg(idx_reg as u32), Operand::Reg(str_reg as u32)));
|
||||
}
|
||||
|
||||
let raw_temp = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::NEW_ARRAY, Operand::Reg(raw_temp as u32), Operand::Imm(quasis.len() as u16), Operand::None));
|
||||
for (i, quasi) in quasis.iter().enumerate() {
|
||||
let raw = quasi.value.raw.to_string();
|
||||
let const_idx = ctx.add_constant(Constant::String(raw));
|
||||
let str_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(str_reg as u32), const_idx));
|
||||
let idx_const = ctx.add_constant(Constant::Int(i as i32));
|
||||
let idx_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(idx_reg as u32), idx_const));
|
||||
ctx.inst(Inst::new(OpCode::SET_ELEM, Operand::Reg(raw_temp as u32), Operand::Reg(idx_reg as u32), Operand::Reg(str_reg as u32)));
|
||||
}
|
||||
|
||||
let mut expr_temps = Vec::new();
|
||||
for expr in expressions {
|
||||
expr_temps.push(self.emit_expression(expr, ctx)?);
|
||||
}
|
||||
|
||||
let cooked_slot = ctx.alloc_reg();
|
||||
let raw_slot = ctx.alloc_reg();
|
||||
let mut expr_slots = Vec::new();
|
||||
for _ in expressions {
|
||||
expr_slots.push(ctx.alloc_reg());
|
||||
}
|
||||
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(cooked_slot as u32), Operand::Reg(cooked_temp as u32), Operand::None));
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(raw_slot as u32), Operand::Reg(raw_temp as u32), Operand::None));
|
||||
for (slot, temp) in expr_slots.iter().zip(expr_temps.iter()) {
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(*slot as u32), Operand::Reg(*temp as u32), Operand::None));
|
||||
}
|
||||
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
let undef_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(undef_reg as u32), undef_idx));
|
||||
|
||||
let arg_count = 2 + expressions.len();
|
||||
ctx.inst(Inst::call(
|
||||
Operand::Reg(tag_reg as u32),
|
||||
Operand::Reg(undef_reg as u32),
|
||||
Operand::Reg(cooked_slot as u32),
|
||||
arg_count as u8,
|
||||
));
|
||||
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::None, Operand::None));
|
||||
Ok(result_reg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_template_literal_expression(
|
||||
&self, tl: &oxide_parser::TemplateLiteral, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let r = ctx.alloc_reg();
|
||||
let quasis = &tl.quasis;
|
||||
let expressions = &tl.expressions;
|
||||
let segment_count = quasis.len() + expressions.len();
|
||||
|
||||
let expr_regs: Vec<u8> = expressions
|
||||
.iter()
|
||||
.map(|e| self.emit_expression(e, ctx))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let quasi_const_idxs: Vec<u16> = quasis
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let s = q.value.cooked.as_ref().map(|c| c.to_string()).unwrap_or_default();
|
||||
ctx.add_constant(Constant::String(s))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let total_len_hint: usize = quasis
|
||||
.iter()
|
||||
.map(|q| q.value.cooked.as_ref().map(|c| c.len()).unwrap_or(0))
|
||||
.sum();
|
||||
|
||||
let mut parts = Vec::with_capacity(quasi_const_idxs.len() * 2);
|
||||
let mut expr_iter = expr_regs.iter();
|
||||
for const_idx in quasi_const_idxs.iter() {
|
||||
parts.push(*const_idx as u32 & 0x7FFF_FFFF);
|
||||
if let Some(expr_reg) = expr_iter.next() {
|
||||
parts.push(0x8000_0000u32 | (*expr_reg as u32));
|
||||
}
|
||||
}
|
||||
|
||||
ctx.inst(Inst::template_str(
|
||||
Operand::Reg(r as u32),
|
||||
segment_count as u32,
|
||||
total_len_hint as u16,
|
||||
&parts,
|
||||
));
|
||||
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_this_expression(&self, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let r = ctx.alloc_reg();
|
||||
let src = ctx.static_block_this_reg.unwrap_or(254);
|
||||
let src_op = if src == 254 { Operand::This } else { Operand::Reg(src as u32) };
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(r as u32), src_op, Operand::None));
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
pub mod class;
|
||||
pub mod closure;
|
||||
pub mod emit;
|
||||
pub mod emit_ctx;
|
||||
pub mod expr;
|
||||
pub mod prepass;
|
||||
pub mod shared;
|
||||
pub mod stmt;
|
||||
pub mod symbol_table;
|
||||
|
||||
pub use emit::{CompileCtx, Emitter, FunctionBodyContext, LabelScope, ParamSpec};
|
||||
pub use emit::{is_int_literal, is_side_effect_free};
|
||||
pub use oxide_bytecode::module::Constant;
|
||||
pub use oxide_parser::{AssignmentOperator, BinaryOperator, UnaryOperator};
|
||||
@@ -0,0 +1,342 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::{Expression, Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
|
||||
/// builtin slot allocation ahead of the temporary register pool.
|
||||
pub(crate) fn pre_register_builtin_references(&self, stmts: &[Statement], ctx: &mut CompileCtx) {
|
||||
for stmt in stmts {
|
||||
self.pre_scan_builtin_stmt(stmt, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
fn pre_scan_builtin_stmt(&self, stmt: &Statement, ctx: &mut CompileCtx) {
|
||||
match stmt {
|
||||
Statement::ExpressionStatement(es) => self.pre_scan_builtin_expr(&es.expression, ctx),
|
||||
Statement::VariableDeclaration(vd) => {
|
||||
for d in &vd.declarations {
|
||||
if let Some(init) = &d.init {
|
||||
self.pre_scan_builtin_expr(init, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ReturnStatement(rs) => {
|
||||
if let Some(a) = &rs.argument {
|
||||
self.pre_scan_builtin_expr(a, ctx);
|
||||
}
|
||||
}
|
||||
Statement::IfStatement(is) => {
|
||||
self.pre_scan_builtin_expr(&is.test, ctx);
|
||||
self.pre_scan_builtin_stmt(&is.consequent, ctx);
|
||||
if let Some(alt) = &is.alternate {
|
||||
self.pre_scan_builtin_stmt(alt, ctx);
|
||||
}
|
||||
}
|
||||
Statement::WhileStatement(wh) => {
|
||||
self.pre_scan_builtin_expr(&wh.test, ctx);
|
||||
self.pre_scan_builtin_stmt(&wh.body, ctx);
|
||||
}
|
||||
Statement::DoWhileStatement(dw) => {
|
||||
self.pre_scan_builtin_stmt(&dw.body, ctx);
|
||||
self.pre_scan_builtin_expr(&dw.test, ctx);
|
||||
}
|
||||
Statement::ForStatement(fs) => {
|
||||
if let Some(init) = &fs.init {
|
||||
if let Some(e) = init.as_expression() {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
} else if let oxide_parser::ForStatementInit::VariableDeclaration(decl) = init {
|
||||
for d in &decl.declarations {
|
||||
if let Some(init_expr) = &d.init {
|
||||
self.pre_scan_builtin_expr(init_expr, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(t) = &fs.test {
|
||||
self.pre_scan_builtin_expr(t, ctx);
|
||||
}
|
||||
if let Some(u) = &fs.update {
|
||||
self.pre_scan_builtin_expr(u, ctx);
|
||||
}
|
||||
self.pre_scan_builtin_stmt(&fs.body, ctx);
|
||||
}
|
||||
Statement::ForInStatement(fi) => {
|
||||
self.pre_scan_builtin_expr(&fi.right, ctx);
|
||||
self.pre_scan_builtin_stmt(&fi.body, ctx);
|
||||
}
|
||||
Statement::ForOfStatement(fo) => {
|
||||
self.pre_scan_builtin_expr(&fo.right, ctx);
|
||||
self.pre_scan_builtin_stmt(&fo.body, ctx);
|
||||
}
|
||||
Statement::SwitchStatement(sw) => {
|
||||
self.pre_scan_builtin_expr(&sw.discriminant, ctx);
|
||||
for case in &sw.cases {
|
||||
if let Some(test) = &case.test {
|
||||
self.pre_scan_builtin_expr(test, ctx);
|
||||
}
|
||||
for s in &case.consequent {
|
||||
self.pre_scan_builtin_stmt(s, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ThrowStatement(ts) => {
|
||||
self.pre_scan_builtin_expr(&ts.argument, ctx);
|
||||
}
|
||||
Statement::TryStatement(ts) => {
|
||||
for s in &ts.block.body {
|
||||
self.pre_scan_builtin_stmt(s, ctx);
|
||||
}
|
||||
if let Some(handler) = &ts.handler {
|
||||
for s in &handler.body.body {
|
||||
self.pre_scan_builtin_stmt(s, ctx);
|
||||
}
|
||||
}
|
||||
if let Some(finalizer) = &ts.finalizer {
|
||||
for s in &finalizer.body {
|
||||
self.pre_scan_builtin_stmt(s, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::BlockStatement(bs) => {
|
||||
for s in &bs.body {
|
||||
self.pre_scan_builtin_stmt(s, ctx);
|
||||
}
|
||||
}
|
||||
Statement::LabeledStatement(ls) => self.pre_scan_builtin_stmt(&ls.body, ctx),
|
||||
Statement::ClassDeclaration(cd) => {
|
||||
if let Some(super_class) = &cd.super_class {
|
||||
self.pre_scan_builtin_expr(super_class, ctx);
|
||||
}
|
||||
}
|
||||
Statement::FunctionDeclaration(_) | Statement::BreakStatement(_) | Statement::ContinueStatement(_) => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn pre_scan_builtin_expr(&self, expr: &Expression, ctx: &mut CompileCtx) {
|
||||
match expr {
|
||||
Expression::Identifier(ident) => {
|
||||
if CompileCtx::is_known_builtin(ident.name.as_str()) {
|
||||
let _ = ctx.lookup_or_builtin(ident.name.as_str());
|
||||
}
|
||||
}
|
||||
Expression::BinaryExpression(bin) => {
|
||||
self.pre_scan_builtin_expr(&bin.left, ctx);
|
||||
self.pre_scan_builtin_expr(&bin.right, ctx);
|
||||
}
|
||||
Expression::UnaryExpression(un) => {
|
||||
self.pre_scan_builtin_expr(&un.argument, ctx);
|
||||
}
|
||||
Expression::CallExpression(call) => {
|
||||
self.pre_scan_builtin_expr(&call.callee, ctx);
|
||||
for arg in &call.arguments {
|
||||
if let Some(e) = arg.as_expression() {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::NewExpression(ne) => {
|
||||
self.pre_scan_builtin_expr(&ne.callee, ctx);
|
||||
for arg in &ne.arguments {
|
||||
if let Some(e) = arg.as_expression() {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::LogicalExpression(log) => {
|
||||
self.pre_scan_builtin_expr(&log.left, ctx);
|
||||
self.pre_scan_builtin_expr(&log.right, ctx);
|
||||
}
|
||||
Expression::ConditionalExpression(cond) => {
|
||||
self.pre_scan_builtin_expr(&cond.test, ctx);
|
||||
self.pre_scan_builtin_expr(&cond.consequent, ctx);
|
||||
self.pre_scan_builtin_expr(&cond.alternate, ctx);
|
||||
}
|
||||
Expression::PrivateInExpression(pin) => {
|
||||
self.pre_scan_builtin_expr(&pin.right, ctx);
|
||||
}
|
||||
Expression::SequenceExpression(seq) => {
|
||||
for e in &seq.expressions {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
Expression::AssignmentExpression(assign) => {
|
||||
if let Some(target) = assign.left.as_simple_assignment_target() {
|
||||
self.pre_scan_builtin_target(target, ctx);
|
||||
}
|
||||
self.pre_scan_builtin_expr(&assign.right, ctx);
|
||||
}
|
||||
Expression::UpdateExpression(update) => {
|
||||
self.pre_scan_builtin_target(&update.argument, ctx);
|
||||
}
|
||||
Expression::TemplateLiteral(tl) => {
|
||||
for e in &tl.expressions {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
Expression::TaggedTemplateExpression(tt) => {
|
||||
self.pre_scan_builtin_expr(&tt.tag, ctx);
|
||||
for e in &tt.quasi.expressions {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
Expression::ObjectExpression(obj) => {
|
||||
for prop in &obj.properties {
|
||||
if let oxide_parser::ObjectPropertyKind::ObjectProperty(p) = prop {
|
||||
if p.computed {
|
||||
self.pre_scan_builtin_expr(p.key.to_expression(), ctx);
|
||||
}
|
||||
self.pre_scan_builtin_expr(&p.value, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::ArrayExpression(arr) => {
|
||||
for e in &arr.elements {
|
||||
if let Some(e) = e.as_expression() {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::PrivateFieldExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
Expression::ComputedMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
self.pre_scan_builtin_expr(&member.expression, ctx);
|
||||
}
|
||||
Expression::ChainExpression(chain) => {
|
||||
self.pre_scan_builtin_chain(&chain.expression, ctx);
|
||||
}
|
||||
Expression::ParenthesizedExpression(p) => self.pre_scan_builtin_expr(&p.expression, ctx),
|
||||
Expression::ArrowFunctionExpression(_)
|
||||
| Expression::FunctionExpression(_)
|
||||
| Expression::ClassExpression(_) => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn pre_scan_builtin_target(&self, target: &oxide_parser::SimpleAssignmentTarget, ctx: &mut CompileCtx) {
|
||||
match target {
|
||||
oxide_parser::SimpleAssignmentTarget::StaticMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
oxide_parser::SimpleAssignmentTarget::ComputedMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
self.pre_scan_builtin_expr(&member.expression, ctx);
|
||||
}
|
||||
oxide_parser::SimpleAssignmentTarget::PrivateFieldExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn pre_scan_builtin_chain(&self, element: &oxide_parser::ChainElement, ctx: &mut CompileCtx) {
|
||||
match element {
|
||||
oxide_parser::ChainElement::StaticMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
oxide_parser::ChainElement::ComputedMemberExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
self.pre_scan_builtin_expr(&member.expression, ctx);
|
||||
}
|
||||
oxide_parser::ChainElement::PrivateFieldExpression(member) => {
|
||||
self.pre_scan_builtin_expr(&member.object, ctx);
|
||||
}
|
||||
oxide_parser::ChainElement::CallExpression(call) => {
|
||||
self.pre_scan_builtin_expr(&call.callee, ctx);
|
||||
for arg in &call.arguments {
|
||||
if let Some(e) = arg.as_expression() {
|
||||
self.pre_scan_builtin_expr(e, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn predeclare_function_declarations(&self, statements: &[Statement], ctx: &mut CompileCtx) {
|
||||
for statement in statements {
|
||||
let Statement::FunctionDeclaration(function) = statement else {
|
||||
continue;
|
||||
};
|
||||
let Some(identifier) = &function.id else {
|
||||
continue;
|
||||
};
|
||||
let reg = ctx.alloc_reg();
|
||||
let _ = ctx.declare_initialized(identifier.name.as_str(), reg, VariableDeclarationKind::Var, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-declare all `var` bindings in this statement list so hoisted function
|
||||
/// declarations emitted earlier can resolve them. Mirrors the removed count
|
||||
/// pass behavior (see fe8bd86): top-level `var` names must be visible while
|
||||
/// compiling function bodies that close over them.
|
||||
pub(crate) fn predeclare_var_declarations(&self, statements: &[Statement], ctx: &mut CompileCtx) {
|
||||
for statement in statements {
|
||||
match statement {
|
||||
Statement::VariableDeclaration(decl) => {
|
||||
if !matches!(decl.kind, VariableDeclarationKind::Var) {
|
||||
continue;
|
||||
}
|
||||
for d in &decl.declarations {
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
let reg = ctx.alloc_reg();
|
||||
let _ = ctx.declare_initialized(bi.name.as_str(), reg, VariableDeclarationKind::Var, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::BlockStatement(bs) => self.predeclare_var_declarations(&bs.body, ctx),
|
||||
Statement::IfStatement(is) => {
|
||||
self.predeclare_var_declarations(std::slice::from_ref(&is.consequent), ctx);
|
||||
if let Some(alt) = &is.alternate {
|
||||
self.predeclare_var_declarations(std::slice::from_ref(alt), ctx);
|
||||
}
|
||||
}
|
||||
Statement::WhileStatement(wh) => {
|
||||
self.predeclare_var_declarations(std::slice::from_ref(&wh.body), ctx);
|
||||
}
|
||||
Statement::DoWhileStatement(dw) => {
|
||||
self.predeclare_var_declarations(std::slice::from_ref(&dw.body), ctx);
|
||||
}
|
||||
Statement::ForStatement(fs) => {
|
||||
if let Some(oxide_parser::ForStatementInit::VariableDeclaration(decl)) = &fs.init {
|
||||
if matches!(decl.kind, VariableDeclarationKind::Var) {
|
||||
for d in &decl.declarations {
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
let reg = ctx.alloc_reg();
|
||||
let _ =
|
||||
ctx.declare_initialized(bi.name.as_str(), reg, VariableDeclarationKind::Var, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.predeclare_var_declarations(std::slice::from_ref(&fs.body), ctx);
|
||||
}
|
||||
Statement::SwitchStatement(sw) => {
|
||||
for case in &sw.cases {
|
||||
self.predeclare_var_declarations(&case.consequent, ctx);
|
||||
}
|
||||
}
|
||||
Statement::TryStatement(ts) => {
|
||||
self.predeclare_var_declarations(&ts.block.body, ctx);
|
||||
if let Some(handler) = &ts.handler {
|
||||
self.predeclare_var_declarations(&handler.body.body, ctx);
|
||||
}
|
||||
if let Some(finalizer) = &ts.finalizer {
|
||||
self.predeclare_var_declarations(&finalizer.body, ctx);
|
||||
}
|
||||
}
|
||||
Statement::LabeledStatement(ls) => {
|
||||
self.predeclare_var_declarations(std::slice::from_ref(&ls.body), ctx);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{
|
||||
ArrayAssignmentTarget, ArrayPattern, AssignmentTarget, AssignmentTargetMaybeDefault, AssignmentTargetProperty,
|
||||
BindingPattern, Expression, ObjectAssignmentTarget, ObjectPattern, VariableDeclarationKind,
|
||||
};
|
||||
|
||||
impl Emitter {
|
||||
fn emit_default_if_undefined(
|
||||
&self, val_reg: u8, default_expr: &Expression, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let undef_reg = self.emit_undefined(ctx);
|
||||
let eq_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::STRICT_EQ, Operand::Reg(eq_reg as u32), Operand::Reg(val_reg as u32), Operand::Reg(undef_reg as u32)));
|
||||
// val != undefined(eq 为 false)→ 跳过默认值
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.inst(Inst::jmp_if_false(eq_reg, end_label));
|
||||
let default_reg = self.emit_expression(default_expr, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(val_reg as u32), Operand::Reg(default_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
Ok(val_reg)
|
||||
}
|
||||
|
||||
fn emit_bind_target(
|
||||
&self, name: &str, src_reg: u8, kind: VariableDeclarationKind, is_const: bool, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let target_reg = if matches!(kind, VariableDeclarationKind::Var) {
|
||||
// `var` names are pre-declared (hoisting); reuse the pre-registered slot
|
||||
// instead of allocating a new one so n_registers matches let/const.
|
||||
if let Some(reg) = ctx.scopes.symbols.lookup_any(name) {
|
||||
reg
|
||||
} else {
|
||||
let var_reg = ctx.alloc_reg();
|
||||
ctx.declare(name, var_reg, kind, is_const)?;
|
||||
var_reg
|
||||
}
|
||||
} else {
|
||||
let var_reg = ctx.alloc_reg();
|
||||
ctx.declare(name, var_reg, kind, is_const)?;
|
||||
var_reg
|
||||
};
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(name) {
|
||||
ctx.inst(Inst::new(OpCode::MAKE_CELL, Operand::Reg(src_reg as u32), Operand::Imm(cell_idx as u16), Operand::None));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(target_reg as u32), Operand::Reg(src_reg as u32), Operand::Imm(if is_const { 1 } else { 0 })));
|
||||
}
|
||||
ctx.init_var(name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn emit_assign_target(
|
||||
&self, target: &AssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
match target {
|
||||
AssignmentTarget::AssignmentTargetIdentifier(id) => {
|
||||
let name = id.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
ctx.inst(Inst::new(
|
||||
OpCode::STORE_VAR,
|
||||
Operand::Reg(var_reg as u32),
|
||||
Operand::Reg(src_reg as u32),
|
||||
Operand::Imm(if ctx.lookup_const_flag(name) { 1 } else { 0 }),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
AssignmentTarget::ArrayAssignmentTarget(ap) => self.emit_array_assignment(ap, src_reg, ctx),
|
||||
AssignmentTarget::ObjectAssignmentTarget(op) => self.emit_object_assignment(op, src_reg, ctx),
|
||||
_ => Err("assignment target not supported".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_binding_pattern(
|
||||
&self, pattern: &BindingPattern, src_reg: u8, kind: VariableDeclarationKind, is_const: bool,
|
||||
ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
match pattern {
|
||||
BindingPattern::BindingIdentifier(bi) => {
|
||||
self.emit_bind_target(bi.name.as_str(), src_reg, kind, is_const, ctx)
|
||||
}
|
||||
BindingPattern::ArrayPattern(ap) => self.emit_array_binding(ap, src_reg, kind, is_const, ctx),
|
||||
BindingPattern::ObjectPattern(op) => self.emit_object_binding(op, src_reg, kind, is_const, ctx),
|
||||
BindingPattern::AssignmentPattern(ap) => {
|
||||
let val_reg = self.emit_default_if_undefined(src_reg, &ap.right, ctx)?;
|
||||
self.emit_binding_pattern(&ap.left, val_reg, kind, is_const, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_array_binding(
|
||||
&self, ap: &ArrayPattern, src_reg: u8, kind: VariableDeclarationKind, is_const: bool, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_INIT, Operand::None, Operand::Reg(src_reg as u32), Operand::None));
|
||||
for elem in &ap.elements {
|
||||
let has_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_DONE, Operand::Reg(has_reg as u32), Operand::None, Operand::None));
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_NEXT, Operand::Reg(val_reg as u32), Operand::None, Operand::None));
|
||||
if let Some(pattern) = elem {
|
||||
self.emit_binding_pattern(pattern, val_reg, kind, is_const, ctx)?;
|
||||
}
|
||||
}
|
||||
if let Some(rest) = &ap.rest {
|
||||
let rest_reg = self.emit_collect_rest_array(ctx)?;
|
||||
self.emit_binding_pattern(&rest.argument, rest_reg, kind, is_const, ctx)?;
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_CLOSE, Operand::None, Operand::None, Operand::None));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_collect_rest_array(&self, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let rest_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::NEW_ARRAY, Operand::Reg(rest_reg as u32), Operand::None, Operand::None));
|
||||
let idx_reg = ctx.alloc_reg();
|
||||
let zero_idx = ctx.add_constant(Constant::Int(0));
|
||||
ctx.inst(Inst::load_const(Operand::Reg(idx_reg as u32), zero_idx));
|
||||
let loop_start = ctx.next_label_id();
|
||||
let loop_end = ctx.next_label_id();
|
||||
ctx.labels.set_label_pos(loop_start, ctx.insts.len());
|
||||
let has_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_DONE, Operand::Reg(has_reg as u32), Operand::None, Operand::None));
|
||||
ctx.inst(Inst::jmp_if_false(has_reg, loop_end));
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_NEXT, Operand::Reg(val_reg as u32), Operand::None, Operand::None));
|
||||
ctx.inst(Inst::new(OpCode::SET_ELEM, Operand::Reg(rest_reg as u32), Operand::Reg(idx_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
let tmp_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::INC_PRE, Operand::Reg(idx_reg as u32), Operand::Reg(tmp_reg as u32), Operand::Reg(tmp_reg as u32)));
|
||||
ctx.inst(Inst::jmp(loop_start));
|
||||
ctx.labels.set_label_pos(loop_end, ctx.insts.len());
|
||||
Ok(rest_reg)
|
||||
}
|
||||
|
||||
fn emit_object_binding(
|
||||
&self, op: &ObjectPattern, src_reg: u8, kind: VariableDeclarationKind, is_const: bool, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let mut excluded = Vec::new();
|
||||
for prop in &op.properties {
|
||||
let (prop_reg, static_key) = self.emit_object_property_read_key(src_reg, &prop.key, prop.computed, ctx)?;
|
||||
if let Some(key) = static_key {
|
||||
excluded.push(key);
|
||||
}
|
||||
self.emit_binding_pattern(&prop.value, prop_reg, kind, is_const, ctx)?;
|
||||
}
|
||||
if let Some(rest) = &op.rest {
|
||||
let rest_reg = ctx.alloc_reg();
|
||||
let excluded_idx = ctx.add_constant(Constant::String(excluded.join("\0")));
|
||||
ctx.inst(Inst::rest_object(Operand::Reg(rest_reg as u32), Operand::Reg(src_reg as u32), excluded_idx as u32));
|
||||
self.emit_binding_pattern(&rest.argument, rest_reg, kind, is_const, ctx)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_assignment_maybe_default(
|
||||
&self, target: &AssignmentTargetMaybeDefault, src_reg: u8, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
match target {
|
||||
AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(default) => {
|
||||
let val_reg = self.emit_default_if_undefined(src_reg, &default.init, ctx)?;
|
||||
self.emit_assign_target(&default.binding, val_reg, ctx)
|
||||
}
|
||||
AssignmentTargetMaybeDefault::ArrayAssignmentTarget(ap) => self.emit_array_assignment(ap, src_reg, ctx),
|
||||
AssignmentTargetMaybeDefault::ObjectAssignmentTarget(op) => self.emit_object_assignment(op, src_reg, ctx),
|
||||
AssignmentTargetMaybeDefault::AssignmentTargetIdentifier(id) => {
|
||||
let name = id.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
ctx.inst(Inst::new(
|
||||
OpCode::STORE_VAR,
|
||||
Operand::Reg(var_reg as u32),
|
||||
Operand::Reg(src_reg as u32),
|
||||
Operand::Imm(if ctx.lookup_const_flag(name) { 1 } else { 0 }),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("assignment target not supported".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_array_assignment(
|
||||
&self, ap: &ArrayAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_INIT, Operand::None, Operand::Reg(src_reg as u32), Operand::None));
|
||||
for elem in &ap.elements {
|
||||
let has_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_DONE, Operand::Reg(has_reg as u32), Operand::None, Operand::None));
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_NEXT, Operand::Reg(val_reg as u32), Operand::None, Operand::None));
|
||||
if let Some(target) = elem {
|
||||
self.emit_assignment_maybe_default(target, val_reg, ctx)?;
|
||||
}
|
||||
}
|
||||
if let Some(rest) = &ap.rest {
|
||||
let rest_reg = self.emit_collect_rest_array(ctx)?;
|
||||
self.emit_assign_target(&rest.target, rest_reg, ctx)?;
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_CLOSE, Operand::None, Operand::None, Operand::None));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn emit_object_assignment(
|
||||
&self, op: &ObjectAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let mut excluded = Vec::new();
|
||||
for prop in &op.properties {
|
||||
match prop {
|
||||
AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(id) => {
|
||||
let key = id.binding.name.as_str().to_string();
|
||||
excluded.push(key.clone());
|
||||
let mut prop_reg = self.emit_object_property_read(src_reg, &key, ctx);
|
||||
if let Some(default_expr) = &id.init {
|
||||
prop_reg = self.emit_default_if_undefined(prop_reg, default_expr, ctx)?;
|
||||
}
|
||||
let name = id.binding.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
ctx.inst(Inst::new(
|
||||
OpCode::STORE_VAR,
|
||||
Operand::Reg(var_reg as u32),
|
||||
Operand::Reg(prop_reg as u32),
|
||||
Operand::Imm(if ctx.lookup_const_flag(name) { 1 } else { 0 }),
|
||||
));
|
||||
}
|
||||
AssignmentTargetProperty::AssignmentTargetPropertyProperty(prop) => {
|
||||
let (prop_reg, static_key) =
|
||||
self.emit_object_property_read_key(src_reg, &prop.name, prop.computed, ctx)?;
|
||||
if let Some(key) = static_key {
|
||||
excluded.push(key);
|
||||
}
|
||||
self.emit_assignment_maybe_default(&prop.binding, prop_reg, ctx)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(rest) = &op.rest {
|
||||
let rest_reg = ctx.alloc_reg();
|
||||
let excluded_idx = ctx.add_constant(Constant::String(excluded.join("\0")));
|
||||
ctx.inst(Inst::rest_object(Operand::Reg(rest_reg as u32), Operand::Reg(src_reg as u32), excluded_idx as u32));
|
||||
self.emit_assign_target(&rest.target, rest_reg, ctx)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::{LabelId, Operand};
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{ChainElement, Expression, LogicalOperator, PropertyKey};
|
||||
|
||||
impl Emitter {
|
||||
fn emit_optional_guard(&self, reg: u8, short_label: LabelId, ctx: &mut CompileCtx) -> Result<(), String> {
|
||||
let dup_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(dup_reg as u32), Operand::Reg(reg as u32), Operand::None));
|
||||
ctx.inst(Inst::jmp_if_nullish(dup_reg, short_label));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_static_member_get_preserve_base(
|
||||
&self, member: &oxide_parser::StaticMemberExpression, short_label: Option<LabelId>, ctx: &mut CompileCtx,
|
||||
) -> Result<(u8, u8), String> {
|
||||
let obj_reg = self.emit_chainable_expression(&member.object, short_label, ctx)?;
|
||||
if member.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(obj_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let idx = ctx.add_constant(Constant::String(member.property.name.as_str().to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), idx));
|
||||
let value_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(value_reg as u32), Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.inst(Inst::ic_get(Operand::Reg(value_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok((value_reg, obj_reg))
|
||||
}
|
||||
|
||||
fn emit_computed_member_get_preserve_base(
|
||||
&self, member: &oxide_parser::ComputedMemberExpression, short_label: Option<LabelId>, ctx: &mut CompileCtx,
|
||||
) -> Result<(u8, u8), String> {
|
||||
let obj_reg = self.emit_chainable_expression(&member.object, short_label, ctx)?;
|
||||
if member.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(obj_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let key_reg = self.emit_expression(&member.expression, ctx)?;
|
||||
let value_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PROP_DYNAMIC, Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(value_reg as u32)));
|
||||
Ok((value_reg, obj_reg))
|
||||
}
|
||||
|
||||
fn emit_chain_call(
|
||||
&self, call: &oxide_parser::CallExpression, short_label: Option<LabelId>, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
let (callee_reg, this_reg) = match &call.callee {
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
self.emit_static_member_get_preserve_base(member, short_label, ctx)?
|
||||
}
|
||||
Expression::ComputedMemberExpression(member) => {
|
||||
self.emit_computed_member_get_preserve_base(member, short_label, ctx)?
|
||||
}
|
||||
Expression::PrivateFieldExpression(member) => {
|
||||
let obj_reg = self.emit_chainable_expression(&member.object, short_label, ctx)?;
|
||||
if member.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(obj_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
let callee_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PRIVATE, Operand::Reg(callee_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
(callee_reg, obj_reg)
|
||||
}
|
||||
_ => {
|
||||
let callee_reg = self.emit_chainable_expression(&call.callee, short_label, ctx)?;
|
||||
if call.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(callee_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let this_idx = ctx.add_constant(Constant::Undefined);
|
||||
let this_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(this_reg as u32), this_idx));
|
||||
(callee_reg, this_reg)
|
||||
}
|
||||
};
|
||||
if call.optional
|
||||
&& matches!(
|
||||
&call.callee,
|
||||
Expression::StaticMemberExpression(_)
|
||||
| Expression::ComputedMemberExpression(_)
|
||||
| Expression::PrivateFieldExpression(_)
|
||||
)
|
||||
{
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(callee_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let mut arg_regs = Vec::new();
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
arg_regs.push(self.emit_expression(expr, ctx)?);
|
||||
}
|
||||
}
|
||||
let first_arg_reg = if arg_regs.is_empty() { 0u8 } else { arg_regs[0] };
|
||||
let op = match &call.callee {
|
||||
Expression::Identifier(ident) if ctx.is_builtin(ident.name.as_str()) => OpCode::CALL_NATIVE,
|
||||
_ => OpCode::CALL,
|
||||
};
|
||||
match op {
|
||||
OpCode::CALL => {
|
||||
ctx.inst(Inst::call(
|
||||
Operand::Reg(callee_reg as u32),
|
||||
Operand::Reg(this_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
}
|
||||
OpCode::CALL_NATIVE => {
|
||||
ctx.inst(Inst::call_native(
|
||||
Operand::Reg(callee_reg as u32),
|
||||
Operand::Reg(this_reg as u32),
|
||||
Operand::Reg(first_arg_reg as u32),
|
||||
arg_regs.len() as u8,
|
||||
));
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let result_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::None, Operand::None));
|
||||
Ok(result_reg)
|
||||
}
|
||||
|
||||
fn emit_chainable_expression(
|
||||
&self, expr: &Expression, short_label: Option<LabelId>, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
match expr {
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
let (value_reg, _) = self.emit_static_member_get_preserve_base(member, short_label, ctx)?;
|
||||
Ok(value_reg)
|
||||
}
|
||||
Expression::ComputedMemberExpression(member) => {
|
||||
let (value_reg, _) = self.emit_computed_member_get_preserve_base(member, short_label, ctx)?;
|
||||
Ok(value_reg)
|
||||
}
|
||||
Expression::PrivateFieldExpression(member) => {
|
||||
let obj_reg = self.emit_chainable_expression(&member.object, short_label, ctx)?;
|
||||
if member.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(obj_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
let value_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PRIVATE, Operand::Reg(value_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(value_reg)
|
||||
}
|
||||
Expression::CallExpression(call) => self.emit_chain_call(call, short_label, ctx),
|
||||
Expression::ChainExpression(chain) => self.emit_chain_element(&chain.expression, short_label, ctx),
|
||||
_ => self.emit_expression(expr, ctx),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_chain_element(
|
||||
&self, element: &ChainElement, short_label: Option<LabelId>, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
match element {
|
||||
ChainElement::StaticMemberExpression(member) => {
|
||||
let (value_reg, _) = self.emit_static_member_get_preserve_base(member, short_label, ctx)?;
|
||||
Ok(value_reg)
|
||||
}
|
||||
ChainElement::ComputedMemberExpression(member) => {
|
||||
let (value_reg, _) = self.emit_computed_member_get_preserve_base(member, short_label, ctx)?;
|
||||
Ok(value_reg)
|
||||
}
|
||||
ChainElement::PrivateFieldExpression(member) => {
|
||||
let obj_reg = self.emit_chainable_expression(&member.object, short_label, ctx)?;
|
||||
if member.optional {
|
||||
if let Some(label) = short_label {
|
||||
self.emit_optional_guard(obj_reg, label, ctx)?;
|
||||
}
|
||||
}
|
||||
let key_reg = self.emit_private_id_reg(member.field.name.as_str(), ctx)?;
|
||||
let value_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PRIVATE, Operand::Reg(value_reg as u32), Operand::Reg(obj_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(value_reg)
|
||||
}
|
||||
ChainElement::CallExpression(call) => self.emit_chain_call(call, short_label, ctx),
|
||||
ChainElement::TSNonNullExpression(_) => Err("TS non-null expressions are not supported in JS mode".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_logical_assign_test(
|
||||
&self, op: LogicalOperator, test_reg: u8, store_label: LabelId, end_label: LabelId, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
match op {
|
||||
LogicalOperator::And => ctx.inst(Inst::jmp_if_false(test_reg, end_label)),
|
||||
LogicalOperator::Or => ctx.inst(Inst::jmp_if_true(test_reg, end_label)),
|
||||
LogicalOperator::Coalesce => {
|
||||
ctx.inst(Inst::jmp_if_nullish(test_reg, store_label));
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn emit_object_property_read(&self, src_reg: u8, key: &str, ctx: &mut CompileCtx) -> u8 {
|
||||
let prop_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(prop_reg as u32), Operand::Reg(src_reg as u32), Operand::None));
|
||||
let key_idx = ctx.add_constant(Constant::String(key.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), key_idx));
|
||||
ctx.inst(Inst::ic_get(Operand::Reg(prop_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
prop_reg
|
||||
}
|
||||
|
||||
fn emit_property_key_expression(&self, key: &PropertyKey, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
match key {
|
||||
PropertyKey::Identifier(ident) => {
|
||||
let name = ident.name.as_str();
|
||||
let var_reg = ctx.lookup_or_builtin(name)?;
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(key_reg as u32), Operand::Reg(var_reg as u32), Operand::None));
|
||||
Ok(key_reg)
|
||||
}
|
||||
PropertyKey::StringLiteral(s) => {
|
||||
let key_idx = ctx.add_constant(Constant::String(s.value.to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), key_idx));
|
||||
Ok(key_reg)
|
||||
}
|
||||
PropertyKey::NumericLiteral(n) => {
|
||||
let key_idx = ctx.add_constant(Constant::Number(n.value));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), key_idx));
|
||||
Ok(key_reg)
|
||||
}
|
||||
PropertyKey::StaticIdentifier(ident) => {
|
||||
let key_idx = ctx.add_constant(Constant::String(ident.name.as_str().to_string()));
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(key_reg as u32), key_idx));
|
||||
Ok(key_reg)
|
||||
}
|
||||
_ => Err("computed destructuring key expression not supported".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_object_property_read_key(
|
||||
&self, src_reg: u8, key: &PropertyKey, computed: bool, ctx: &mut CompileCtx,
|
||||
) -> Result<(u8, Option<String>), String> {
|
||||
if !computed {
|
||||
let key_name = self.static_property_name(key)?;
|
||||
let prop_reg = self.emit_object_property_read(src_reg, &key_name, ctx);
|
||||
return Ok((prop_reg, Some(key_name)));
|
||||
}
|
||||
let prop_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(prop_reg as u32), Operand::Reg(src_reg as u32), Operand::None));
|
||||
let key_reg = self.emit_property_key_expression(key, ctx)?;
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::GET_PROP_DYNAMIC, Operand::Reg(prop_reg as u32), Operand::Reg(key_reg as u32), Operand::Reg(val_reg as u32)));
|
||||
Ok((val_reg, None))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{Expression, PropertyKey};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_public_field_init(
|
||||
&self, target: Operand, key: &PropertyKey, computed: bool, value: Option<&Expression>, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let key_reg = self.emit_class_key_reg(key, computed, ctx)?;
|
||||
let value_reg = if let Some(expr) = value {
|
||||
self.emit_expression(expr, ctx)?
|
||||
} else {
|
||||
self.emit_undefined(ctx)
|
||||
};
|
||||
if computed {
|
||||
ctx.inst(Inst::new(OpCode::SET_PROP_DYNAMIC, target, Operand::Reg(key_reg as u32), Operand::Reg(value_reg as u32)));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::SET_PROP, target, Operand::Reg(value_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn emit_private_field_init(
|
||||
&self, target: Operand, name: &str, value: Option<&Expression>, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let key_reg = self.emit_private_id_reg(name, ctx)?;
|
||||
let value_reg = if let Some(expr) = value {
|
||||
self.emit_expression(expr, ctx)?
|
||||
} else {
|
||||
self.emit_undefined(ctx)
|
||||
};
|
||||
ctx.inst(Inst::new(OpCode::INIT_PRIVATE, target, Operand::Reg(value_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn emit_private_method_init(
|
||||
&self, target: Operand, method: &oxide_parser::MethodDefinition, home_reg: Operand, ctx: &mut CompileCtx,
|
||||
) -> Result<(), String> {
|
||||
let PropertyKey::PrivateIdentifier(private) = &method.key else {
|
||||
return Err("expected private method key".into());
|
||||
};
|
||||
let name = private.name.as_str();
|
||||
let key_reg = self.emit_private_id_reg(name, ctx)?;
|
||||
let method_reg = self.emit_class_method_function(method, name, home_reg, ctx, &[])?;
|
||||
ctx.inst(Inst::new(OpCode::INIT_PRIVATE, target, Operand::Reg(method_reg as u32), Operand::Reg(key_reg as u32)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_parser::PropertyKey;
|
||||
|
||||
impl Emitter {
|
||||
fn private_name_id(&self, name: &str, ctx: &CompileCtx) -> Result<u32, String> {
|
||||
ctx.scopes
|
||||
.private_name_map
|
||||
.iter()
|
||||
.find_map(|(n, id)| (n == name).then_some(*id))
|
||||
.ok_or_else(|| format!("private name #{name} is not defined"))
|
||||
}
|
||||
|
||||
pub(crate) fn emit_private_id_reg(&self, name: &str, ctx: &mut CompileCtx) -> Result<u8, String> {
|
||||
let id = self.private_name_id(name, ctx)?;
|
||||
let idx = ctx.add_constant(Constant::Int(id as i32));
|
||||
let reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(reg as u32), idx));
|
||||
Ok(reg)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_class_key_reg(
|
||||
&self, key: &PropertyKey, computed: bool, ctx: &mut CompileCtx,
|
||||
) -> Result<u8, String> {
|
||||
if !computed {
|
||||
let name = self.class_property_name(key)?;
|
||||
let idx = ctx.add_constant(Constant::String(name));
|
||||
let reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(reg as u32), idx));
|
||||
return Ok(reg);
|
||||
}
|
||||
|
||||
if matches!(key, PropertyKey::PrivateIdentifier(_)) {
|
||||
return Err("private class elements not yet supported".into());
|
||||
}
|
||||
self.emit_expression(key.to_expression(), ctx)
|
||||
}
|
||||
|
||||
pub(crate) fn static_property_name(&self, key: &PropertyKey) -> Result<String, String> {
|
||||
match key {
|
||||
PropertyKey::StaticIdentifier(ident) => Ok(ident.name.as_str().to_string()),
|
||||
PropertyKey::Identifier(ident) => Ok(ident.name.as_str().to_string()),
|
||||
PropertyKey::StringLiteral(s) => Ok(s.value.to_string()),
|
||||
PropertyKey::NumericLiteral(n) => Ok(n.value.to_string()),
|
||||
_ => Err("computed destructuring keys not yet supported".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn class_property_name(&self, key: &PropertyKey) -> Result<String, String> {
|
||||
match key {
|
||||
PropertyKey::StaticIdentifier(ident) => Ok(ident.name.as_str().to_string()),
|
||||
PropertyKey::Identifier(ident) => Ok(ident.name.as_str().to_string()),
|
||||
PropertyKey::StringLiteral(s) => Ok(s.value.to_string()),
|
||||
PropertyKey::NumericLiteral(n) => Ok(n.value.to_string()),
|
||||
PropertyKey::PrivateIdentifier(_) => Err("private class elements not yet supported".into()),
|
||||
_ => Err("unsupported class property key type".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_undefined(&self, ctx: &mut CompileCtx) -> u8 {
|
||||
let idx = ctx.add_constant(Constant::Undefined);
|
||||
let reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(reg as u32), idx));
|
||||
reg
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod binding;
|
||||
pub mod chain;
|
||||
pub mod class_field;
|
||||
pub mod class_key;
|
||||
@@ -0,0 +1,42 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_break_statement(
|
||||
&self, stmt: &oxide_parser::BreakStatement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let break_label = if let Some(label) = &stmt.label {
|
||||
let name = label.name.as_str();
|
||||
let scope = ctx
|
||||
.find_label(name)
|
||||
.ok_or_else(|| format!("SyntaxError: Undefined label '{name}'"))?;
|
||||
scope.break_label
|
||||
} else if let Some(sw_label) = ctx.current_switch() {
|
||||
*sw_label
|
||||
} else {
|
||||
let (bl, _) = ctx.current_loop().ok_or("break outside switch or loop".to_string())?;
|
||||
*bl
|
||||
};
|
||||
ctx.inst(Inst::jmp(break_label));
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_continue_statement(
|
||||
&self, stmt: &oxide_parser::ContinueStatement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let continue_label = if let Some(label) = &stmt.label {
|
||||
let name = label.name.as_str();
|
||||
let scope = ctx
|
||||
.find_label(name)
|
||||
.ok_or_else(|| format!("SyntaxError: Undefined label '{name}'"))?;
|
||||
scope.continue_label.ok_or_else(|| {
|
||||
format!("SyntaxError: Illegal continue statement: '{name}' does not denote an iteration statement")
|
||||
})?
|
||||
} else {
|
||||
let (_, cl) = ctx.current_loop().ok_or("continue outside loop".to_string())?;
|
||||
*cl
|
||||
};
|
||||
ctx.inst(Inst::jmp(continue_label));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_expression_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ExpressionStatement(es) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(self.emit_expression(&es.expression, ctx)?))
|
||||
}
|
||||
|
||||
pub(crate) fn emit_basic_expression(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
self.emit_expression_statement(stmt, ctx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn is_iteration_statement(stmt: &Statement) -> bool {
|
||||
matches!(
|
||||
stmt,
|
||||
Statement::WhileStatement(_)
|
||||
| Statement::DoWhileStatement(_)
|
||||
| Statement::ForStatement(_)
|
||||
| Statement::ForInStatement(_)
|
||||
| Statement::ForOfStatement(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_labeled_statement(
|
||||
&self, stmt: &oxide_parser::LabeledStatement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let name = stmt.label.name.as_str();
|
||||
if Self::is_iteration_statement(&stmt.body) {
|
||||
ctx.queue_loop_label(name)?;
|
||||
self.emit_statement(&stmt.body, ctx)?;
|
||||
} else {
|
||||
let id = ctx.next_label_id();
|
||||
ctx.push_label_scope(name, id, None)?;
|
||||
self.emit_statement(&stmt.body, ctx)?;
|
||||
ctx.labels.set_label_pos(id, ctx.insts.len());
|
||||
ctx.pop_label_scope();
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
mod break_continue;
|
||||
mod expression;
|
||||
mod labeled;
|
||||
mod return_stmt;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_basic_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::ExpressionStatement(_) => self.emit_basic_expression(stmt, ctx),
|
||||
Statement::ReturnStatement(_) => self.emit_basic_return(stmt, ctx),
|
||||
Statement::EmptyStatement(_) => Ok(None),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_return_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ReturnStatement(ret) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
match &ret.argument {
|
||||
Some(expr) => {
|
||||
let r = self.emit_expression(expr, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::RETURN, Operand::Reg(r as u32), Operand::None, Operand::None));
|
||||
}
|
||||
None => {
|
||||
ctx.inst(Inst::new(OpCode::RETURN, Operand::None, Operand::None, Operand::None));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_basic_return(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
self.emit_return_statement(stmt, ctx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_block_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::BlockStatement(block) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
ctx.push_scope();
|
||||
let mut r = None;
|
||||
for s in &block.body {
|
||||
if let Some(rr) = self.emit_statement(s, ctx)? {
|
||||
r = Some(rr);
|
||||
}
|
||||
}
|
||||
ctx.pop_scope();
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_block_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::BlockStatement(_) => self.emit_block_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_if_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::IfStatement(ifs) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let else_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
|
||||
let test_reg = self.emit_expression(&ifs.test, ctx)?;
|
||||
|
||||
ctx.inst(Inst::jmp_if_false(test_reg, else_label));
|
||||
|
||||
let cons_reg = self.emit_statement(&ifs.consequent, ctx)?;
|
||||
let result_reg = ctx.alloc_reg();
|
||||
if let Some(r) = cons_reg {
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(r as u32), Operand::None));
|
||||
} else {
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
ctx.inst(Inst::load_const(Operand::Reg(result_reg as u32), undef_idx));
|
||||
}
|
||||
|
||||
if ifs.alternate.is_some() {
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
}
|
||||
|
||||
ctx.labels.set_label_pos(else_label, ctx.insts.len());
|
||||
if let Some(alt) = &ifs.alternate {
|
||||
let alt_reg = self.emit_statement(alt, ctx)?;
|
||||
if let Some(r) = alt_reg {
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(r as u32), Operand::None));
|
||||
} else {
|
||||
let undef_idx = ctx.add_constant(Constant::Undefined);
|
||||
ctx.inst(Inst::load_const(Operand::Reg(result_reg as u32), undef_idx));
|
||||
}
|
||||
}
|
||||
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
|
||||
Ok(Some(result_reg))
|
||||
}
|
||||
|
||||
pub(crate) fn emit_control_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::IfStatement(_) => self.emit_if_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_class_declaration_statement(
|
||||
&self, stmt: &Statement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let Statement::ClassDeclaration(class) = stmt else {
|
||||
return Err("ClassDeclaration without name".into());
|
||||
};
|
||||
let name = class
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.name.to_string())
|
||||
.ok_or_else(|| "ClassDeclaration without name".to_string())?;
|
||||
let var_reg = ctx.alloc_reg();
|
||||
ctx.declare(&name, var_reg, VariableDeclarationKind::Let, false)?;
|
||||
ctx.init_var(&name);
|
||||
let ctor_reg = self.emit_class(class, ctx)?;
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(&name) {
|
||||
ctx.inst(Inst::new(OpCode::MAKE_CELL, Operand::Reg(var_reg as u32), Operand::Imm(cell_idx as u16), Operand::None));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(ctor_reg as u32), Operand::None));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use crate::{CompileCtx, Emitter, ParamSpec};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_function_declaration_statement(
|
||||
&self, stmt: &Statement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let Statement::FunctionDeclaration(fd) = stmt else {
|
||||
return Err("FunctionDeclaration without name".into());
|
||||
};
|
||||
let name = if let Some(id) = &fd.id {
|
||||
id.name.to_string()
|
||||
} else {
|
||||
return Err("FunctionDeclaration without name".into());
|
||||
};
|
||||
let mut param_names = Vec::new();
|
||||
for (idx, param) in fd.params.items.iter().enumerate() {
|
||||
match ¶m.pattern {
|
||||
oxide_parser::BindingPattern::BindingIdentifier(bi) => {
|
||||
param_names.push(ParamSpec::Identifier(bi.name.to_string()))
|
||||
}
|
||||
pattern => param_names.push(ParamSpec::Pattern {
|
||||
synthetic_name: format!("@@param_{idx}"),
|
||||
pattern,
|
||||
}),
|
||||
}
|
||||
}
|
||||
let body_stmts: &[Statement] = if let Some(body) = &fd.body { &body.statements } else { &[] };
|
||||
let mut sub_module = self.compile_function_body(¶m_names, body_stmts, ctx, false, false)?;
|
||||
sub_module.function_name = Some(name.clone());
|
||||
ctx.nested.push(sub_module);
|
||||
let var_reg = ctx.lookup(&name)?;
|
||||
ctx.reserve_reg(var_reg);
|
||||
ctx.inst(Inst::create_closure(Operand::Reg(var_reg as u32), ctx.nested.len() as u16));
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(&name) {
|
||||
ctx.inst(Inst::new(OpCode::MAKE_CELL, Operand::Reg(var_reg as u32), Operand::Imm(cell_idx as u16), Operand::None));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(var_reg as u32), Operand::None));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
mod class_decl;
|
||||
mod function_decl;
|
||||
mod var;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_declaration_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::VariableDeclaration(_) => self.emit_variable_declaration_statement(stmt, ctx),
|
||||
Statement::FunctionDeclaration(_) => self.emit_function_declaration_statement(stmt, ctx),
|
||||
Statement::ClassDeclaration(_) => self.emit_class_declaration_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{BindingPattern, Expression, Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_variable_declaration_statement(
|
||||
&self, stmt: &Statement, ctx: &mut CompileCtx,
|
||||
) -> Result<Option<u8>, String> {
|
||||
let Statement::VariableDeclaration(decl) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut r = None;
|
||||
for d in &decl.declarations {
|
||||
let is_const = matches!(decl.kind, VariableDeclarationKind::Const);
|
||||
if is_const && d.init.is_none() {
|
||||
return Err("const declaration must have an initializer".into());
|
||||
}
|
||||
if let Some(init) = &d.init {
|
||||
let val_reg = self.emit_expression(init, ctx)?;
|
||||
self.emit_binding_pattern(&d.id, val_reg, decl.kind, is_const, ctx)?;
|
||||
if let BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
if matches!(*init, Expression::ArrowFunctionExpression(_)) {
|
||||
if let Some(sub_mod) = ctx.nested.last_mut() {
|
||||
sub_mod.function_name = Some(bi.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
r = Some(val_reg);
|
||||
} else {
|
||||
let BindingPattern::BindingIdentifier(bi) = &d.id else {
|
||||
return Err("destructuring declaration requires an initializer".into());
|
||||
};
|
||||
let idx = ctx.add_constant(Constant::Undefined);
|
||||
let tmp = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(tmp as u32), idx));
|
||||
let var_reg = ctx.alloc_reg();
|
||||
let target_reg = if matches!(decl.kind, VariableDeclarationKind::Var) {
|
||||
match ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const) {
|
||||
Ok(()) => var_reg,
|
||||
Err(_) => ctx.lookup(bi.name.as_str()).unwrap_or(var_reg),
|
||||
}
|
||||
} else {
|
||||
ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const)?;
|
||||
var_reg
|
||||
};
|
||||
if let Some(&cell_idx) = ctx.captured_bindings.get(bi.name.as_str()) {
|
||||
ctx.inst(Inst::new(OpCode::MAKE_CELL, Operand::Reg(tmp as u32), Operand::Imm(cell_idx as u16), Operand::None));
|
||||
} else {
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(target_reg as u32), Operand::Reg(tmp as u32), Operand::None));
|
||||
}
|
||||
ctx.init_var(bi.name.as_str());
|
||||
r = Some(var_reg);
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
mod throw;
|
||||
mod try_catch;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_exception_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::ThrowStatement(_) => self.emit_throw_statement(stmt, ctx),
|
||||
Statement::TryStatement(_) => self.emit_try_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_throw_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ThrowStatement(ts) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let exc_reg = self.emit_expression(&ts.argument, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::THROW, Operand::Reg(exc_reg as u32), Operand::None, Operand::None));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_try_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::TryStatement(ts) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let catch_label = ctx.next_label_id();
|
||||
let finally_label = ctx.next_label_id();
|
||||
let try_end_label = ctx.next_label_id();
|
||||
let has_catch = ts.handler.is_some();
|
||||
let has_finally = ts.finalizer.is_some();
|
||||
let result_reg = ctx.alloc_reg();
|
||||
if has_finally {
|
||||
ctx.inst(Inst::try_finally_begin(finally_label));
|
||||
}
|
||||
if has_catch {
|
||||
ctx.inst(Inst::try_begin(catch_label));
|
||||
}
|
||||
let mut last_try_result: Option<u8> = None;
|
||||
for s in &ts.block.body {
|
||||
if let Some(r) = self.emit_statement(s, ctx)? {
|
||||
last_try_result = Some(r);
|
||||
}
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(last_try_result.unwrap_or(result_reg) as u32), Operand::None));
|
||||
if has_catch {
|
||||
ctx.inst(Inst::new(OpCode::TRY_END, Operand::None, Operand::None, Operand::None));
|
||||
}
|
||||
let jmp_needed = has_catch || has_finally;
|
||||
if jmp_needed {
|
||||
let target = if has_finally { finally_label } else { try_end_label };
|
||||
ctx.inst(Inst::jmp(target));
|
||||
}
|
||||
ctx.labels.set_label_pos(catch_label, ctx.insts.len());
|
||||
if let Some(catch) = &ts.handler {
|
||||
ctx.push_scope();
|
||||
if let Some(param) = &catch.param {
|
||||
let catch_reg = ctx.alloc_reg();
|
||||
if let oxide_parser::BindingPattern::BindingIdentifier(bi) = ¶m.pattern {
|
||||
ctx.declare_initialized(bi.name.as_str(), catch_reg, VariableDeclarationKind::Let, false)?;
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(catch_reg as u32), Operand::None, Operand::None));
|
||||
}
|
||||
}
|
||||
let mut last_catch_result: Option<u8> = None;
|
||||
for s in &catch.body.body {
|
||||
if let Some(r) = self.emit_statement(s, ctx)? {
|
||||
last_catch_result = Some(r);
|
||||
}
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(last_catch_result.unwrap_or(result_reg) as u32), Operand::None));
|
||||
ctx.pop_scope();
|
||||
}
|
||||
if has_finally {
|
||||
ctx.labels.set_label_pos(finally_label, ctx.insts.len());
|
||||
let mut last_finally_result: Option<u8> = None;
|
||||
for s in &ts.finalizer.as_ref().unwrap().body {
|
||||
if let Some(r) = self.emit_statement(s, ctx)? {
|
||||
last_finally_result = Some(r);
|
||||
}
|
||||
}
|
||||
ctx.inst(Inst::new(OpCode::LOAD_VAR, Operand::Reg(result_reg as u32), Operand::Reg(last_finally_result.unwrap_or(result_reg) as u32), Operand::None));
|
||||
ctx.inst(Inst::new(OpCode::TRY_FINALLY_END, Operand::None, Operand::None, Operand::None));
|
||||
}
|
||||
ctx.labels.set_label_pos(try_end_label, ctx.insts.len());
|
||||
Ok(Some(result_reg))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_do_while_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::DoWhileStatement(dw) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.labels.set_label_pos(start_label, ctx.insts.len());
|
||||
ctx.push_loop(end_label, start_label);
|
||||
let n_labeled = ctx.take_pending_loop_labels(end_label, start_label);
|
||||
self.emit_statement(&dw.body, ctx)?;
|
||||
let test_reg = self.emit_expression(&dw.test, ctx)?;
|
||||
ctx.inst(Inst::jmp_if_true(test_reg, start_label));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.pop_label_scopes(n_labeled);
|
||||
ctx.pop_loop();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::module::Constant;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{BindingPattern, ForStatementInit, Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_for_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ForStatement(fr) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_label = ctx.next_label_id();
|
||||
let update_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.push_loop(end_label, update_label);
|
||||
let n_labeled = ctx.take_pending_loop_labels(end_label, update_label);
|
||||
if let Some(init) = &fr.init {
|
||||
if let Some(expr) = init.as_expression() {
|
||||
self.emit_expression(expr, ctx)?;
|
||||
} else if let ForStatementInit::VariableDeclaration(decl) = init {
|
||||
for d in &decl.declarations {
|
||||
let is_const = matches!(decl.kind, VariableDeclarationKind::Const);
|
||||
if let Some(init_expr) = &d.init {
|
||||
let val_reg = self.emit_expression(init_expr, ctx)?;
|
||||
self.emit_binding_pattern(&d.id, val_reg, decl.kind, is_const, ctx)?;
|
||||
} else if let BindingPattern::BindingIdentifier(bi) = &d.id {
|
||||
let idx = ctx.add_constant(Constant::Undefined);
|
||||
let tmp = ctx.alloc_reg();
|
||||
ctx.inst(Inst::load_const(Operand::Reg(tmp as u32), idx));
|
||||
let var_reg = ctx.alloc_reg();
|
||||
let target_reg = if matches!(decl.kind, VariableDeclarationKind::Var) {
|
||||
match ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const) {
|
||||
Ok(()) => var_reg,
|
||||
Err(_) => ctx.lookup(bi.name.as_str()).unwrap_or(var_reg),
|
||||
}
|
||||
} else {
|
||||
ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const)?;
|
||||
var_reg
|
||||
};
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(target_reg as u32), Operand::Reg(tmp as u32), Operand::None));
|
||||
ctx.init_var(bi.name.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.labels.set_label_pos(start_label, ctx.insts.len());
|
||||
if let Some(test) = &fr.test {
|
||||
let test_reg = self.emit_expression(test, ctx)?;
|
||||
ctx.inst(Inst::jmp_if_false(test_reg, end_label));
|
||||
}
|
||||
self.emit_statement(&fr.body, ctx)?;
|
||||
ctx.labels.set_label_pos(update_label, ctx.insts.len());
|
||||
if let Some(update) = &fr.update {
|
||||
self.emit_expression(update, ctx)?;
|
||||
}
|
||||
ctx.inst(Inst::jmp(start_label));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.pop_label_scopes(n_labeled);
|
||||
ctx.pop_loop();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{ForStatementLeft, Statement, VariableDeclarationKind};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_for_in_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ForInStatement(fi) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let obj_reg = self.emit_expression(&fi.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::FOR_IN_INIT, Operand::None, Operand::Reg(obj_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(start_label, ctx.insts.len());
|
||||
ctx.push_loop(end_label, start_label);
|
||||
let n_labeled = ctx.take_pending_loop_labels(end_label, start_label);
|
||||
let done_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_IN_DONE, Operand::Reg(done_reg as u32), Operand::None, Operand::None));
|
||||
// done=true 表示迭代结束:done=false 时跳过 end jmp 继续迭代
|
||||
let continue_label = ctx.next_label_id();
|
||||
ctx.inst(Inst::jmp_if_false(done_reg, continue_label));
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
ctx.labels.set_label_pos(continue_label, ctx.insts.len());
|
||||
let key_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_IN_NEXT, Operand::Reg(key_reg as u32), Operand::None, Operand::None));
|
||||
match &fi.left {
|
||||
ForStatementLeft::VariableDeclaration(decl) => {
|
||||
for d in &decl.declarations {
|
||||
let name = match &d.id {
|
||||
oxide_parser::BindingPattern::BindingIdentifier(bi) => bi.name.as_str(),
|
||||
_ => return Err("destructuring not supported".into()),
|
||||
};
|
||||
let var_reg = ctx.alloc_reg();
|
||||
ctx.declare(name, var_reg, decl.kind, matches!(decl.kind, VariableDeclarationKind::Const))?;
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(key_reg as u32), Operand::None));
|
||||
ctx.init_var(name);
|
||||
}
|
||||
}
|
||||
ForStatementLeft::AssignmentTargetIdentifier(id_ref) => {
|
||||
let name = id_ref.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(key_reg as u32), Operand::None));
|
||||
}
|
||||
_ => return Err("unsupported for-in left-hand side".into()),
|
||||
}
|
||||
self.emit_statement(&fi.body, ctx)?;
|
||||
ctx.inst(Inst::jmp(start_label));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.inst(Inst::new(OpCode::FOR_IN_CLEANUP, Operand::None, Operand::None, Operand::None));
|
||||
ctx.pop_label_scopes(n_labeled);
|
||||
ctx.pop_loop();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::{ForStatementLeft, Statement};
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_for_of_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::ForOfStatement(fo) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
let iter_src_reg = self.emit_expression(&fo.right, ctx)?;
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_INIT, Operand::None, Operand::Reg(iter_src_reg as u32), Operand::None));
|
||||
ctx.labels.set_label_pos(start_label, ctx.insts.len());
|
||||
ctx.push_loop(end_label, start_label);
|
||||
let n_labeled = ctx.take_pending_loop_labels(end_label, start_label);
|
||||
let has_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_DONE, Operand::Reg(has_reg as u32), Operand::None, Operand::None));
|
||||
ctx.inst(Inst::jmp_if_false(has_reg, end_label));
|
||||
let val_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_NEXT, Operand::Reg(val_reg as u32), Operand::None, Operand::None));
|
||||
match &fo.left {
|
||||
ForStatementLeft::VariableDeclaration(decl) => {
|
||||
for d in &decl.declarations {
|
||||
self.emit_binding_pattern(&d.id, val_reg, decl.kind, false, ctx)?;
|
||||
}
|
||||
}
|
||||
ForStatementLeft::AssignmentTargetIdentifier(id_ref) => {
|
||||
let name = id_ref.name.as_str();
|
||||
let var_reg = ctx.lookup_or_global(name);
|
||||
ctx.inst(Inst::new(OpCode::STORE_VAR, Operand::Reg(var_reg as u32), Operand::Reg(val_reg as u32), Operand::None));
|
||||
}
|
||||
ForStatementLeft::ArrayAssignmentTarget(ap) => {
|
||||
self.emit_array_assignment(ap, val_reg, ctx)?;
|
||||
}
|
||||
ForStatementLeft::ObjectAssignmentTarget(op) => {
|
||||
self.emit_object_assignment(op, val_reg, ctx)?;
|
||||
}
|
||||
_ => return Err("unsupported for-of left-hand side".into()),
|
||||
}
|
||||
self.emit_statement(&fo.body, ctx)?;
|
||||
ctx.inst(Inst::jmp(start_label));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.inst(Inst::new(OpCode::FOR_OF_CLOSE, Operand::None, Operand::None, Operand::None));
|
||||
ctx.pop_label_scopes(n_labeled);
|
||||
ctx.pop_loop();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_parser::Statement;
|
||||
|
||||
mod do_while;
|
||||
mod for_;
|
||||
mod for_in;
|
||||
mod for_of;
|
||||
mod while_loop;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_iteration_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::WhileStatement(_) => self.emit_while_statement(stmt, ctx),
|
||||
Statement::DoWhileStatement(_) => self.emit_do_while_statement(stmt, ctx),
|
||||
Statement::ForStatement(_) => self.emit_for_statement(stmt, ctx),
|
||||
Statement::ForInStatement(_) => self.emit_for_in_statement(stmt, ctx),
|
||||
Statement::ForOfStatement(_) => self.emit_for_of_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
pub(crate) fn emit_while_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::WhileStatement(wh) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let start_label = ctx.next_label_id();
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.labels.set_label_pos(start_label, ctx.insts.len());
|
||||
ctx.push_loop(end_label, start_label);
|
||||
let n_labeled = ctx.take_pending_loop_labels(end_label, start_label);
|
||||
let test_reg = self.emit_expression(&wh.test, ctx)?;
|
||||
ctx.inst(Inst::jmp_if_false(test_reg, end_label));
|
||||
self.emit_statement(&wh.body, ctx)?;
|
||||
ctx.inst(Inst::jmp(start_label));
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.pop_label_scopes(n_labeled);
|
||||
ctx.pop_loop();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod basic;
|
||||
pub mod block;
|
||||
pub mod control;
|
||||
pub mod declaration;
|
||||
pub mod exception;
|
||||
pub mod iteration;
|
||||
pub mod switch;
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{CompileCtx, Emitter};
|
||||
use oxide_ir::inst::Inst;
|
||||
use oxide_ir::operand::Operand;
|
||||
use oxide_bytecode::opcode::OpCode;
|
||||
use oxide_parser::Statement;
|
||||
|
||||
impl Emitter {
|
||||
fn emit_switch_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
let Statement::SwitchStatement(sw) = stmt else {
|
||||
return Ok(None);
|
||||
};
|
||||
let end_label = ctx.next_label_id();
|
||||
ctx.push_switch(end_label);
|
||||
let disc_reg = self.emit_expression(&sw.discriminant, ctx)?;
|
||||
let compare_reg_checkpoint = ctx.reg_checkpoint();
|
||||
let cases = &sw.cases;
|
||||
let mut case_labels = Vec::with_capacity(cases.len());
|
||||
for case in cases.iter() {
|
||||
let case_label = ctx.next_label_id();
|
||||
case_labels.push(case_label);
|
||||
if let Some(test) = &case.test {
|
||||
let test_reg = self.emit_expression(test, ctx)?;
|
||||
let eq_reg = ctx.alloc_reg();
|
||||
ctx.inst(Inst::new(OpCode::EQ, Operand::Reg(eq_reg as u32), Operand::Reg(disc_reg as u32), Operand::Reg(test_reg as u32)));
|
||||
ctx.inst(Inst::jmp_if_true(eq_reg, case_label));
|
||||
ctx.restore_reg_checkpoint(compare_reg_checkpoint);
|
||||
}
|
||||
}
|
||||
let has_default = cases.iter().any(|c| c.test.is_none());
|
||||
if !has_default {
|
||||
ctx.inst(Inst::jmp(end_label));
|
||||
}
|
||||
for (case_idx, case) in cases.iter().enumerate() {
|
||||
let case_label = case_labels[case_idx];
|
||||
ctx.labels.set_label_pos(case_label, ctx.insts.len());
|
||||
for s in &case.consequent {
|
||||
self.emit_statement(s, ctx)?;
|
||||
}
|
||||
}
|
||||
ctx.labels.set_label_pos(end_label, ctx.insts.len());
|
||||
ctx.pop_switch();
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn emit_switch_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
|
||||
match stmt {
|
||||
Statement::SwitchStatement(_) => self.emit_switch_statement(stmt, ctx),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use oxide_parser::VariableDeclarationKind;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ScopeKind {
|
||||
FunctionScope,
|
||||
BlockScope,
|
||||
}
|
||||
|
||||
pub(crate) struct Scope {
|
||||
pub(crate) bindings: HashMap<String, Binding>,
|
||||
pub(crate) kind: ScopeKind,
|
||||
}
|
||||
|
||||
pub(crate) struct Binding {
|
||||
pub(crate) reg: u8,
|
||||
pub(crate) initialized: bool,
|
||||
pub(crate) is_const: bool,
|
||||
}
|
||||
|
||||
pub struct SymbolTable {
|
||||
pub(crate) scopes: Vec<Scope>,
|
||||
}
|
||||
|
||||
impl Default for SymbolTable {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl SymbolTable {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
scopes: vec![Scope {
|
||||
bindings: HashMap::new(),
|
||||
kind: ScopeKind::FunctionScope,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_scope(&mut self) {
|
||||
self.scopes.push(Scope {
|
||||
bindings: HashMap::new(),
|
||||
kind: ScopeKind::BlockScope,
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn push_scope_with_kind(&mut self, kind: ScopeKind) {
|
||||
self.scopes.push(Scope { bindings: HashMap::new(), kind });
|
||||
}
|
||||
|
||||
pub fn pop_scope(&mut self) {
|
||||
if self.scopes.len() > 1 {
|
||||
self.scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn find_var_target_scope(&self) -> usize {
|
||||
for (i, scope) in self.scopes.iter().enumerate().rev() {
|
||||
if scope.kind == ScopeKind::FunctionScope {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
pub fn declare(
|
||||
&mut self, name: &str, reg: u8, kind: VariableDeclarationKind, is_const: bool,
|
||||
) -> Result<(), String> {
|
||||
let target_idx = if matches!(kind, VariableDeclarationKind::Var) {
|
||||
self.find_var_target_scope()
|
||||
} else {
|
||||
self.scopes.len() - 1
|
||||
};
|
||||
|
||||
let target = &mut self.scopes[target_idx];
|
||||
if target.bindings.contains_key(name) {
|
||||
return Err(format!("Identifier '{name}' has already been declared"));
|
||||
}
|
||||
target.bindings.insert(
|
||||
name.to_string(),
|
||||
Binding {
|
||||
reg,
|
||||
initialized: false,
|
||||
is_const: matches!(kind, VariableDeclarationKind::Const) || is_const,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn lookup(&self, name: &str) -> Result<u8, String> {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
if let Some(b) = scope.bindings.get(name) {
|
||||
if b.initialized {
|
||||
return Ok(b.reg);
|
||||
}
|
||||
return Err(format!("Cannot access '{name}' before initialization"));
|
||||
}
|
||||
}
|
||||
Err(format!("Identifier '{name}' is not defined"))
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_any(&self, name: &str) -> Option<u8> {
|
||||
self.scopes
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|scope| scope.bindings.get(name).map(|binding| binding.reg))
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_any_binding(&self, name: &str) -> Option<(&Binding, usize)> {
|
||||
for (i, scope) in self.scopes.iter().enumerate().rev() {
|
||||
if let Some(b) = scope.bindings.get(name) {
|
||||
return Some((b, i));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn lookup_or_global(&mut self, name: &str, reg_for_new: u8) -> u8 {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
if let Some(b) = scope.bindings.get(name) {
|
||||
return b.reg;
|
||||
}
|
||||
}
|
||||
self.scopes[0].bindings.insert(
|
||||
name.to_string(),
|
||||
Binding {
|
||||
reg: reg_for_new,
|
||||
initialized: true,
|
||||
is_const: false,
|
||||
},
|
||||
);
|
||||
reg_for_new
|
||||
}
|
||||
|
||||
pub fn lookup_is_const(&self, name: &str) -> bool {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
if let Some(b) = scope.bindings.get(name) {
|
||||
if b.initialized {
|
||||
return b.is_const;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn declare_initialized(
|
||||
&mut self, name: &str, reg: u8, kind: VariableDeclarationKind, is_const: bool,
|
||||
) -> Result<(), String> {
|
||||
let target_idx = if matches!(kind, VariableDeclarationKind::Var) {
|
||||
self.find_var_target_scope()
|
||||
} else {
|
||||
self.scopes.len() - 1
|
||||
};
|
||||
|
||||
let target = &mut self.scopes[target_idx];
|
||||
if let Some(b) = target.bindings.get_mut(name) {
|
||||
b.initialized = true;
|
||||
return Ok(());
|
||||
}
|
||||
target.bindings.insert(
|
||||
name.to_string(),
|
||||
Binding {
|
||||
reg,
|
||||
initialized: true,
|
||||
is_const: matches!(kind, VariableDeclarationKind::Const) || is_const,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn pre_register_global(&mut self, name: &str, reg: u8) {
|
||||
self.scopes[0].bindings.entry(name.to_string()).or_insert(Binding {
|
||||
reg,
|
||||
initialized: true,
|
||||
is_const: false,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn init_var(&mut self, name: &str) {
|
||||
for scope in self.scopes.iter_mut().rev() {
|
||||
if let Some(b) = scope.bindings.get_mut(name) {
|
||||
b.initialized = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SymbolTable;
|
||||
use oxide_parser::VariableDeclarationKind;
|
||||
|
||||
fn v() -> VariableDeclarationKind {
|
||||
VariableDeclarationKind::Var
|
||||
}
|
||||
fn l() -> VariableDeclarationKind {
|
||||
VariableDeclarationKind::Let
|
||||
}
|
||||
fn c() -> VariableDeclarationKind {
|
||||
VariableDeclarationKind::Const
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_scope_exists() {
|
||||
let st = SymbolTable::new();
|
||||
assert!(st.lookup("x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declare_and_lookup() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
assert_eq!(st.lookup("x").unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tdz_error() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
assert!(st.lookup("x").unwrap_err().contains("before initialization"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_declaration_error() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
assert!(st.declare("x", 1, l(), false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_scopes_shadow() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
st.push_scope();
|
||||
st.declare("x", 1, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
assert_eq!(st.lookup("x").unwrap(), 1);
|
||||
st.pop_scope();
|
||||
assert_eq!(st.lookup("x").unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_or_global_auto_create() {
|
||||
let mut st = SymbolTable::new();
|
||||
let reg = st.lookup_or_global("x", 5);
|
||||
assert_eq!(reg, 5);
|
||||
assert_eq!(st.lookup("x").unwrap(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_or_global_existing() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 3, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
let reg = st.lookup_or_global("x", 99);
|
||||
assert_eq!(reg, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn var_hoists_to_function_scope() {
|
||||
let mut st = SymbolTable::new();
|
||||
// Global scope is FunctionScope
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
// Push a block scope
|
||||
st.push_scope();
|
||||
// var declaration inside block should go to function scope
|
||||
st.declare("y", 1, v(), false).unwrap();
|
||||
st.init_var("y");
|
||||
st.pop_scope();
|
||||
// y should be accessible (it was declared in function scope, not block scope)
|
||||
assert_eq!(st.lookup("y").unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn let_block_scoped() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
st.push_scope();
|
||||
st.declare("x", 1, l(), false).unwrap();
|
||||
st.init_var("x");
|
||||
assert_eq!(st.lookup("x").unwrap(), 1);
|
||||
st.pop_scope();
|
||||
assert_eq!(st.lookup("x").unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn const_has_is_const_flag() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.declare("x", 0, c(), false).unwrap();
|
||||
st.init_var("x");
|
||||
let reg = st.lookup("x").unwrap();
|
||||
assert_eq!(reg, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn var_in_two_blocks_same_function_scope_is_duplicate() {
|
||||
let mut st = SymbolTable::new();
|
||||
st.push_scope();
|
||||
st.declare("y", 1, v(), false).unwrap();
|
||||
st.pop_scope();
|
||||
st.push_scope();
|
||||
// Same function scope, so this should be a duplicate
|
||||
assert!(st.declare("y", 2, v(), false).is_err());
|
||||
st.pop_scope();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user