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

This commit is contained in:
爱特每羊队
2026-08-05 20:13:18 +08:00
parent 9f02985a82
commit bbdfca1a1c
62 changed files with 1045 additions and 993 deletions
@@ -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)
}
}
+18
View File
@@ -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)
}
}
+26
View File
@@ -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),
}
}
}
+55
View File
@@ -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 &param.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(&param_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) = &param.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)
}
}
+7
View File
@@ -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;
+51
View File
@@ -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),
}
}
}