refactor: 拆分编译流水线过程以避免逻辑漂移

This commit is contained in:
爱特每羊队
2026-07-05 14:41:08 +08:00
parent a4c13c4f6a
commit ff6de1e4e7
62 changed files with 2190 additions and 1152 deletions
+68 -30
View File
@@ -880,10 +880,8 @@ impl Compiler {
) )
} }
#[expect(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn pre_scan_function_expressions( fn pre_scan_function_expressions(&self, stmts: &[Statement], parent_ctx: &mut CompileCtx) -> Result<(), String> {
&self, stmts: &[Statement], parent_ctx: &mut CompileCtx,
) -> Result<(), String> {
for stmt in stmts { for stmt in stmts {
self.pre_scan_stmt(stmt, parent_ctx)?; self.pre_scan_stmt(stmt, parent_ctx)?;
} }
@@ -893,16 +891,30 @@ impl Compiler {
fn pre_scan_stmt(&self, stmt: &Statement, parent_ctx: &mut CompileCtx) -> Result<(), String> { fn pre_scan_stmt(&self, stmt: &Statement, parent_ctx: &mut CompileCtx) -> Result<(), String> {
match stmt { match stmt {
Statement::ExpressionStatement(es) => self.pre_scan_expr(&es.expression, parent_ctx)?, Statement::ExpressionStatement(es) => self.pre_scan_expr(&es.expression, parent_ctx)?,
Statement::ReturnStatement(rs) => { if let Some(a) = &rs.argument { self.pre_scan_expr(a, parent_ctx)?; } } Statement::ReturnStatement(rs) => {
if let Some(a) = &rs.argument {
self.pre_scan_expr(a, parent_ctx)?;
}
}
Statement::IfStatement(is) => { Statement::IfStatement(is) => {
self.pre_scan_expr(&is.test, parent_ctx)?; self.pre_scan_expr(&is.test, parent_ctx)?;
self.pre_scan_stmt(&is.consequent, parent_ctx)?; self.pre_scan_stmt(&is.consequent, parent_ctx)?;
if let Some(alt) = &is.alternate { self.pre_scan_stmt(alt, parent_ctx)?; } if let Some(alt) = &is.alternate {
self.pre_scan_stmt(alt, parent_ctx)?;
}
} }
Statement::ForStatement(fs) => { Statement::ForStatement(fs) => {
if let Some(init) = &fs.init { if let Some(e) = init.as_expression() { self.pre_scan_expr(e, parent_ctx)?; } } if let Some(init) = &fs.init {
if let Some(t) = &fs.test { self.pre_scan_expr(t, parent_ctx)?; } if let Some(e) = init.as_expression() {
if let Some(u) = &fs.update { self.pre_scan_expr(u, parent_ctx)?; } self.pre_scan_expr(e, parent_ctx)?;
}
}
if let Some(t) = &fs.test {
self.pre_scan_expr(t, parent_ctx)?;
}
if let Some(u) = &fs.update {
self.pre_scan_expr(u, parent_ctx)?;
}
self.pre_scan_stmt(&fs.body, parent_ctx)?; self.pre_scan_stmt(&fs.body, parent_ctx)?;
} }
Statement::BlockStatement(bs) => self.pre_scan_function_expressions(&bs.body, parent_ctx)?, Statement::BlockStatement(bs) => self.pre_scan_function_expressions(&bs.body, parent_ctx)?,
@@ -926,19 +938,45 @@ impl Compiler {
Expression::ArrowFunctionExpression(_ae) => {} Expression::ArrowFunctionExpression(_ae) => {}
Expression::CallExpression(ce) => { Expression::CallExpression(ce) => {
self.pre_scan_expr(&ce.callee, parent_ctx)?; self.pre_scan_expr(&ce.callee, parent_ctx)?;
for arg in &ce.arguments { if let Some(e) = arg.as_expression() { self.pre_scan_expr(e, parent_ctx)?; } } for arg in &ce.arguments {
if let Some(e) = arg.as_expression() {
self.pre_scan_expr(e, parent_ctx)?;
}
}
}
Expression::BinaryExpression(be) => {
self.pre_scan_expr(&be.left, parent_ctx)?;
self.pre_scan_expr(&be.right, parent_ctx)?;
}
Expression::ConditionalExpression(ce) => {
self.pre_scan_expr(&ce.test, parent_ctx)?;
self.pre_scan_expr(&ce.consequent, parent_ctx)?;
self.pre_scan_expr(&ce.alternate, parent_ctx)?;
}
Expression::ArrayExpression(ae) => {
for e in &ae.elements {
if let Some(e) = e.as_expression() {
self.pre_scan_expr(e, parent_ctx)?;
}
}
}
Expression::SequenceExpression(se) => {
for e in &se.expressions {
self.pre_scan_expr(e, parent_ctx)?;
}
}
Expression::AssignmentExpression(ae) => {
self.pre_scan_expr(&ae.right, parent_ctx)?;
}
Expression::UnaryExpression(ue) => {
self.pre_scan_expr(&ue.argument, parent_ctx)?;
} }
Expression::BinaryExpression(be) => { self.pre_scan_expr(&be.left, parent_ctx)?; self.pre_scan_expr(&be.right, parent_ctx)?; }
Expression::ConditionalExpression(ce) => { self.pre_scan_expr(&ce.test, parent_ctx)?; self.pre_scan_expr(&ce.consequent, parent_ctx)?; self.pre_scan_expr(&ce.alternate, parent_ctx)?; }
Expression::ArrayExpression(ae) => { for e in &ae.elements { if let Some(e) = e.as_expression() { self.pre_scan_expr(e, parent_ctx)?; } } }
Expression::SequenceExpression(se) => { for e in &se.expressions { self.pre_scan_expr(e, parent_ctx)?; } }
Expression::AssignmentExpression(ae) => { self.pre_scan_expr(&ae.right, parent_ctx)?; }
Expression::UnaryExpression(ue) => { self.pre_scan_expr(&ue.argument, parent_ctx)?; }
_ => {} _ => {}
} }
Ok(()) Ok(())
} }
#[allow(clippy::too_many_arguments)]
pub(crate) fn compile_function_body_with_field_hooks<'a, C, E>( pub(crate) fn compile_function_body_with_field_hooks<'a, C, E>(
&self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx, &self, param_specs: &[ParamSpec<'a>], body_stmts: &[Statement<'a>], parent_ctx: &CompileCtx,
is_expression_body: bool, extra_bindings: &[(&str, u8)], body_context: FunctionBodyContext, is_expression_body: bool, extra_bindings: &[(&str, u8)], body_context: FunctionBodyContext,
@@ -1117,13 +1155,13 @@ impl Compiler {
} }
} }
debug_assert_eq!( if counted_pc != ctx.bytecode.len() {
counted_pc, return Err(format!(
ctx.bytecode.len(), "counter/emitter instruction drift in function body (before implicit RETURN): counted {} vs emitted {}",
"counter/emitter instruction drift in function body (before implicit RETURN): counted {} vs emitted {}", counted_pc,
counted_pc, ctx.bytecode.len()
ctx.bytecode.len() ));
); }
// Emit implicit RETURN: expression body returns the last expression, // Emit implicit RETURN: expression body returns the last expression,
// statement body returns undefined. // statement body returns undefined.
@@ -1237,13 +1275,13 @@ impl Compiler {
} }
crate::compiler_debug!("emitter: {} bytes emitted", ctx.bytecode.len()); crate::compiler_debug!("emitter: {} bytes emitted", ctx.bytecode.len());
debug_assert_eq!( if counted_pc != ctx.bytecode.len() {
counted_pc, return Err(format!(
ctx.bytecode.len(), "counter/emitter instruction drift in top-level module (before result store + HALT): counted {} vs emitted {}",
"counter/emitter instruction drift in top-level module (before result store + HALT): counted {} vs emitted {}", counted_pc,
counted_pc, ctx.bytecode.len()
ctx.bytecode.len() ));
); }
if let Some(r) = last_result { if let Some(r) = last_result {
ctx.emit(opcode::encode(OpCode::LOAD_VAR, 0, r, 0)); ctx.emit(opcode::encode(OpCode::LOAD_VAR, 0, r, 0));
@@ -1,116 +0,0 @@
use super::*;
impl Compiler {
fn count_assignment_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::AssignmentExpression(assign) = expr else {
return;
};
if let oxide_parser::AssignmentTarget::StaticMemberExpression(member) = &assign.left {
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_static_member_logical_assignment(member, logical_op, &assign.right, ctx);
return;
}
self.count_expression(&member.object, ctx);
self.count_expression(&assign.right, ctx);
// Both plain (IC_SET_PROP) and compound (COMPOUND_MEMBER_*) emit one opcode + 3 ext
// words after the key load — no extra instruction for the compound case.
ctx.count_load_const(); // key
ctx.count_ic_set_with_ext(); // IC_SET_PROP or COMPOUND_MEMBER_* + 3 ext words
} else if let oxide_parser::AssignmentTarget::ComputedMemberExpression(member) = &assign.left {
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_computed_member_logical_assignment(member, logical_op, &assign.right, ctx);
return;
}
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
self.count_expression(&assign.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // SET_PROP_DYNAMIC
} else if let oxide_parser::AssignmentTarget::PrivateFieldExpression(member) = &assign.left {
self.count_expression(&member.object, ctx);
self.count_expression(&assign.right, ctx);
ctx.count_load_const(); // private id
ctx.count_instr(); // SET_PRIVATE
} else if let oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(ati) = &assign.left {
let name = ati.name.as_str();
// Check if target is an upvalue or captured cell
let is_upvalue = ctx.current_upvalue_captures.iter().any(|u| u.name == name);
let is_captured = ctx.scopes.symbols.lookup_is_captured(name);
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_identifier_logical_assignment(logical_op, &assign.right, ctx);
} else {
self.count_expression(&assign.right, ctx);
if assign.operator != AssignmentOperator::Assign {
ctx.projected_pc += 1; // COMPOUND_* on var
} else if is_upvalue {
ctx.count_instr(); // STORE_UPVALUE
} else if is_captured {
ctx.count_instr(); // CELL_SET
} else {
ctx.alloc_reg();
ctx.projected_pc += 1; // STORE_VAR
}
}
} else if let oxide_parser::AssignmentTarget::ArrayAssignmentTarget(ap) = &assign.left {
self.count_expression(&assign.right, ctx);
self.count_array_assignment(ap, ctx);
} else if let oxide_parser::AssignmentTarget::ObjectAssignmentTarget(op) = &assign.left {
self.count_expression(&assign.right, ctx);
self.count_object_assignment(op, ctx);
} else {
self.count_expression(&assign.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
fn count_static_member_logical_assignment(
&self, member: &oxide_parser::StaticMemberExpression<'_>, logical_op: LogicalOperator, right: &Expression,
ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.count_load_var(); // current value copy
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.count_ic_set_with_ext(); // IC_SET_PROP + 3 ext
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
fn count_computed_member_logical_assignment(
&self, member: &oxide_parser::ComputedMemberExpression<'_>, logical_op: LogicalOperator, right: &Expression,
ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // GET_PROP_DYNAMIC
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.projected_pc += 1; // SET_PROP_DYNAMIC
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
fn count_identifier_logical_assignment(
&self, logical_op: LogicalOperator, right: &Expression, ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR result <- current var
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.projected_pc += 1; // STORE_VAR
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
pub(in crate::counter) fn count_assignment(&self, expr: &Expression, ctx: &mut CompileCtx) {
self.count_assignment_expression(expr, ctx);
}
}
@@ -1,78 +0,0 @@
use super::*;
impl Compiler {
fn count_call_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::CallExpression(call) = expr else {
return;
};
if matches!(&call.callee, Expression::Super(_)) {
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.alloc_reg();
ctx.count_call_instr_with_arg_ext(); // SUPER_CALL + arg_count ext word
// Mirror emit: derived-ctor instance fields are injected right after super().
if let Some(words) = ctx.after_super_count_words.take() {
ctx.projected_pc += words;
}
return;
}
match &call.callee {
Expression::PrivateFieldExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_private_access();
}
Expression::StaticMemberExpression(member) => {
if matches!(&member.object, Expression::Super(_)) {
ctx.count_load_var(); // this register
ctx.count_load_const(); // key
ctx.alloc_reg(); // callee
ctx.count_instr(); // SUPER_GET_PROP
} else {
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.count_load_var(); // callee object copy
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words
}
}
_ => {
self.count_expression(&call.callee, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.count_call_instr_with_arg_ext(); // CALL/CALL_NATIVE + arg_count ext word
ctx.count_load_var(); // result <- regs[0]
}
fn count_new_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::NewExpression(ne) = expr else {
return;
};
self.count_expression(&ne.callee, ctx);
for arg in &ne.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.alloc_reg(); // result register
ctx.count_instr_with_ext(1); // NEW_EXPRESSION + arg_count ext word
}
pub(in crate::counter) fn count_call_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::CallExpression(_) => self.count_call_expression(expr, ctx),
Expression::NewExpression(_) => self.count_new_expression(expr, ctx),
_ => {}
}
}
}
@@ -1,17 +0,0 @@
use super::*;
impl Compiler {
pub(in crate::counter) fn count_chain_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ChainExpression(chain) = expr else {
return;
};
let id = ctx.next_label_id();
self.count_chain_element(&chain.expression, true, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR result <- chain value
ctx.projected_pc += 1; // JMP over short-circuit writer
ctx.labels.label_map.insert(Label::TernaryElse(id), ctx.projected_pc);
ctx.projected_pc += 1; // LOAD_CONST undefined
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
}
@@ -1,79 +0,0 @@
use super::*;
impl Compiler {
fn count_conditional_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ConditionalExpression(cond) = expr else {
return;
};
let id = ctx.next_label_id();
let else_label = Label::TernaryElse(id);
let end_label = Label::TernaryEnd(id);
self.count_expression(&cond.test, ctx);
ctx.projected_pc += 1; // JMP_IF_FALSE
self.count_expression(&cond.consequent, ctx);
ctx.alloc_reg(); // result register
ctx.projected_pc += 1; // LOAD_VAR result <- consequent
ctx.projected_pc += 1; // JMP to end
ctx.labels.label_map.insert(else_label, ctx.projected_pc);
self.count_expression(&cond.alternate, ctx);
ctx.projected_pc += 1; // LOAD_VAR result <- alternate
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn count_sequence_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::SequenceExpression(seq) = expr else {
return;
};
for e in &seq.expressions {
self.count_expression(e, ctx);
}
}
fn count_logical_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::LogicalExpression(log) = expr else {
return;
};
self.count_expression(&log.left, ctx);
let is_simple = is_side_effect_free(&log.left) && is_side_effect_free(&log.right);
if is_simple {
self.count_expression(&log.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // AND/OR
} else if matches!(log.operator, LogicalOperator::Coalesce) {
// Mirror emit_logical_expression's Coalesce path: it patches raw bytecode
// positions and does NOT consume a label id. Consuming one here would shift
// every later construct's label id and break resolve_label at emit time.
ctx.alloc_reg(); // dup register
ctx.projected_pc += 1; // LOAD_VAR (DUP)
ctx.projected_pc += 1; // JMP_IF_NULLISH
ctx.projected_pc += 1; // JMP over RHS on non-nullish
self.count_expression(&log.right, ctx);
ctx.projected_pc += 1; // LOAD_VAR (overwrite)
} else {
let id = ctx.next_label_id();
ctx.alloc_reg(); // dup register
ctx.projected_pc += 1; // LOAD_VAR (DUP)
ctx.projected_pc += 1; // JMP_IF_FALSE or JMP_IF_TRUE
self.count_expression(&log.right, ctx);
ctx.projected_pc += 1; // LOAD_VAR (overwrite)
let skip_label = match log.operator {
LogicalOperator::And => Label::TernaryEnd(id),
LogicalOperator::Or => Label::TernaryElse(id),
LogicalOperator::Coalesce => unreachable!("coalesce handled above"),
};
ctx.labels.label_map.insert(skip_label, ctx.projected_pc);
}
}
pub(in crate::counter) fn count_conditional_chain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::ConditionalExpression(_) => self.count_conditional_expression(expr, ctx),
Expression::SequenceExpression(_) => self.count_sequence_expression(expr, ctx),
Expression::LogicalExpression(_) => self.count_logical_expression(expr, ctx),
_ => {}
}
}
}
@@ -1,29 +0,0 @@
use super::*;
impl Compiler {
fn count_arrow_function_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST
}
fn count_function_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST
}
fn count_class_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ClassExpression(class) = expr else {
return;
};
self.count_class(class, ctx);
}
pub(in crate::counter) fn count_function_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::ArrowFunctionExpression(_) => self.count_arrow_function_expression(ctx),
Expression::FunctionExpression(_) => self.count_function_expression(ctx),
Expression::ClassExpression(_) => self.count_class_expression(expr, ctx),
_ => {}
}
}
}
@@ -1,62 +0,0 @@
use super::*;
impl Compiler {
/// Domain entry point: count any literal expression. The central
/// `count_expression` match delegates all literal variants here in one arm.
/// Numeric/String/Boolean/Null share the default single-`LOAD_CONST` shape;
/// RegExp emits three instructions.
pub(in crate::counter) fn count_literal(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::RegExpLiteral(_) => self.count_regexp_literal(ctx),
_ => self.count_default_expression(ctx),
}
}
pub(in crate::counter) fn count_this_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR from reg 254
}
pub(in crate::counter) fn count_identifier_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::Identifier(ident) = expr else {
return;
};
let name = ident.name.as_str();
// Check if this is an upvalue reference (nested closure)
for up in &ctx.current_upvalue_captures {
if up.name == name {
ctx.alloc_reg();
ctx.count_instr(); // LOAD_UPVALUE
return;
}
}
// Check if the owner's binding is captured (cell access)
if ctx.scopes.symbols.lookup_is_captured(name) {
ctx.alloc_reg();
ctx.count_instr(); // CELL_GET
return;
}
if CompileCtx::is_known_builtin(name) {
let _ = ctx.lookup_or_builtin(name);
}
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR
}
fn count_regexp_literal(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg(); // pattern reg (LOAD_CONST)
ctx.projected_pc += 1;
ctx.alloc_reg(); // flags reg (LOAD_CONST)
ctx.projected_pc += 1;
ctx.alloc_reg(); // result reg (CREATE_REGEXP)
ctx.projected_pc += 1;
}
pub(in crate::counter) fn count_default_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST or LOAD_VAR
}
}
@@ -1,53 +0,0 @@
use super::*;
impl Compiler {
fn count_static_member_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::StaticMemberExpression(member) = expr else {
return;
};
if matches!(&member.object, Expression::Super(_)) {
ctx.count_load_const(); // key
ctx.count_load_var(); // this
ctx.alloc_reg(); // result
ctx.count_instr(); // SUPER_GET_PROP
return;
}
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words
}
fn count_computed_member_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ComputedMemberExpression(member) = expr else {
return;
};
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // GET_PROP_DYNAMIC
}
fn count_private_field_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::PrivateFieldExpression(member) = expr else {
return;
};
self.count_expression(&member.object, ctx);
ctx.count_private_access();
}
pub(in crate::counter) fn count_parenthesized_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ParenthesizedExpression(p) = expr else {
return;
};
self.count_expression(&p.expression, ctx);
}
pub(in crate::counter) fn count_member_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::StaticMemberExpression(_) => self.count_static_member_expression(expr, ctx),
Expression::ComputedMemberExpression(_) => self.count_computed_member_expression(expr, ctx),
Expression::PrivateFieldExpression(_) => self.count_private_field_expression(expr, ctx),
_ => {}
}
}
}
@@ -1,48 +0,0 @@
use super::*;
mod assignment;
mod call;
mod chain;
mod control;
mod function;
mod literal;
mod member;
mod object;
mod operator;
mod template;
impl Compiler {
pub(crate) fn count_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::BinaryExpression(_)
| Expression::PrivateInExpression(_)
| Expression::UnaryExpression(_)
| Expression::UpdateExpression(_) => self.count_operator(expr, ctx),
Expression::CallExpression(_) | Expression::NewExpression(_) => self.count_call_domain(expr, ctx),
Expression::AssignmentExpression(_) => self.count_assignment(expr, ctx),
Expression::ConditionalExpression(_)
| Expression::SequenceExpression(_)
| Expression::LogicalExpression(_) => self.count_conditional_chain(expr, ctx),
Expression::ChainExpression(_) => self.count_chain_expression(expr, ctx),
Expression::ObjectExpression(_) | Expression::ArrayExpression(_) => self.count_object_domain(expr, ctx),
Expression::TemplateLiteral(_) | Expression::TaggedTemplateExpression(_) => {
self.count_template_domain(expr, ctx)
}
Expression::ArrowFunctionExpression(_)
| Expression::FunctionExpression(_)
| Expression::ClassExpression(_) => self.count_function_domain(expr, ctx),
Expression::StaticMemberExpression(_)
| Expression::ComputedMemberExpression(_)
| Expression::PrivateFieldExpression(_) => self.count_member_domain(expr, ctx),
Expression::ParenthesizedExpression(_) => self.count_parenthesized_expression(expr, ctx),
Expression::ThisExpression(_) => self.count_this_expression(ctx),
Expression::Identifier(_) => self.count_identifier_expression(expr, ctx),
Expression::NumericLiteral(_)
| Expression::StringLiteral(_)
| Expression::BooleanLiteral(_)
| Expression::NullLiteral(_)
| Expression::RegExpLiteral(_) => self.count_literal(expr, ctx),
_ => self.count_default_expression(ctx),
}
}
}
@@ -1,130 +0,0 @@
use super::*;
impl Compiler {
fn count_binary_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::BinaryExpression(bin) = expr else {
return;
};
let checkpoint = ctx.reg_checkpoint();
self.count_expression(&bin.left, ctx);
self.count_expression(&bin.right, ctx);
ctx.projected_pc += 1; // ADD/SUB/MUL/DIV/etc.
if is_side_effect_free(&bin.left) && is_side_effect_free(&bin.right) {
ctx.restore_reg_checkpoint(checkpoint.saturating_add(1));
}
}
fn count_private_in_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::PrivateInExpression(pin) = expr else {
return;
};
self.count_expression(&pin.right, ctx);
ctx.count_private_access();
}
fn count_unary_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::UnaryExpression(un) = expr else {
return;
};
match un.operator {
UnaryOperator::Delete => self.count_delete_expression(&un.argument, ctx),
_ => {
self.count_expression(&un.argument, ctx);
ctx.projected_pc += 1; // NEG/TYPEOF/VOID/NOT
}
}
}
fn count_delete_expression(&self, argument: &Expression, ctx: &mut CompileCtx) {
match argument {
Expression::Identifier(_) => {
// SyntaxError at compile time, no bytecode cost.
}
Expression::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_delete_static();
}
Expression::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.projected_pc += 1; // DELETE_PROP_DYNAMIC
}
Expression::ChainExpression(chain) => {
self.count_delete_chain_expression(&chain.expression, ctx);
}
_ => {}
}
}
fn count_delete_chain_expression(&self, chain: &ChainElement, ctx: &mut CompileCtx) {
match chain {
ChainElement::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
if member.optional {
self.count_optional_guard(ctx);
}
ctx.count_delete_static();
}
ChainElement::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
if member.optional {
self.count_optional_guard(ctx);
}
self.count_expression(&member.expression, ctx);
ctx.projected_pc += 1; // DELETE_PROP_DYNAMIC
}
_ => {}
}
ctx.projected_pc += 1; // JMP over nullish true writer
ctx.projected_pc += 1; // LOAD_CONST true
}
fn count_update_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::UpdateExpression(update) = expr else {
return;
};
match &update.argument {
SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
let name = id.name.as_str();
let is_upvalue = ctx.current_upvalue_captures.iter().any(|u| u.name == name);
let is_captured = ctx.scopes.symbols.lookup_is_captured(name);
if is_upvalue || is_captured {
ctx.alloc_reg(); // val_reg
ctx.count_instr(); // LOAD_UPVALUE or CELL_GET
ctx.count_load_const(); // 1, alloc + instr
ctx.count_instr(); // ADD/SUB
ctx.count_instr(); // STORE_UPVALUE or CELL_SET
} else {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
SimpleAssignmentTarget::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.alloc_reg();
ctx.count_ic_instr_with_ext(); // MEMBER_INC/MEMBER_DEC + 3 ext words
}
SimpleAssignmentTarget::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
_ => {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
}
pub(in crate::counter) fn count_operator(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::BinaryExpression(_) => self.count_binary_expression(expr, ctx),
Expression::PrivateInExpression(_) => self.count_private_in_expression(expr, ctx),
Expression::UnaryExpression(_) => self.count_unary_expression(expr, ctx),
Expression::UpdateExpression(_) => self.count_update_expression(expr, ctx),
_ => {}
}
}
}
@@ -46,7 +46,7 @@ impl Compiler {
} }
} }
pub(in crate::counter) fn count_rest_array(&self, ctx: &mut CompileCtx) { pub(crate) fn count_rest_array(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg(); // rest ctx.alloc_reg(); // rest
ctx.count_instr(); // NEW_ARRAY ctx.count_instr(); // NEW_ARRAY
ctx.count_load_const(); // idx = 0 ctx.count_load_const(); // idx = 0
@@ -61,9 +61,7 @@ impl Compiler {
ctx.count_jump(); // JMP ctx.count_jump(); // JMP
} }
pub(in crate::counter) fn count_array_assignment( pub(crate) fn count_array_assignment(&self, ap: &oxide_parser::ArrayAssignmentTarget, ctx: &mut CompileCtx) {
&self, ap: &oxide_parser::ArrayAssignmentTarget, ctx: &mut CompileCtx,
) {
ctx.count_instr(); // FOR_OF_INIT ctx.count_instr(); // FOR_OF_INIT
for elem in &ap.elements { for elem in &ap.elements {
ctx.alloc_reg(); ctx.alloc_reg();
@@ -86,9 +84,7 @@ impl Compiler {
ctx.count_instr(); // FOR_OF_CLOSE ctx.count_instr(); // FOR_OF_CLOSE
} }
pub(in crate::counter) fn count_object_assignment( pub(crate) fn count_object_assignment(&self, op: &oxide_parser::ObjectAssignmentTarget, ctx: &mut CompileCtx) {
&self, op: &oxide_parser::ObjectAssignmentTarget, ctx: &mut CompileCtx,
) {
for prop in &op.properties { for prop in &op.properties {
match prop { match prop {
oxide_parser::AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(id) => { oxide_parser::AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(id) => {
@@ -118,7 +114,7 @@ impl Compiler {
} }
} }
pub(in crate::counter) fn count_assignment_maybe_default( pub(crate) fn count_assignment_maybe_default(
&self, target: &oxide_parser::AssignmentTargetMaybeDefault, ctx: &mut CompileCtx, &self, target: &oxide_parser::AssignmentTargetMaybeDefault, ctx: &mut CompileCtx,
) { ) {
match target { match target {
@@ -144,9 +140,7 @@ impl Compiler {
} }
} }
pub(in crate::counter) fn count_assign_target( pub(crate) fn count_assign_target(&self, target: &oxide_parser::AssignmentTarget, ctx: &mut CompileCtx) {
&self, target: &oxide_parser::AssignmentTarget, ctx: &mut CompileCtx,
) {
match target { match target {
oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(_) => { oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(_) => {
ctx.alloc_reg(); ctx.alloc_reg();
@@ -1,13 +1,13 @@
use super::super::*; use super::super::*;
impl Compiler { impl Compiler {
pub(in crate::counter) fn count_object_property_read_static(&self, ctx: &mut CompileCtx) { pub(crate) fn count_object_property_read_static(&self, ctx: &mut CompileCtx) {
ctx.count_load_var(); // prop/object temp ctx.count_load_var(); // prop/object temp
ctx.count_load_const(); // key reg ctx.count_load_const(); // key reg
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words
} }
pub(in crate::counter) fn count_object_property_read_key( pub(crate) fn count_object_property_read_key(
&self, key: &oxide_parser::PropertyKey, computed: bool, ctx: &mut CompileCtx, &self, key: &oxide_parser::PropertyKey, computed: bool, ctx: &mut CompileCtx,
) { ) {
if !computed { if !computed {
@@ -38,12 +38,12 @@ impl Compiler {
ctx.count_instr(); // GET_PROP_DYNAMIC ctx.count_instr(); // GET_PROP_DYNAMIC
} }
pub(in crate::counter) fn count_optional_guard(&self, ctx: &mut CompileCtx) { pub(crate) fn count_optional_guard(&self, ctx: &mut CompileCtx) {
ctx.count_load_var(); // dup ctx.count_load_var(); // dup
ctx.count_jump(); // JMP_IF_NULLISH ctx.count_jump(); // JMP_IF_NULLISH
} }
pub(in crate::counter) fn count_static_member_get_preserve_base( pub(crate) fn count_static_member_get_preserve_base(
&self, member: &oxide_parser::StaticMemberExpression, short_chain: bool, ctx: &mut CompileCtx, &self, member: &oxide_parser::StaticMemberExpression, short_chain: bool, ctx: &mut CompileCtx,
) { ) {
self.count_chainable_expression(&member.object, short_chain, ctx); self.count_chainable_expression(&member.object, short_chain, ctx);
@@ -55,7 +55,7 @@ impl Compiler {
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words
} }
pub(in crate::counter) fn count_computed_member_get_preserve_base( pub(crate) fn count_computed_member_get_preserve_base(
&self, member: &oxide_parser::ComputedMemberExpression, short_chain: bool, ctx: &mut CompileCtx, &self, member: &oxide_parser::ComputedMemberExpression, short_chain: bool, ctx: &mut CompileCtx,
) { ) {
self.count_chainable_expression(&member.object, short_chain, ctx); self.count_chainable_expression(&member.object, short_chain, ctx);
@@ -67,7 +67,7 @@ impl Compiler {
ctx.count_instr(); // GET_PROP_DYNAMIC ctx.count_instr(); // GET_PROP_DYNAMIC
} }
pub(in crate::counter) fn count_chain_call( pub(crate) fn count_chain_call(
&self, call: &oxide_parser::CallExpression, short_chain: bool, ctx: &mut CompileCtx, &self, call: &oxide_parser::CallExpression, short_chain: bool, ctx: &mut CompileCtx,
) { ) {
match &call.callee { match &call.callee {
@@ -113,9 +113,7 @@ impl Compiler {
ctx.count_load_var(); // result <- regs[0] ctx.count_load_var(); // result <- regs[0]
} }
pub(in crate::counter) fn count_chainable_expression( pub(crate) fn count_chainable_expression(&self, expr: &Expression, short_chain: bool, ctx: &mut CompileCtx) {
&self, expr: &Expression, short_chain: bool, ctx: &mut CompileCtx,
) {
match expr { match expr {
Expression::StaticMemberExpression(member) => { Expression::StaticMemberExpression(member) => {
self.count_static_member_get_preserve_base(member, short_chain, ctx) self.count_static_member_get_preserve_base(member, short_chain, ctx)
@@ -136,9 +134,7 @@ impl Compiler {
} }
} }
pub(in crate::counter) fn count_chain_element( pub(crate) fn count_chain_element(&self, element: &ChainElement, short_chain: bool, ctx: &mut CompileCtx) {
&self, element: &ChainElement, short_chain: bool, ctx: &mut CompileCtx,
) {
match element { match element {
ChainElement::StaticMemberExpression(member) => { ChainElement::StaticMemberExpression(member) => {
self.count_static_member_get_preserve_base(member, short_chain, ctx) self.count_static_member_get_preserve_base(member, short_chain, ctx)
@@ -158,7 +154,7 @@ impl Compiler {
} }
} }
pub(in crate::counter) fn count_logical_assign_test(&self, op: LogicalOperator, id: u32, ctx: &mut CompileCtx) { pub(crate) fn count_logical_assign_test(&self, op: LogicalOperator, id: u32, ctx: &mut CompileCtx) {
match op { match op {
LogicalOperator::And | LogicalOperator::Or => { LogicalOperator::And | LogicalOperator::Or => {
ctx.projected_pc += 1; ctx.projected_pc += 1;
@@ -1,3 +1,2 @@
mod binding; mod binding;
mod class;
mod member; mod member;
+14 -7
View File
@@ -1,10 +1,17 @@
#[allow(unused_imports)]
use crate::compiler::{
is_int_literal, is_side_effect_free, BinaryOperator, CompileCtx, Compiler, FunctionBodyContext, Label, ParamSpec,
};
#[allow(unused_imports)]
use oxide_bytecode::module::Constant;
#[allow(unused_imports)]
use oxide_bytecode::opcode::{self, OpCode};
#[allow(unused_imports)]
use oxide_parser::{ use oxide_parser::{
AssignmentOperator, ChainElement, ClassElement, Expression, ForStatementInit, LogicalOperator, AssignmentOperator, AssignmentTarget, AssignmentTargetMaybeDefault, AssignmentTargetProperty, BindingPattern,
MethodDefinitionKind, SimpleAssignmentTarget, Statement, UnaryOperator, VariableDeclarationKind, ChainElement, Class, ClassElement, Expression, ForStatementInit, ForStatementLeft, LogicalOperator,
MethodDefinitionKind, ObjectAssignmentTarget, PropertyKey, PropertyKind, SimpleAssignmentTarget, Statement,
UnaryOperator, UpdateOperator, VariableDeclarationKind,
}; };
use crate::compiler::{is_side_effect_free, CompileCtx, Compiler, Label}; pub mod helper;
mod expr;
mod helper;
mod stmt;
@@ -1,51 +0,0 @@
use super::*;
impl Compiler {
fn count_expression_statement(&self, stmt: &oxide_parser::ExpressionStatement<'_>, ctx: &mut CompileCtx) {
self.count_expression(&stmt.expression, ctx);
}
fn count_return_statement(&self, stmt: &oxide_parser::ReturnStatement<'_>, ctx: &mut CompileCtx) {
if let Some(arg) = &stmt.argument {
self.count_expression(arg, ctx);
}
ctx.projected_pc += 1; // RETURN
}
fn count_break_statement(&self, ctx: &mut CompileCtx) {
ctx.projected_pc += 1; // JMP
}
fn count_continue_statement(&self, ctx: &mut CompileCtx) {
ctx.projected_pc += 1; // JMP
}
fn count_labeled_statement(&self, stmt: &oxide_parser::LabeledStatement<'_>, ctx: &mut CompileCtx) {
let body_is_loop = matches!(
stmt.body,
Statement::WhileStatement(_)
| Statement::DoWhileStatement(_)
| Statement::ForStatement(_)
| Statement::ForInStatement(_)
| Statement::ForOfStatement(_)
);
if body_is_loop {
self.count_statement(&stmt.body, ctx);
} else {
let id = ctx.next_label_id();
self.count_statement(&stmt.body, ctx);
ctx.labels.label_map.insert(Label::LabeledEnd(id), ctx.projected_pc);
}
}
pub(in crate::counter) fn count_basic(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::ExpressionStatement(es) => self.count_expression_statement(es, ctx),
Statement::ReturnStatement(ret) => self.count_return_statement(ret, ctx),
Statement::BreakStatement(_) => self.count_break_statement(ctx),
Statement::ContinueStatement(_) => self.count_continue_statement(ctx),
Statement::LabeledStatement(ls) => self.count_labeled_statement(ls, ctx),
_ => {}
}
}
}
@@ -1,15 +0,0 @@
use super::*;
impl Compiler {
fn count_block_statement(&self, block: &oxide_parser::BlockStatement<'_>, ctx: &mut CompileCtx) {
for s in &block.body {
self.count_statement(s, ctx);
}
}
pub(in crate::counter) fn count_block_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
if let Statement::BlockStatement(block) = stmt {
self.count_block_statement(block, ctx);
}
}
}
@@ -1,30 +0,0 @@
use super::*;
impl Compiler {
fn count_if_statement(&self, stmt: &oxide_parser::IfStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let else_label = Label::IfElse(id);
let end_label = Label::IfEnd(id);
self.count_expression(&stmt.test, ctx);
ctx.projected_pc += 1; // JMP_IF_FALSE
self.count_statement(&stmt.consequent, ctx);
ctx.alloc_reg(); // result register
ctx.projected_pc += 1; // LOAD_VAR result <- consequent
if stmt.alternate.is_some() {
ctx.projected_pc += 1; // JMP (skip else)
}
ctx.labels.label_map.insert(else_label, ctx.projected_pc);
if let Some(alt_stmt) = &stmt.alternate {
self.count_statement(alt_stmt, ctx);
ctx.projected_pc += 1; // LOAD_VAR result <- alternate
}
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
pub(in crate::counter) fn count_control_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
if let Statement::IfStatement(ifs) = stmt {
self.count_if_statement(ifs, ctx);
}
}
}
@@ -1,34 +0,0 @@
use super::*;
mod basic;
mod block;
mod control;
mod declaration;
mod exception;
mod iteration;
mod switch;
impl Compiler {
pub(crate) fn count_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::ExpressionStatement(_)
| Statement::ReturnStatement(_)
| Statement::BreakStatement(_)
| Statement::ContinueStatement(_)
| Statement::LabeledStatement(_) => self.count_basic(stmt, ctx),
Statement::BlockStatement(_) => self.count_block_domain(stmt, ctx),
Statement::VariableDeclaration(_) | Statement::FunctionDeclaration(_) | Statement::ClassDeclaration(_) => {
self.count_declaration_domain(stmt, ctx)
}
Statement::IfStatement(_) => self.count_control_domain(stmt, ctx),
Statement::WhileStatement(_)
| Statement::DoWhileStatement(_)
| Statement::ForStatement(_)
| Statement::ForInStatement(_)
| Statement::ForOfStatement(_) => self.count_iteration_domain(stmt, ctx),
Statement::SwitchStatement(_) => self.count_switch_domain(stmt, ctx),
Statement::ThrowStatement(_) | Statement::TryStatement(_) => self.count_exception_domain(stmt, ctx),
_ => {}
}
}
}
@@ -1,45 +0,0 @@
use super::*;
impl Compiler {
fn count_switch_statement(&self, stmt: &oxide_parser::SwitchStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let end_label = Label::SwitchEnd(id);
ctx.push_switch(end_label);
self.count_expression(&stmt.discriminant, ctx);
let compare_reg_checkpoint = ctx.reg_checkpoint();
let cases = &stmt.cases;
for case in cases.iter() {
if let Some(test) = &case.test {
self.count_expression(test, ctx);
ctx.projected_pc += 1; // EQ
ctx.alloc_reg(); // eq result
ctx.projected_pc += 1; // JMP_IF_TRUE
ctx.restore_reg_checkpoint(compare_reg_checkpoint);
}
}
let has_default = cases.iter().any(|c| c.test.is_none());
if !has_default {
ctx.projected_pc += 1; // JMP to SwitchEnd (no match)
}
for (case_idx, case) in cases.iter().enumerate() {
let case_label = Label::SwitchCase(id, case_idx as u32);
ctx.labels.label_map.insert(case_label, ctx.projected_pc);
for s in &case.consequent {
self.count_statement(s, ctx);
}
}
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
ctx.pop_switch();
}
pub(in crate::counter) fn count_switch_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
if let Statement::SwitchStatement(sw) = stmt {
self.count_switch_statement(sw, ctx);
}
}
}
@@ -1,10 +0,0 @@
use super::*;
mod assignment;
mod call;
mod function;
mod literal;
mod member;
mod object;
mod operator;
mod template;
+12 -70
View File
@@ -1,3 +1,4 @@
#![allow(unused_imports)]
use crate::compiler::Label; use crate::compiler::Label;
use oxide_bytecode::module::Constant; use oxide_bytecode::module::Constant;
use oxide_bytecode::opcode::{self, OpCode}; use oxide_bytecode::opcode::{self, OpCode};
@@ -12,9 +13,6 @@ use crate::compiler::{
is_int_literal, is_side_effect_free, BinaryOperator, CompileCtx, Compiler, FunctionBodyContext, ParamSpec, is_int_literal, is_side_effect_free, BinaryOperator, CompileCtx, Compiler, FunctionBodyContext, ParamSpec,
}; };
mod expr;
mod stmt;
impl Compiler { impl Compiler {
fn emit_optional_guard(&self, reg: u8, short_label: Label, ctx: &mut CompileCtx) -> Result<(), String> { fn emit_optional_guard(&self, reg: u8, short_label: Label, ctx: &mut CompileCtx) -> Result<(), String> {
let short_pos = ctx.resolve_label(short_label)?; let short_pos = ctx.resolve_label(short_label)?;
@@ -157,7 +155,7 @@ impl Compiler {
} }
} }
fn emit_chain_element( pub(crate) fn emit_chain_element(
&self, element: &ChainElement, short_label: Option<Label>, ctx: &mut CompileCtx, &self, element: &ChainElement, short_label: Option<Label>, ctx: &mut CompileCtx,
) -> Result<u8, String> { ) -> Result<u8, String> {
match element { match element {
@@ -186,7 +184,7 @@ impl Compiler {
} }
} }
fn emit_logical_assign_test( pub(crate) fn emit_logical_assign_test(
&self, op: LogicalOperator, test_reg: u8, store_label: Label, end_label: Label, ctx: &mut CompileCtx, &self, op: LogicalOperator, test_reg: u8, store_label: Label, end_label: Label, ctx: &mut CompileCtx,
) -> Result<(), String> { ) -> Result<(), String> {
match op { match op {
@@ -224,7 +222,7 @@ impl Compiler {
.ok_or_else(|| format!("private name #{name} is not defined")) .ok_or_else(|| format!("private name #{name} is not defined"))
} }
fn emit_private_id_reg(&self, name: &str, ctx: &mut CompileCtx) -> Result<u8, String> { 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 id = self.private_name_id(name, ctx)?;
let idx = ctx.add_constant(Constant::Int(id as i32)); let idx = ctx.add_constant(Constant::Int(id as i32));
let reg = ctx.alloc_reg(); let reg = ctx.alloc_reg();
@@ -324,7 +322,7 @@ impl Compiler {
ctx.projected_pc += 1; ctx.projected_pc += 1;
} }
fn static_property_name(&self, key: &PropertyKey) -> Result<String, String> { pub(crate) fn static_property_name(&self, key: &PropertyKey) -> Result<String, String> {
match key { match key {
PropertyKey::StaticIdentifier(ident) => Ok(ident.name.as_str().to_string()), PropertyKey::StaticIdentifier(ident) => Ok(ident.name.as_str().to_string()),
PropertyKey::Identifier(ident) => Ok(ident.name.as_str().to_string()), PropertyKey::Identifier(ident) => Ok(ident.name.as_str().to_string()),
@@ -375,7 +373,9 @@ impl Compiler {
Ok(()) Ok(())
} }
fn emit_assign_target(&self, target: &AssignmentTarget, src_reg: u8, ctx: &mut CompileCtx) -> Result<(), String> { pub(crate) fn emit_assign_target(
&self, target: &AssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
) -> Result<(), String> {
match target { match target {
AssignmentTarget::AssignmentTargetIdentifier(id) => { AssignmentTarget::AssignmentTargetIdentifier(id) => {
let name = id.name.as_str(); let name = id.name.as_str();
@@ -566,7 +566,7 @@ impl Compiler {
} }
} }
fn emit_array_assignment( pub(crate) fn emit_array_assignment(
&self, ap: &oxide_parser::ArrayAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx, &self, ap: &oxide_parser::ArrayAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
) -> Result<(), String> { ) -> Result<(), String> {
ctx.emit(opcode::encode(OpCode::FOR_OF_INIT, 0, src_reg, 0)); ctx.emit(opcode::encode(OpCode::FOR_OF_INIT, 0, src_reg, 0));
@@ -587,7 +587,7 @@ impl Compiler {
Ok(()) Ok(())
} }
fn emit_object_assignment( pub(crate) fn emit_object_assignment(
&self, op: &ObjectAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx, &self, op: &ObjectAssignmentTarget, src_reg: u8, ctx: &mut CompileCtx,
) -> Result<(), String> { ) -> Result<(), String> {
let mut excluded = Vec::new(); let mut excluded = Vec::new();
@@ -640,7 +640,7 @@ impl Compiler {
} }
} }
fn emit_class(&self, class: &Class, ctx: &mut CompileCtx) -> Result<u8, String> { pub(crate) fn emit_class(&self, class: &Class, ctx: &mut CompileCtx) -> Result<u8, String> {
let mut constructor_method = None; let mut constructor_method = None;
let mut instance_fields = Vec::new(); let mut instance_fields = Vec::new();
let mut private_names = Vec::<(String, u32)>::new(); let mut private_names = Vec::<(String, u32)>::new();
@@ -931,7 +931,7 @@ impl Compiler {
Ok(ctor_reg) Ok(ctor_reg)
} }
fn emit_undefined(&self, ctx: &mut CompileCtx) -> u8 { pub(crate) fn emit_undefined(&self, ctx: &mut CompileCtx) -> u8 {
let idx = ctx.add_constant(Constant::Undefined); let idx = ctx.add_constant(Constant::Undefined);
let reg = ctx.alloc_reg(); let reg = ctx.alloc_reg();
ctx.emit_load_const(reg, idx); ctx.emit_load_const(reg, idx);
@@ -966,62 +966,4 @@ impl Compiler {
ctx.emit(opcode::encode(OpCode::SET_HOME_OBJECT, method_reg, home_reg, 0)); ctx.emit(opcode::encode(OpCode::SET_HOME_OBJECT, method_reg, home_reg, 0));
Ok(method_reg) Ok(method_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),
}
}
} }
@@ -1,112 +0,0 @@
use super::*;
impl Compiler {
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)?))
}
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.emit(opcode::encode(OpCode::RETURN, r, 0, 0));
}
None => {
ctx.emit(opcode::encode(OpCode::RETURN, 0, 0, 0));
}
}
Ok(None)
}
pub(in crate::emitter) 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
};
let break_pos = ctx.resolve_label(break_label)?;
let offset = (break_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
Ok(None)
}
pub(in crate::emitter) 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
};
let continue_pos = ctx.resolve_label(continue_label)?;
let offset = (continue_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
Ok(None)
}
pub(in crate::emitter) 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) {
// Bind the label to the loop's own continue/break targets (the loop
// drains the queue and pops the scope after its body).
ctx.queue_loop_label(name)?;
self.emit_statement(&stmt.body, ctx)?;
} else {
// Non-loop labeled statement: only `break label` is valid; it targets
// the LabeledEnd placed (by the count pass) right after the body.
let id = ctx.next_label_id();
ctx.push_label_scope(name, Label::LabeledEnd(id), None)?;
self.emit_statement(&stmt.body, ctx)?;
ctx.pop_label_scope();
}
Ok(None)
}
fn is_iteration_statement(stmt: &Statement) -> bool {
matches!(
stmt,
Statement::WhileStatement(_)
| Statement::DoWhileStatement(_)
| Statement::ForStatement(_)
| Statement::ForInStatement(_)
| Statement::ForOfStatement(_)
)
}
pub(in crate::emitter) fn emit_basic_domain(
&self, stmt: &Statement, ctx: &mut CompileCtx,
) -> Result<Option<u8>, String> {
match stmt {
Statement::ExpressionStatement(_) => self.emit_expression_statement(stmt, ctx),
Statement::ReturnStatement(_) => self.emit_return_statement(stmt, ctx),
Statement::EmptyStatement(_) => Ok(None),
_ => Ok(None),
}
}
}
@@ -1,9 +0,0 @@
use super::*;
mod basic;
mod block;
mod control;
mod declaration;
mod exception;
mod iteration;
mod switch;
+1
View File
@@ -6,4 +6,5 @@ pub mod counter;
pub mod emit_ctx; pub mod emit_ctx;
pub mod emitter; pub mod emitter;
pub mod hash; pub mod hash;
pub mod passes;
pub mod symbol_table; pub mod symbol_table;
@@ -1,7 +1,7 @@
use super::super::*; use super::*;
impl Compiler { impl Compiler {
pub(in crate::counter) fn count_class(&self, class: &oxide_parser::Class, ctx: &mut CompileCtx) { pub(crate) fn count_class(&self, class: &oxide_parser::Class, ctx: &mut CompileCtx) {
ctx.alloc_reg(); // ctor_reg ctx.alloc_reg(); // ctor_reg
ctx.alloc_reg(); // proto_reg ctx.alloc_reg(); // proto_reg
if let Some(super_class) = &class.super_class { if let Some(super_class) = &class.super_class {
@@ -0,0 +1,2 @@
pub use super::*;
pub mod core;
@@ -1,7 +1,122 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
pub(in crate::emitter) fn emit_assignment_expression( fn count_assignment_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::AssignmentExpression(assign) = expr else {
return;
};
if let oxide_parser::AssignmentTarget::StaticMemberExpression(member) = &assign.left {
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_static_member_logical_assignment(member, logical_op, &assign.right, ctx);
return;
}
self.count_expression(&member.object, ctx);
self.count_expression(&assign.right, ctx);
// Both plain (IC_SET_PROP) and compound (COMPOUND_MEMBER_*) emit one opcode + 3 ext
// words after the key load — no extra instruction for the compound case.
ctx.count_load_const(); // key
ctx.count_ic_set_with_ext(); // IC_SET_PROP or COMPOUND_MEMBER_* + 3 ext words
} else if let oxide_parser::AssignmentTarget::ComputedMemberExpression(member) = &assign.left {
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_computed_member_logical_assignment(member, logical_op, &assign.right, ctx);
return;
}
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
self.count_expression(&assign.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // SET_PROP_DYNAMIC
} else if let oxide_parser::AssignmentTarget::PrivateFieldExpression(member) = &assign.left {
self.count_expression(&member.object, ctx);
self.count_expression(&assign.right, ctx);
ctx.count_load_const(); // private id
ctx.count_instr(); // SET_PRIVATE
} else if let oxide_parser::AssignmentTarget::AssignmentTargetIdentifier(ati) = &assign.left {
let name = ati.name.as_str();
// Check if target is an upvalue or captured cell
let is_upvalue = ctx.current_upvalue_captures.iter().any(|u| u.name == name);
let is_captured = ctx.scopes.symbols.lookup_is_captured(name);
if let Some(logical_op) = assign.operator.to_logical_operator() {
self.count_identifier_logical_assignment(logical_op, &assign.right, ctx);
} else {
self.count_expression(&assign.right, ctx);
if assign.operator != AssignmentOperator::Assign {
ctx.projected_pc += 1; // COMPOUND_* on var
} else if is_upvalue {
ctx.count_instr(); // STORE_UPVALUE
} else if is_captured {
ctx.count_instr(); // CELL_SET
} else {
ctx.alloc_reg();
ctx.projected_pc += 1; // STORE_VAR
}
}
} else if let oxide_parser::AssignmentTarget::ArrayAssignmentTarget(ap) = &assign.left {
self.count_expression(&assign.right, ctx);
self.count_array_assignment(ap, ctx);
} else if let oxide_parser::AssignmentTarget::ObjectAssignmentTarget(op) = &assign.left {
self.count_expression(&assign.right, ctx);
self.count_object_assignment(op, ctx);
} else {
self.count_expression(&assign.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
fn count_static_member_logical_assignment(
&self, member: &oxide_parser::StaticMemberExpression<'_>, logical_op: LogicalOperator, right: &Expression,
ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.count_load_var(); // current value copy
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.count_ic_set_with_ext(); // IC_SET_PROP + 3 ext
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
fn count_computed_member_logical_assignment(
&self, member: &oxide_parser::ComputedMemberExpression<'_>, logical_op: LogicalOperator, right: &Expression,
ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // GET_PROP_DYNAMIC
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.projected_pc += 1; // SET_PROP_DYNAMIC
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
fn count_identifier_logical_assignment(
&self, logical_op: LogicalOperator, right: &Expression, ctx: &mut CompileCtx,
) {
let id = ctx.next_label_id();
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR result <- current var
self.count_logical_assign_test(logical_op, id, ctx);
self.count_expression(right, ctx);
ctx.projected_pc += 1; // STORE_VAR
ctx.projected_pc += 1; // LOAD_VAR result <- rhs
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
pub(crate) fn count_assignment(&self, expr: &Expression, ctx: &mut CompileCtx) {
self.count_assignment_expression(expr, ctx);
}
}
impl Compiler {
pub(crate) fn emit_assignment_expression(
&self, assign: &oxide_parser::AssignmentExpression, ctx: &mut CompileCtx, &self, assign: &oxide_parser::AssignmentExpression, ctx: &mut CompileCtx,
) -> Result<u8, String> { ) -> Result<u8, String> {
if let oxide_parser::AssignmentTarget::StaticMemberExpression(member) = &assign.left { if let oxide_parser::AssignmentTarget::StaticMemberExpression(member) = &assign.left {
@@ -1,6 +1,70 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
fn count_call_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::CallExpression(call) = expr else {
return;
};
if matches!(&call.callee, Expression::Super(_)) {
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.alloc_reg();
ctx.count_call_instr_with_arg_ext();
if let Some(words) = ctx.after_super_count_words.take() {
ctx.projected_pc += words;
}
return;
}
match &call.callee {
Expression::PrivateFieldExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_private_access();
}
Expression::StaticMemberExpression(member) => {
if matches!(&member.object, Expression::Super(_)) {
ctx.count_load_var();
ctx.count_load_const();
ctx.alloc_reg();
ctx.count_instr();
} else {
self.count_expression(&member.object, ctx);
ctx.count_load_const();
ctx.count_load_var();
ctx.count_ic_instr_with_ext();
}
}
_ => {
self.count_expression(&call.callee, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.count_call_instr_with_arg_ext();
ctx.count_load_var();
}
fn count_new_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::NewExpression(ne) = expr else {
return;
};
self.count_expression(&ne.callee, ctx);
for arg in &ne.arguments {
if let Some(expr) = arg.as_expression() {
self.count_expression(expr, ctx);
}
}
ctx.alloc_reg();
ctx.count_instr_with_ext(1);
}
fn emit_call_expression(&self, call: &oxide_parser::CallExpression, ctx: &mut CompileCtx) -> Result<u8, String> { fn emit_call_expression(&self, call: &oxide_parser::CallExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
if matches!(&call.callee, Expression::Super(_)) { if matches!(&call.callee, Expression::Super(_)) {
if !ctx.in_derived_constructor { if !ctx.in_derived_constructor {
@@ -86,14 +150,20 @@ impl Compiler {
}; };
ctx.emit(opcode::encode(op, callee_reg, this_reg, first_arg_reg)); ctx.emit(opcode::encode(op, callee_reg, this_reg, first_arg_reg));
ctx.emit(arg_regs.len() as u32); ctx.emit(arg_regs.len() as u32);
// Copy result from regs[0] into a dedicated register so multiple
// call expressions don't overwrite each other.
let result_reg = ctx.alloc_reg(); let result_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, 0, 0)); ctx.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, 0, 0));
Ok(result_reg) Ok(result_reg)
} }
pub(in crate::emitter) fn emit_call_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> { pub(crate) fn count_call_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::CallExpression(_) => self.count_call_expression(expr, ctx),
Expression::NewExpression(_) => self.count_new_expression(expr, ctx),
_ => {}
}
}
pub(crate) fn emit_call_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
match expr { match expr {
Expression::CallExpression(call) => self.emit_call_expression(call, ctx), Expression::CallExpression(call) => self.emit_call_expression(call, ctx),
_ => self.emit_unsupported_expression(expr, ctx), _ => self.emit_unsupported_expression(expr, ctx),
@@ -1,5 +1,33 @@
use super::*; use super::*;
impl Compiler {
fn count_arrow_function_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST
}
fn count_function_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST
}
fn count_class_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ClassExpression(class) = expr else {
return;
};
self.count_class(class, ctx);
}
pub(crate) fn count_function_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::ArrowFunctionExpression(_) => self.count_arrow_function_expression(ctx),
Expression::FunctionExpression(_) => self.count_function_expression(ctx),
Expression::ClassExpression(_) => self.count_class_expression(expr, ctx),
_ => {}
}
}
}
impl Compiler { impl Compiler {
fn emit_arrow_function_expression( fn emit_arrow_function_expression(
&self, arrow: &oxide_parser::ArrowFunctionExpression, ctx: &mut CompileCtx, &self, arrow: &oxide_parser::ArrowFunctionExpression, ctx: &mut CompileCtx,
@@ -93,9 +121,7 @@ impl Compiler {
Ok(r) Ok(r)
} }
pub(in crate::emitter) fn emit_function_domain( pub(crate) fn emit_function_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
&self, expr: &Expression, ctx: &mut CompileCtx,
) -> Result<u8, String> {
match expr { match expr {
Expression::ArrowFunctionExpression(arrow) => self.emit_arrow_function_expression(arrow, ctx), Expression::ArrowFunctionExpression(arrow) => self.emit_arrow_function_expression(arrow, ctx),
Expression::FunctionExpression(fe) => self.emit_function_expression(fe, ctx), Expression::FunctionExpression(fe) => self.emit_function_expression(fe, ctx),
@@ -0,0 +1,67 @@
use super::*;
impl Compiler {
pub(crate) fn count_identifier_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::Identifier(ident) = expr else {
return;
};
let name = ident.name.as_str();
for up in &ctx.current_upvalue_captures {
if up.name == name {
ctx.alloc_reg();
ctx.count_instr();
return;
}
}
if ctx.scopes.symbols.lookup_is_captured(name) {
ctx.alloc_reg();
ctx.count_instr();
return;
}
if CompileCtx::is_known_builtin(name) {
let _ = ctx.lookup_or_builtin(name);
}
ctx.alloc_reg();
ctx.projected_pc += 1;
}
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.emit(opcode::encode(OpCode::LOAD_UPVALUE, r, idx, 0));
return Ok(r);
}
}
if ctx.scopes.symbols.lookup_is_captured(name) {
let cell_idx = ctx
.scopes
.cell_registry
.iter()
.find(|(n, _)| n == name)
.map(|(_, idx)| *idx)
.unwrap_or(0);
let r = ctx.alloc_reg();
if let Some((binding, _)) = ctx.scopes.symbols.lookup_any_binding(name) {
ctx.emit(opcode::encode(OpCode::CELL_GET, r, binding.reg, cell_idx));
} else {
ctx.emit(opcode::encode(OpCode::CELL_GET, r, 0, cell_idx));
}
return Ok(r);
}
let var_reg = ctx.lookup_or_builtin(name)?;
let r = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::LOAD_VAR, r, var_reg, 0));
Ok(r)
}
}
@@ -1,10 +1,28 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
/// Domain entry point: emit any literal expression. The central pub(crate) fn count_literal(&self, expr: &Expression, ctx: &mut CompileCtx) {
/// `emit_expression` match delegates all literal variants here in one arm; match expr {
/// adding a new literal kind only touches this file plus that one arm. Expression::RegExpLiteral(_) => self.count_regexp_literal(ctx),
pub(in crate::emitter) fn emit_literal(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> { _ => self.count_default_expression(ctx),
}
}
fn count_regexp_literal(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1;
ctx.alloc_reg();
ctx.projected_pc += 1;
ctx.alloc_reg();
ctx.projected_pc += 1;
}
pub(crate) fn count_default_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
pub(crate) fn emit_literal(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
match expr { match expr {
Expression::NumericLiteral(n) => self.emit_numeric_literal_expression(n, ctx), Expression::NumericLiteral(n) => self.emit_numeric_literal_expression(n, ctx),
Expression::StringLiteral(s) => self.emit_string_literal_expression(s, ctx), Expression::StringLiteral(s) => self.emit_string_literal_expression(s, ctx),
@@ -53,58 +71,6 @@ impl Compiler {
Ok(r) Ok(r)
} }
pub(in crate::emitter) fn emit_identifier_expression(
&self, ident: &oxide_parser::IdentifierReference, ctx: &mut CompileCtx,
) -> Result<u8, String> {
let name = ident.name.as_str();
// Check if this is an upvalue reference (nested closure)
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.emit(opcode::encode(OpCode::LOAD_UPVALUE, r, idx, 0));
return Ok(r);
}
}
// Check if the owner's binding is captured (cell access)
if ctx.scopes.symbols.lookup_is_captured(name) {
let cell_idx = ctx
.scopes
.cell_registry
.iter()
.find(|(n, _)| n == name)
.map(|(_, idx)| *idx)
.unwrap_or(0);
let r = ctx.alloc_reg();
if let Some((binding, _)) = ctx.scopes.symbols.lookup_any_binding(name) {
ctx.emit(opcode::encode(OpCode::CELL_GET, r, binding.reg, cell_idx));
} else {
ctx.emit(opcode::encode(OpCode::CELL_GET, r, 0, cell_idx));
}
return Ok(r);
}
let var_reg = ctx.lookup_or_builtin(name)?;
let r = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::LOAD_VAR, r, var_reg, 0));
Ok(r)
}
pub(in crate::emitter) fn emit_parenthesized_expression(
&self, p: &oxide_parser::ParenthesizedExpression, ctx: &mut CompileCtx,
) -> Result<u8, String> {
self.emit_expression(&p.expression, ctx)
}
pub(in crate::emitter) 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);
ctx.emit(opcode::encode(OpCode::LOAD_VAR, r, src, 0));
Ok(r)
}
fn emit_reg_exp_literal_expression( fn emit_reg_exp_literal_expression(
&self, lit: &oxide_parser::RegExpLiteral, ctx: &mut CompileCtx, &self, lit: &oxide_parser::RegExpLiteral, ctx: &mut CompileCtx,
) -> Result<u8, String> { ) -> Result<u8, String> {
@@ -130,24 +96,4 @@ impl Compiler {
Err(format!("unsupported regexp literal: {:?}", lit)) Err(format!("unsupported regexp literal: {:?}", lit))
} }
} }
pub(in crate::emitter) fn emit_sequence_expression(
&self, seq: &oxide_parser::SequenceExpression, ctx: &mut CompileCtx,
) -> Result<u8, String> {
// Comma operator: evaluate each expression in order, value is the last.
// Emits exactly one expression per element (no extra instruction), so the
// projected-PC count in count_sequence_expression stays aligned.
let mut last = 0u8;
for e in &seq.expressions {
last = self.emit_expression(e, ctx)?;
}
Ok(last)
}
pub(in crate::emitter) fn emit_unsupported_expression(
&self, expr: &Expression, ctx: &mut CompileCtx,
) -> Result<u8, String> {
let _ = ctx;
Err(format!("unsupported expression type: {:?}", expr))
}
} }
@@ -1,5 +1,64 @@
use super::*; use super::*;
impl Compiler {
fn count_static_member_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::StaticMemberExpression(member) = expr else {
return;
};
if matches!(&member.object, Expression::Super(_)) {
ctx.count_load_const(); // key
ctx.count_load_var(); // this
ctx.alloc_reg(); // result
ctx.count_instr(); // SUPER_GET_PROP
return;
}
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.count_ic_instr_with_ext(); // IC_GET_PROP + 3 ext words
}
fn count_computed_member_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ComputedMemberExpression(member) = expr else {
return;
};
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // GET_PROP_DYNAMIC
}
fn count_private_field_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::PrivateFieldExpression(member) = expr else {
return;
};
self.count_expression(&member.object, ctx);
ctx.count_private_access();
}
pub(crate) fn count_chain_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ChainExpression(chain) = expr else {
return;
};
let id = ctx.next_label_id();
self.count_chain_element(&chain.expression, true, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_VAR result <- chain value
ctx.projected_pc += 1; // JMP over short-circuit writer
ctx.labels.label_map.insert(Label::TernaryElse(id), ctx.projected_pc);
ctx.projected_pc += 1; // LOAD_CONST undefined
ctx.labels.label_map.insert(Label::TernaryEnd(id), ctx.projected_pc);
}
pub(crate) fn count_member_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::StaticMemberExpression(_) => self.count_static_member_expression(expr, ctx),
Expression::ComputedMemberExpression(_) => self.count_computed_member_expression(expr, ctx),
Expression::PrivateFieldExpression(_) => self.count_private_field_expression(expr, ctx),
_ => {}
}
}
}
impl Compiler { impl Compiler {
fn emit_static_member_expression( fn emit_static_member_expression(
&self, member: &oxide_parser::StaticMemberExpression, ctx: &mut CompileCtx, &self, member: &oxide_parser::StaticMemberExpression, ctx: &mut CompileCtx,
@@ -71,7 +130,7 @@ impl Compiler {
Ok(result_reg) Ok(result_reg)
} }
pub(in crate::emitter) fn emit_member_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> { pub(crate) fn emit_member_domain(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
match expr { match expr {
Expression::StaticMemberExpression(member) => self.emit_static_member_expression(member, ctx), Expression::StaticMemberExpression(member) => self.emit_static_member_expression(member, ctx),
Expression::ComputedMemberExpression(member) => self.emit_computed_member_expression(member, ctx), Expression::ComputedMemberExpression(member) => self.emit_computed_member_expression(member, ctx),
@@ -0,0 +1,30 @@
pub use super::*;
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 Compiler {
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,52 @@
use super::*;
impl Compiler {
fn count_object_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ObjectExpression(obj) = expr else {
return;
};
ctx.alloc_reg();
ctx.projected_pc += 1; // NEW_OBJECT
let prop_checkpoint = ctx.reg_checkpoint();
for prop in &obj.properties {
if let oxide_parser::ObjectPropertyKind::ObjectProperty(p) = prop {
if matches!(p.kind, oxide_parser::PropertyKind::Get | oxide_parser::PropertyKind::Set) {
self.count_expression(&p.value, ctx);
ctx.count_load_const(); // undefined getter/setter placeholder
ctx.count_define_accessor(); // DEFINE_ACCESSOR + ext
} else {
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST key
self.count_expression(&p.value, ctx);
ctx.projected_pc += 1; // SET_PROP
}
ctx.restore_reg_checkpoint(prop_checkpoint);
}
}
}
fn count_array_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ArrayExpression(arr) = expr else {
return;
};
ctx.alloc_reg();
ctx.projected_pc += 1; // NEW_ARRAY
let elem_checkpoint = ctx.reg_checkpoint();
for elem in &arr.elements {
if let Some(e) = elem.as_expression() {
self.count_expression(e, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // LOAD_CONST index
ctx.projected_pc += 1; // SET_ELEM
ctx.restore_reg_checkpoint(elem_checkpoint);
}
}
}
pub(crate) fn count_object_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::ObjectExpression(_) => self.count_object_expression(expr, ctx),
Expression::ArrayExpression(_) => self.count_array_expression(expr, ctx),
_ => {}
}
}
}
@@ -0,0 +1,79 @@
use super::*;
impl Compiler {
fn emit_object_expression(&self, obj: &oxide_parser::ObjectExpression, ctx: &mut CompileCtx) -> Result<u8, String> {
let obj_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::NEW_OBJECT, obj_reg, 0, 0));
let prop_checkpoint = ctx.reg_checkpoint();
for prop in &obj.properties {
let oxide_parser::ObjectPropertyKind::ObjectProperty(p) = prop else {
return Err("spread properties not yet supported".into());
};
let prop_name = match &p.key {
oxide_parser::PropertyKey::StaticIdentifier(ident) => ident.name.as_str().to_string(),
oxide_parser::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.sub_modules.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.emit(opcode::encode(OpCode::DEFINE_ACCESSOR, obj_reg, get_reg, set_reg));
ctx.emit(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.emit_load_const(key_reg, idx);
let val_reg = self.emit_expression(&p.value, ctx)?;
// Name inference: if property value is an arrow function,
// set the compiled sub_module's function_name to the property key.
if matches!(&p.value, Expression::ArrowFunctionExpression(_)) {
if let Some(sub_mod) = ctx.sub_modules.last_mut() {
sub_mod.function_name = Some(prop_name.to_string());
}
}
ctx.emit(opcode::encode(OpCode::SET_PROP, obj_reg, val_reg, key_reg));
ctx.restore_reg_checkpoint(prop_checkpoint);
}
}
}
Ok(obj_reg)
}
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.emit(opcode::encode(OpCode::NEW_ARRAY, arr_reg, (n & 0xFF) as u8, ((n >> 8) & 0xFF) as u8));
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.emit_load_const(idx_reg, idx);
ctx.emit(opcode::encode(OpCode::SET_ELEM, arr_reg, idx_reg, val_reg));
ctx.restore_reg_checkpoint(elem_checkpoint);
}
Ok(arr_reg)
}
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,3 @@
pub use super::*;
pub mod count;
pub mod emit;
@@ -1,5 +1,210 @@
use super::*; use super::*;
impl Compiler {
fn count_binary_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::BinaryExpression(bin) = expr else {
return;
};
let checkpoint = ctx.reg_checkpoint();
self.count_expression(&bin.left, ctx);
self.count_expression(&bin.right, ctx);
ctx.projected_pc += 1; // ADD/SUB/MUL/DIV/etc.
if is_side_effect_free(&bin.left) && is_side_effect_free(&bin.right) {
ctx.restore_reg_checkpoint(checkpoint.saturating_add(1));
}
}
fn count_private_in_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::PrivateInExpression(pin) = expr else {
return;
};
self.count_expression(&pin.right, ctx);
ctx.count_private_access();
}
fn count_unary_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::UnaryExpression(un) = expr else {
return;
};
match un.operator {
UnaryOperator::Delete => self.count_delete_expression(&un.argument, ctx),
_ => {
self.count_expression(&un.argument, ctx);
ctx.projected_pc += 1; // NEG/TYPEOF/VOID/NOT
}
}
}
fn count_delete_expression(&self, argument: &Expression, ctx: &mut CompileCtx) {
match argument {
Expression::Identifier(_) => {
// SyntaxError at compile time, no bytecode cost.
}
Expression::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_delete_static();
}
Expression::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.projected_pc += 1; // DELETE_PROP_DYNAMIC
}
Expression::ChainExpression(chain) => {
self.count_delete_chain_expression(&chain.expression, ctx);
}
_ => {}
}
}
fn count_delete_chain_expression(&self, chain: &ChainElement, ctx: &mut CompileCtx) {
match chain {
ChainElement::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
if member.optional {
self.count_optional_guard(ctx);
}
ctx.count_delete_static();
}
ChainElement::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
if member.optional {
self.count_optional_guard(ctx);
}
self.count_expression(&member.expression, ctx);
ctx.projected_pc += 1; // DELETE_PROP_DYNAMIC
}
_ => {}
}
ctx.projected_pc += 1; // JMP over nullish true writer
ctx.projected_pc += 1; // LOAD_CONST true
}
fn count_update_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::UpdateExpression(update) = expr else {
return;
};
match &update.argument {
SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
let name = id.name.as_str();
let is_upvalue = ctx.current_upvalue_captures.iter().any(|u| u.name == name);
let is_captured = ctx.scopes.symbols.lookup_is_captured(name);
if is_upvalue || is_captured {
ctx.alloc_reg(); // val_reg
ctx.count_instr(); // LOAD_UPVALUE or CELL_GET
ctx.count_load_const(); // 1, alloc + instr
ctx.count_instr(); // ADD/SUB
ctx.count_instr(); // STORE_UPVALUE or CELL_SET
} else {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
SimpleAssignmentTarget::StaticMemberExpression(member) => {
self.count_expression(&member.object, ctx);
ctx.count_load_const(); // key
ctx.alloc_reg();
ctx.count_ic_instr_with_ext(); // MEMBER_INC/MEMBER_DEC + 3 ext words
}
SimpleAssignmentTarget::ComputedMemberExpression(member) => {
self.count_expression(&member.object, ctx);
self.count_expression(&member.expression, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
}
_ => {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
}
}
pub(crate) fn count_operator(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::BinaryExpression(_) => self.count_binary_expression(expr, ctx),
Expression::PrivateInExpression(_) => self.count_private_in_expression(expr, ctx),
Expression::UnaryExpression(_) => self.count_unary_expression(expr, ctx),
Expression::UpdateExpression(_) => self.count_update_expression(expr, ctx),
_ => {}
}
}
fn count_conditional_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::ConditionalExpression(cond) = expr else {
return;
};
let id = ctx.next_label_id();
let else_label = Label::TernaryElse(id);
let end_label = Label::TernaryEnd(id);
self.count_expression(&cond.test, ctx);
ctx.projected_pc += 1; // JMP_IF_FALSE
self.count_expression(&cond.consequent, ctx);
ctx.alloc_reg(); // result register
ctx.projected_pc += 1; // LOAD_VAR result <- consequent
ctx.projected_pc += 1; // JMP to end
ctx.labels.label_map.insert(else_label, ctx.projected_pc);
self.count_expression(&cond.alternate, ctx);
ctx.projected_pc += 1; // LOAD_VAR result <- alternate
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn count_sequence_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::SequenceExpression(seq) = expr else {
return;
};
for e in &seq.expressions {
self.count_expression(e, ctx);
}
}
fn count_logical_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::LogicalExpression(log) = expr else {
return;
};
self.count_expression(&log.left, ctx);
let is_simple = is_side_effect_free(&log.left) && is_side_effect_free(&log.right);
if is_simple {
self.count_expression(&log.right, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1; // AND/OR
} else if matches!(log.operator, LogicalOperator::Coalesce) {
// Mirror emit_logical_expression's Coalesce path: it patches raw bytecode
// positions and does NOT consume a label id. Consuming one here would shift
// every later construct's label id and break resolve_label at emit time.
ctx.alloc_reg(); // dup register
ctx.projected_pc += 1; // LOAD_VAR (DUP)
ctx.projected_pc += 1; // JMP_IF_NULLISH
ctx.projected_pc += 1; // JMP over RHS on non-nullish
self.count_expression(&log.right, ctx);
ctx.projected_pc += 1; // LOAD_VAR (overwrite)
} else {
let id = ctx.next_label_id();
ctx.alloc_reg(); // dup register
ctx.projected_pc += 1; // LOAD_VAR (DUP)
ctx.projected_pc += 1; // JMP_IF_FALSE or JMP_IF_TRUE
self.count_expression(&log.right, ctx);
ctx.projected_pc += 1; // LOAD_VAR (overwrite)
let skip_label = match log.operator {
LogicalOperator::And => Label::TernaryEnd(id),
LogicalOperator::Or => Label::TernaryElse(id),
LogicalOperator::Coalesce => unreachable!("coalesce handled above"),
};
ctx.labels.label_map.insert(skip_label, ctx.projected_pc);
}
}
pub(crate) fn count_conditional_chain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::ConditionalExpression(_) => self.count_conditional_expression(expr, ctx),
Expression::SequenceExpression(_) => self.count_sequence_expression(expr, ctx),
Expression::LogicalExpression(_) => self.count_logical_expression(expr, ctx),
_ => {}
}
}
}
impl Compiler { impl Compiler {
fn emit_private_in_expression( fn emit_private_in_expression(
&self, pin: &oxide_parser::PrivateInExpression, ctx: &mut CompileCtx, &self, pin: &oxide_parser::PrivateInExpression, ctx: &mut CompileCtx,
@@ -347,7 +552,7 @@ impl Compiler {
} }
} }
pub(in crate::emitter) fn emit_operator(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> { pub(crate) fn emit_operator(&self, expr: &Expression, ctx: &mut CompileCtx) -> Result<u8, String> {
match expr { match expr {
Expression::BinaryExpression(bin) => self.emit_binary_expression(bin, ctx), Expression::BinaryExpression(bin) => self.emit_binary_expression(bin, ctx),
Expression::PrivateInExpression(pin) => self.emit_private_in_expression(pin, ctx), Expression::PrivateInExpression(pin) => self.emit_private_in_expression(pin, ctx),
@@ -0,0 +1,15 @@
use super::*;
impl Compiler {
pub(crate) fn count_parenthesized_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
if let Expression::ParenthesizedExpression(p) = expr {
self.count_expression(&p.expression, ctx);
}
}
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,60 @@
use super::*;
impl Compiler {
fn count_template_literal(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::TemplateLiteral(tl) = expr else {
return;
};
for expr in &tl.expressions {
self.count_expression(expr, ctx);
}
let segment_count = tl.quasis.len() + tl.expressions.len();
ctx.count_template_str(segment_count);
}
fn count_tagged_template_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
let Expression::TaggedTemplateExpression(tt) = expr else {
return;
};
self.count_expression(&tt.tag, ctx);
let quasi_count = tt.quasi.quasis.len();
for _ in 0..quasi_count {
ctx.count_load_const(); // string
ctx.count_load_const(); // index
ctx.count_instr(); // SET_ELEM (cooked)
}
ctx.alloc_reg(); // cooked_temp
ctx.count_instr(); // NEW_ARRAY
for _ in 0..quasi_count {
ctx.count_load_const(); // string
ctx.count_load_const(); // index
ctx.count_instr(); // SET_ELEM (raw)
}
ctx.alloc_reg(); // raw_temp
ctx.count_instr(); // NEW_ARRAY
for expr in &tt.quasi.expressions {
self.count_expression(expr, ctx);
}
ctx.alloc_reg(); // cooked_slot
ctx.alloc_reg(); // raw_slot
for _ in &tt.quasi.expressions {
ctx.alloc_reg(); // expr_slot
ctx.count_instr(); // LOAD_VAR
}
ctx.count_words(2); // LOAD_VAR for cooked and raw
ctx.count_load_const(); // undefined this arg
ctx.count_call_instr_with_arg_ext();
ctx.count_load_var(); // result <- regs[0]
}
pub(crate) fn count_template_domain(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::TemplateLiteral(_) => self.count_template_literal(expr, ctx),
Expression::TaggedTemplateExpression(_) => self.count_tagged_template_expression(expr, ctx),
_ => {}
}
}
}
@@ -0,0 +1,135 @@
use super::*;
impl Compiler {
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();
// Evaluate each expression, collecting registers
let expr_regs: Vec<u8> = expressions
.iter()
.map(|e| self.emit_expression(e, ctx))
.collect::<Result<Vec<_>, _>>()?;
// Add each quasi string to constant pool
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();
// Compute total length hint
let total_len_hint: usize = quasis
.iter()
.map(|q| q.value.cooked.as_ref().map(|c| c.len()).unwrap_or(0))
.sum();
// Emit TEMPLATE_STR rd, 0, 0
ctx.emit(opcode::encode(OpCode::TEMPLATE_STR, r, 0, 0));
// Ext word 0: (segment_count << 16) | (total_len_hint & 0xFFFF)
ctx.emit(((segment_count as u32) << 16) | (total_len_hint as u32 & 0xFFFF));
// Interleave segments: quasi[0], expr[0], quasi[1], expr[1], ...
let mut expr_iter = expr_regs.iter();
for const_idx in quasi_const_idxs.iter() {
// Quasi: is_expression=0, bits 0-15 = const_idx
ctx.emit(*const_idx as u32 & 0x7FFF_FFFF);
// Expression (if any remaining)
if let Some(expr_reg) = expr_iter.next() {
// Expression: is_expression=1, bits 0-15 = reg
ctx.emit(0x8000_0000u32 | (*expr_reg as u32));
}
}
Ok(r)
}
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;
// 1. Evaluate tag expression
let tag_reg = self.emit_expression(&tt.tag, ctx)?;
// 2. Build cooked strings array (into a temp register)
let cooked_temp = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::NEW_ARRAY, cooked_temp, quasis.len() as u8, 0));
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.emit_load_const(str_reg, const_idx);
let idx_const = ctx.add_constant(Constant::Int(i as i32));
let idx_reg = ctx.alloc_reg();
ctx.emit_load_const(idx_reg, idx_const);
ctx.emit(opcode::encode(OpCode::SET_ELEM, cooked_temp, idx_reg, str_reg));
}
// 3. Build raw strings array (into a temp register)
let raw_temp = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::NEW_ARRAY, raw_temp, quasis.len() as u8, 0));
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.emit_load_const(str_reg, const_idx);
let idx_const = ctx.add_constant(Constant::Int(i as i32));
let idx_reg = ctx.alloc_reg();
ctx.emit_load_const(idx_reg, idx_const);
ctx.emit(opcode::encode(OpCode::SET_ELEM, raw_temp, idx_reg, str_reg));
}
// 4. Evaluate expression arguments (into temp registers)
let mut expr_temps = Vec::new();
for expr in expressions {
expr_temps.push(self.emit_expression(expr, ctx)?);
}
// 5. Allocate consecutive argument slots: cooked, raw, expr[0], expr[1], ...
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());
}
// Copy temps to consecutive slots using LOAD_VAR (register-to-register move)
ctx.emit(opcode::encode(OpCode::LOAD_VAR, cooked_slot, cooked_temp, 0));
ctx.emit(opcode::encode(OpCode::LOAD_VAR, raw_slot, raw_temp, 0));
for (slot, temp) in expr_slots.iter().zip(expr_temps.iter()) {
ctx.emit(opcode::encode(OpCode::LOAD_VAR, *slot, *temp, 0));
}
// 6. Emit undefined as this_arg
let undef_idx = ctx.add_constant(Constant::Undefined);
let undef_reg = ctx.alloc_reg();
ctx.emit_load_const(undef_reg, undef_idx);
// 7. Emit CALL(tag, undefined, cooked_slot)
let arg_count = 2 + expressions.len();
ctx.emit(opcode::encode(OpCode::CALL, tag_reg, undef_reg, cooked_slot));
ctx.emit(arg_count as u32);
// 8. Result from regs[0]
let result_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, 0, 0));
Ok(result_reg)
}
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,3 @@
pub use super::*;
pub mod count;
pub mod emit;
@@ -0,0 +1,15 @@
use super::*;
impl Compiler {
pub(crate) fn count_this_expression(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.projected_pc += 1;
}
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);
ctx.emit(opcode::encode(OpCode::LOAD_VAR, r, src, 0));
Ok(r)
}
}
+139
View File
@@ -0,0 +1,139 @@
#[allow(unused_imports)]
use oxide_bytecode::module::Constant;
#[allow(unused_imports)]
use oxide_bytecode::opcode::{self, OpCode};
#[allow(unused_imports)]
use oxide_parser::{
AssignmentOperator, AssignmentTarget, AssignmentTargetMaybeDefault, AssignmentTargetProperty, BindingPattern,
ChainElement, Class, ClassElement, Expression, ForStatementInit, ForStatementLeft, LogicalOperator,
MethodDefinitionKind, ObjectAssignmentTarget, PropertyKey, PropertyKind, SimpleAssignmentTarget, Statement,
UnaryOperator, UpdateOperator, VariableDeclarationKind,
};
#[allow(unused_imports)]
use crate::compiler::{
is_int_literal, is_side_effect_free, BinaryOperator, CompileCtx, Compiler, FunctionBodyContext, Label, ParamSpec,
};
pub mod class;
pub mod expr;
pub mod shared;
pub mod stmt;
impl Compiler {
pub(crate) fn count_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::ExpressionStatement(_)
| Statement::ReturnStatement(_)
| Statement::BreakStatement(_)
| Statement::ContinueStatement(_)
| Statement::LabeledStatement(_) => self.count_basic(stmt, ctx),
Statement::BlockStatement(_) => self.count_block_domain(stmt, ctx),
Statement::VariableDeclaration(_) | Statement::FunctionDeclaration(_) | Statement::ClassDeclaration(_) => {
self.count_declaration_domain(stmt, ctx)
}
Statement::IfStatement(_) => self.count_control_domain(stmt, ctx),
Statement::WhileStatement(_)
| Statement::DoWhileStatement(_)
| Statement::ForStatement(_)
| Statement::ForInStatement(_)
| Statement::ForOfStatement(_) => self.count_iteration_domain(stmt, ctx),
Statement::SwitchStatement(_) => self.count_switch_domain(stmt, ctx),
Statement::ThrowStatement(_) | Statement::TryStatement(_) => self.count_exception_domain(stmt, ctx),
_ => {}
}
}
pub(crate) fn count_expression(&self, expr: &Expression, ctx: &mut CompileCtx) {
match expr {
Expression::BinaryExpression(_)
| Expression::PrivateInExpression(_)
| Expression::UnaryExpression(_)
| Expression::UpdateExpression(_) => self.count_operator(expr, ctx),
Expression::CallExpression(_) | Expression::NewExpression(_) => self.count_call_domain(expr, ctx),
Expression::AssignmentExpression(_) => self.count_assignment(expr, ctx),
Expression::ConditionalExpression(_)
| Expression::SequenceExpression(_)
| Expression::LogicalExpression(_) => self.count_conditional_chain(expr, ctx),
Expression::ChainExpression(_) => self.count_chain_expression(expr, ctx),
Expression::ObjectExpression(_) | Expression::ArrayExpression(_) => self.count_object_domain(expr, ctx),
Expression::TemplateLiteral(_) | Expression::TaggedTemplateExpression(_) => {
self.count_template_domain(expr, ctx)
}
Expression::ArrowFunctionExpression(_)
| Expression::FunctionExpression(_)
| Expression::ClassExpression(_) => self.count_function_domain(expr, ctx),
Expression::StaticMemberExpression(_)
| Expression::ComputedMemberExpression(_)
| Expression::PrivateFieldExpression(_) => self.count_member_domain(expr, ctx),
Expression::ParenthesizedExpression(_) => self.count_parenthesized_expression(expr, ctx),
Expression::ThisExpression(_) => self.count_this_expression(ctx),
Expression::Identifier(_) => self.count_identifier_expression(expr, ctx),
Expression::NumericLiteral(_)
| Expression::StringLiteral(_)
| Expression::BooleanLiteral(_)
| Expression::NullLiteral(_)
| Expression::RegExpLiteral(_) => self.count_literal(expr, ctx),
_ => self.count_default_expression(ctx),
}
}
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),
}
}
}
@@ -0,0 +1 @@
// placeholder
@@ -0,0 +1 @@
// placeholder
@@ -0,0 +1,55 @@
use super::super::*;
impl Compiler {
pub(super) fn count_break_statement(&self, ctx: &mut CompileCtx) {
ctx.projected_pc += 1;
}
pub(super) fn count_continue_statement(&self, ctx: &mut CompileCtx) {
ctx.projected_pc += 1;
}
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
};
let break_pos = ctx.resolve_label(break_label)?;
let offset = (break_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
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
};
let continue_pos = ctx.resolve_label(continue_label)?;
let offset = (continue_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
Ok(None)
}
}
@@ -0,0 +1,20 @@
use super::super::*;
impl Compiler {
pub(super) fn count_expression_statement(
&self, stmt: &oxide_parser::ExpressionStatement<'_>, ctx: &mut CompileCtx,
) {
self.count_expression(&stmt.expression, ctx);
}
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,48 @@
use super::super::*;
impl Compiler {
pub(super) fn count_labeled_statement(&self, stmt: &oxide_parser::LabeledStatement<'_>, ctx: &mut CompileCtx) {
let body_is_loop = matches!(
stmt.body,
Statement::WhileStatement(_)
| Statement::DoWhileStatement(_)
| Statement::ForStatement(_)
| Statement::ForInStatement(_)
| Statement::ForOfStatement(_)
);
if body_is_loop {
self.count_statement(&stmt.body, ctx);
} else {
let id = ctx.next_label_id();
self.count_statement(&stmt.body, ctx);
ctx.labels.label_map.insert(Label::LabeledEnd(id), ctx.projected_pc);
}
}
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, Label::LabeledEnd(id), None)?;
self.emit_statement(&stmt.body, ctx)?;
ctx.pop_label_scope();
}
Ok(None)
}
}
@@ -0,0 +1,28 @@
pub use super::super::*;
mod break_continue;
mod expression;
mod labeled;
mod return_stmt;
impl Compiler {
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),
}
}
pub(crate) fn count_basic(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::ExpressionStatement(es) => self.count_expression_statement(es, ctx),
Statement::ReturnStatement(ret) => self.count_return_statement(ret, ctx),
Statement::BreakStatement(_) => self.count_break_statement(ctx),
Statement::ContinueStatement(_) => self.count_continue_statement(ctx),
Statement::LabeledStatement(ls) => self.count_labeled_statement(ls, ctx),
_ => {}
}
}
}
@@ -0,0 +1,30 @@
use super::super::*;
impl Compiler {
pub(super) fn count_return_statement(&self, stmt: &oxide_parser::ReturnStatement<'_>, ctx: &mut CompileCtx) {
if let Some(arg) = &stmt.argument {
self.count_expression(arg, ctx);
}
ctx.projected_pc += 1;
}
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.emit(opcode::encode(OpCode::RETURN, r, 0, 0));
}
None => {
ctx.emit(opcode::encode(OpCode::RETURN, 0, 0, 0));
}
}
Ok(None)
}
pub(crate) fn emit_basic_return(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
self.emit_return_statement(stmt, ctx)
}
}
@@ -1,6 +1,12 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
fn count_block_statement(&self, block: &oxide_parser::BlockStatement<'_>, ctx: &mut CompileCtx) {
for s in &block.body {
self.count_statement(s, ctx);
}
}
fn emit_block_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> { fn emit_block_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
let Statement::BlockStatement(block) = stmt else { let Statement::BlockStatement(block) = stmt else {
return Ok(None); return Ok(None);
@@ -16,9 +22,13 @@ impl Compiler {
Ok(r) Ok(r)
} }
pub(in crate::emitter) fn emit_block_domain( pub(crate) fn count_block_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
&self, stmt: &Statement, ctx: &mut CompileCtx, if let Statement::BlockStatement(block) = stmt {
) -> Result<Option<u8>, String> { self.count_block_statement(block, ctx);
}
}
pub(crate) fn emit_block_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
match stmt { match stmt {
Statement::BlockStatement(_) => self.emit_block_statement(stmt, ctx), Statement::BlockStatement(_) => self.emit_block_statement(stmt, ctx),
_ => Ok(None), _ => Ok(None),
@@ -1,6 +1,27 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
fn count_if_statement(&self, stmt: &oxide_parser::IfStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let else_label = Label::IfElse(id);
let end_label = Label::IfEnd(id);
self.count_expression(&stmt.test, ctx);
ctx.projected_pc += 1;
self.count_statement(&stmt.consequent, ctx);
ctx.alloc_reg();
ctx.projected_pc += 1;
if stmt.alternate.is_some() {
ctx.projected_pc += 1;
}
ctx.labels.label_map.insert(else_label, ctx.projected_pc);
if let Some(alt_stmt) = &stmt.alternate {
self.count_statement(alt_stmt, ctx);
ctx.projected_pc += 1;
}
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn emit_if_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> { fn emit_if_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
let Statement::IfStatement(ifs) = stmt else { let Statement::IfStatement(ifs) = stmt else {
return Ok(None); return Ok(None);
@@ -45,9 +66,13 @@ impl Compiler {
Ok(Some(result_reg)) Ok(Some(result_reg))
} }
pub(in crate::emitter) fn emit_control_domain( pub(crate) fn count_control_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
&self, stmt: &Statement, ctx: &mut CompileCtx, if let Statement::IfStatement(ifs) = stmt {
) -> Result<Option<u8>, String> { self.count_if_statement(ifs, ctx);
}
}
pub(crate) fn emit_control_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
match stmt { match stmt {
Statement::IfStatement(_) => self.emit_if_statement(stmt, ctx), Statement::IfStatement(_) => self.emit_if_statement(stmt, ctx),
_ => Ok(None), _ => Ok(None),
@@ -0,0 +1,3 @@
pub use super::super::*;
pub mod var;
@@ -0,0 +1,162 @@
use super::super::*;
impl Compiler {
fn count_variable_declaration(&self, decl: &oxide_parser::VariableDeclaration<'_>, ctx: &mut CompileCtx) {
let is_var = matches!(decl.kind, VariableDeclarationKind::Var);
for d in &decl.declarations {
if let Some(init) = &d.init {
self.count_expression(init, ctx);
if is_var {
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);
ctx.projected_pc += 1;
continue;
}
}
self.count_binding_pattern(&d.id, ctx);
} else {
ctx.alloc_reg();
ctx.count_words(2);
}
}
}
fn count_function_declaration(&self, decl: &oxide_parser::Function<'_>, ctx: &mut CompileCtx) {
let name = if let Some(id) = &decl.id {
id.name.to_string()
} else {
return;
};
let func_reg = ctx.alloc_reg();
let _ = ctx.declare_initialized(&name, func_reg, VariableDeclarationKind::Var, false);
ctx.count_words(2);
}
fn count_class_declaration(&self, class: &oxide_parser::Class<'_>, ctx: &mut CompileCtx) {
ctx.alloc_reg();
self.count_class(class, ctx);
ctx.projected_pc += 1;
}
pub(crate) fn count_declaration_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::VariableDeclaration(decl) => self.count_variable_declaration(decl, ctx),
Statement::FunctionDeclaration(fd) => self.count_function_declaration(fd, ctx),
Statement::ClassDeclaration(class) => self.count_class_declaration(class, ctx),
_ => {}
}
}
}
impl Compiler {
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.sub_modules.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.emit_load_const(tmp, idx);
let var_reg = ctx.alloc_reg();
ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const)?;
let is_captured = ctx.scopes.symbols.lookup_is_captured(bi.name.as_str());
if is_captured {
let cell_idx = ctx.scopes.cell_registry.len() as u8;
ctx.scopes.cell_registry.push((bi.name.to_string(), cell_idx));
ctx.emit(opcode::encode(OpCode::MAKE_CELL, tmp, cell_idx, 0));
} else {
ctx.emit(opcode::encode(OpCode::STORE_VAR, var_reg, tmp, 0));
}
ctx.init_var(bi.name.as_str());
r = Some(var_reg);
}
}
Ok(r)
}
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.sub_modules.push(sub_module);
let sub_idx = ctx.sub_modules.len() as u32;
let var_reg = ctx.lookup(&name)?;
ctx.reserve_reg(var_reg);
ctx.emit_create_closure(var_reg, sub_idx);
ctx.emit(opcode::encode(OpCode::STORE_VAR, var_reg, var_reg, 0));
Ok(None)
}
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)?;
ctx.emit(opcode::encode(OpCode::STORE_VAR, var_reg, ctor_reg, 0));
Ok(None)
}
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,67 @@
use super::super::*;
impl Compiler {
fn count_throw_statement(&self, stmt: &oxide_parser::ThrowStatement<'_>, ctx: &mut CompileCtx) {
self.count_expression(&stmt.argument, ctx);
ctx.projected_pc += 1;
}
fn count_try_statement(&self, stmt: &oxide_parser::TryStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let catch_label = Label::CatchBody(id);
let try_end_label = Label::TryEnd(id);
let has_catch = stmt.handler.is_some();
let has_finally = stmt.finalizer.is_some();
ctx.alloc_reg();
if has_finally {
ctx.projected_pc += 1;
}
if has_catch {
ctx.projected_pc += 1;
}
for s in &stmt.block.body {
self.count_statement(s, ctx);
}
ctx.projected_pc += 1;
if has_catch {
ctx.projected_pc += 1;
}
let jmp_needed = has_catch || has_finally;
if jmp_needed {
ctx.projected_pc += 1;
}
ctx.labels.label_map.insert(catch_label, ctx.projected_pc);
if let Some(catch) = &stmt.handler {
ctx.push_scope();
if let Some(param) = &catch.param {
ctx.alloc_reg();
if let oxide_parser::BindingPattern::BindingIdentifier(_) = &param.pattern {
ctx.projected_pc += 1;
}
}
for cs in &catch.body.body {
self.count_statement(cs, ctx);
}
ctx.projected_pc += 1;
ctx.pop_scope();
}
if let Some(finally) = &stmt.finalizer {
let finally_label = Label::FinallyBody(id);
ctx.labels.label_map.insert(finally_label, ctx.projected_pc);
for fs in &finally.body {
self.count_statement(fs, ctx);
}
ctx.projected_pc += 1;
ctx.projected_pc += 1;
}
ctx.labels.label_map.insert(try_end_label, ctx.projected_pc);
}
pub(crate) fn count_exception_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::ThrowStatement(ts) => self.count_throw_statement(ts, ctx),
Statement::TryStatement(ts) => self.count_try_statement(ts, ctx),
_ => {}
}
}
}
@@ -0,0 +1,115 @@
use super::super::*;
impl Compiler {
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.emit(opcode::encode(OpCode::THROW, exc_reg, 0, 0));
Ok(None)
}
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 id = ctx.next_label_id();
let catch_label = Label::CatchBody(id);
let try_end_label = Label::TryEnd(id);
let has_catch = ts.handler.is_some();
let has_finally = ts.finalizer.is_some();
let result_reg = ctx.alloc_reg();
let mut try_finally_begin_pos: Option<usize> = None;
let mut try_begin_pos: Option<usize> = None;
if has_finally {
try_finally_begin_pos = Some(ctx.bytecode.len());
ctx.emit(opcode::encode_try_finally_begin(0));
}
if has_catch {
try_begin_pos = Some(ctx.bytecode.len());
ctx.emit(opcode::encode_try_begin(0));
}
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.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, last_try_result.unwrap_or(result_reg), 0));
if has_catch {
ctx.emit(opcode::encode(OpCode::TRY_END, 0, 0, 0));
}
let jmp_needed = has_catch || has_finally;
let jmp_skip_pos = if jmp_needed {
let pos = ctx.bytecode.len();
ctx.emit(opcode::encode_jmp(0));
Some(pos)
} else {
None
};
let catch_label_pc = ctx.bytecode.len();
ctx.labels.label_map.insert(catch_label, catch_label_pc);
if let Some(try_begin_pc) = try_begin_pos {
let offset = catch_label_pc as isize - (try_begin_pc as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.bytecode[try_begin_pc] = opcode::encode_try_begin(offset);
}
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.emit(opcode::encode(OpCode::STORE_VAR, catch_reg, 0, 0));
}
}
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.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, last_catch_result.unwrap_or(result_reg), 0));
ctx.pop_scope();
}
if has_finally {
let finally_label = Label::FinallyBody(id);
let finally_label_pc = ctx.bytecode.len();
ctx.labels.label_map.insert(finally_label, finally_label_pc);
if let Some(fb_pos) = try_finally_begin_pos {
let offset = finally_label_pc as isize - (fb_pos as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.bytecode[fb_pos] = opcode::encode_try_finally_begin(offset);
}
if let Some(jmp_pos) = jmp_skip_pos {
let offset = finally_label_pc as isize - (jmp_pos as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.bytecode[jmp_pos] = opcode::encode_jmp(offset);
}
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.emit(opcode::encode(OpCode::LOAD_VAR, result_reg, last_finally_result.unwrap_or(result_reg), 0));
ctx.emit(opcode::encode(OpCode::TRY_FINALLY_END, 0, 0, 0));
} else if let Some(jmp_pos) = jmp_skip_pos {
let offset = ctx.bytecode.len() as isize - (jmp_pos as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.bytecode[jmp_pos] = opcode::encode_jmp(offset);
}
let try_end_pc = ctx.bytecode.len();
ctx.labels.label_map.insert(try_end_label, try_end_pc);
Ok(Some(result_reg))
}
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,4 @@
pub use super::super::*;
pub mod count;
pub mod emit;
@@ -0,0 +1,138 @@
use super::super::*;
impl Compiler {
fn count_while_statement(&self, stmt: &oxide_parser::WhileStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let start_label = Label::WhileStart(id);
let end_label = Label::WhileEnd(id);
ctx.labels.label_map.insert(start_label, ctx.projected_pc);
self.count_expression(&stmt.test, ctx);
ctx.projected_pc += 1;
self.count_statement(&stmt.body, ctx);
ctx.projected_pc += 1;
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn count_do_while_statement(&self, stmt: &oxide_parser::DoWhileStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let start_label = Label::DoWhileStart(id);
let end_label = Label::DoWhileEnd(id);
ctx.labels.label_map.insert(start_label, ctx.projected_pc);
self.count_statement(&stmt.body, ctx);
self.count_expression(&stmt.test, ctx);
ctx.projected_pc += 1;
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn count_for_statement(&self, stmt: &oxide_parser::ForStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let start_label = Label::ForStart(id);
let update_label = Label::ForUpdate(id);
let end_label = Label::ForEnd(id);
if let Some(init) = &stmt.init {
if let Some(expr) = init.as_expression() {
self.count_expression(expr, ctx);
} else if let ForStatementInit::VariableDeclaration(decl) = init {
for d in &decl.declarations {
if let Some(init_expr) = &d.init {
self.count_expression(init_expr, ctx);
self.count_binding_pattern(&d.id, ctx);
} else {
ctx.alloc_reg();
ctx.alloc_reg();
ctx.count_words(2);
}
}
}
}
ctx.labels.label_map.insert(start_label, ctx.projected_pc);
if let Some(test) = &stmt.test {
self.count_expression(test, ctx);
ctx.projected_pc += 1;
}
self.count_statement(&stmt.body, ctx);
ctx.labels.label_map.insert(update_label, ctx.projected_pc);
if let Some(update) = &stmt.update {
self.count_expression(update, ctx);
}
ctx.projected_pc += 1;
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
}
fn count_for_in_statement(&self, stmt: &oxide_parser::ForInStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let start_label = Label::ForInStart(id);
let end_label = Label::ForInEnd(id);
self.count_expression(&stmt.right, ctx);
ctx.count_instr();
ctx.labels.label_map.insert(start_label, ctx.projected_pc);
ctx.count_instr();
ctx.count_jump();
ctx.count_jump();
ctx.count_instr();
match &stmt.left {
oxide_parser::ForStatementLeft::VariableDeclaration(decl) => {
for _d in &decl.declarations {
ctx.alloc_reg();
ctx.count_instr();
}
}
oxide_parser::ForStatementLeft::AssignmentTargetIdentifier(_) => {
ctx.alloc_reg();
ctx.count_instr();
}
_ => {}
}
self.count_statement(&stmt.body, ctx);
ctx.count_jump();
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
ctx.count_instr();
}
fn count_for_of_statement(&self, stmt: &oxide_parser::ForOfStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let start_label = Label::ForOfStart(id);
let end_label = Label::ForOfEnd(id);
self.count_expression(&stmt.right, ctx);
ctx.count_instr();
ctx.labels.label_map.insert(start_label, ctx.projected_pc);
ctx.alloc_reg();
ctx.count_instr();
ctx.count_jump();
ctx.alloc_reg();
ctx.count_instr();
match &stmt.left {
oxide_parser::ForStatementLeft::VariableDeclaration(decl) => {
for d in &decl.declarations {
self.count_binding_pattern(&d.id, ctx);
}
}
oxide_parser::ForStatementLeft::AssignmentTargetIdentifier(_) => {
ctx.alloc_reg();
ctx.count_instr();
}
oxide_parser::ForStatementLeft::ArrayAssignmentTarget(ap) => {
self.count_array_assignment(ap, ctx);
}
oxide_parser::ForStatementLeft::ObjectAssignmentTarget(op) => {
self.count_object_assignment(op, ctx);
}
_ => {}
}
self.count_statement(&stmt.body, ctx);
ctx.count_jump();
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
ctx.count_instr();
}
pub(crate) fn count_iteration_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
match stmt {
Statement::WhileStatement(wh) => self.count_while_statement(wh, ctx),
Statement::DoWhileStatement(dw) => self.count_do_while_statement(dw, ctx),
Statement::ForStatement(fr) => self.count_for_statement(fr, ctx),
Statement::ForInStatement(fi) => self.count_for_in_statement(fi, ctx),
Statement::ForOfStatement(fo) => self.count_for_of_statement(fo, ctx),
_ => {}
}
}
}
@@ -0,0 +1,209 @@
use super::super::*;
impl Compiler {
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),
}
}
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 id = ctx.next_label_id();
let start_label = Label::WhileStart(id);
let end_label = Label::WhileEnd(id);
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)?;
let end_pos = ctx.resolve_label(end_label)?;
let offset = (end_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp_if_false(test_reg, offset));
self.emit_statement(&wh.body, ctx)?;
let start_pos = ctx.resolve_label(start_label)?;
let offset = (start_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
ctx.pop_label_scopes(n_labeled);
ctx.pop_loop();
Ok(None)
}
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 id = ctx.next_label_id();
let start_label = Label::DoWhileStart(id);
let end_label = Label::DoWhileEnd(id);
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)?;
let start_pos = ctx.resolve_label(start_label)?;
let offset = (start_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp_if_true(test_reg, offset));
ctx.pop_label_scopes(n_labeled);
ctx.pop_loop();
Ok(None)
}
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 id = ctx.next_label_id();
let start_label = Label::ForStart(id);
let update_label = Label::ForUpdate(id);
let end_label = Label::ForEnd(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.emit_load_const(tmp, idx);
let var_reg = ctx.alloc_reg();
ctx.declare(bi.name.as_str(), var_reg, decl.kind, is_const)?;
ctx.emit(opcode::encode(OpCode::STORE_VAR, var_reg, tmp, 0));
ctx.init_var(bi.name.as_str());
}
}
}
}
if let Some(test) = &fr.test {
let test_reg = self.emit_expression(test, ctx)?;
let end_pos = ctx.resolve_label(end_label)?;
let offset = (end_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp_if_false(test_reg, offset));
}
self.emit_statement(&fr.body, ctx)?;
if let Some(update) = &fr.update {
self.emit_expression(update, ctx)?;
}
let start_pos = ctx.resolve_label(start_label)?;
let offset = (start_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
ctx.pop_label_scopes(n_labeled);
ctx.pop_loop();
Ok(None)
}
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 id = ctx.next_label_id();
let start_label = Label::ForInStart(id);
let end_label = Label::ForInEnd(id);
let obj_reg = self.emit_expression(&fi.right, ctx)?;
ctx.emit(opcode::encode(OpCode::FOR_IN_INIT, 0, obj_reg, 0));
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.emit(opcode::encode(OpCode::FOR_IN_DONE, done_reg, 0, 0));
let end_pos = ctx.resolve_label(end_label)?;
let cleanup_jmp_offset = (end_pos as isize) - (ctx.bytecode.len() as isize);
ctx.emit(opcode::encode_jmp_if_false(done_reg, 2));
let cleanup_jmp_offset = ctx.checked_jump_offset(cleanup_jmp_offset);
ctx.emit(opcode::encode_jmp(cleanup_jmp_offset));
let key_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::FOR_IN_NEXT, key_reg, 0, 0));
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.emit(opcode::encode(OpCode::STORE_VAR, var_reg, key_reg, 0));
ctx.init_var(name);
}
}
ForStatementLeft::AssignmentTargetIdentifier(id_ref) => {
let name = id_ref.name.as_str();
let var_reg = ctx.lookup_or_global(name);
ctx.emit(opcode::encode(OpCode::STORE_VAR, var_reg, key_reg, 0));
}
_ => return Err("unsupported for-in left-hand side".into()),
}
self.emit_statement(&fi.body, ctx)?;
let start_pos = ctx.resolve_label(start_label)?;
let offset = (start_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
ctx.emit(opcode::encode(OpCode::FOR_IN_CLEANUP, 0, 0, 0));
ctx.pop_label_scopes(n_labeled);
ctx.pop_loop();
Ok(None)
}
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 id = ctx.next_label_id();
let start_label = Label::ForOfStart(id);
let end_label = Label::ForOfEnd(id);
let iter_src_reg = self.emit_expression(&fo.right, ctx)?;
ctx.emit(opcode::encode(OpCode::FOR_OF_INIT, 0, iter_src_reg, 0));
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.emit(opcode::encode(OpCode::FOR_OF_DONE, has_reg, 0, 0));
let end_pos = ctx.resolve_label(end_label)?;
let offset = (end_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp_if_false(has_reg, offset));
let val_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::FOR_OF_NEXT, val_reg, 0, 0));
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.emit(opcode::encode(OpCode::STORE_VAR, var_reg, val_reg, 0));
}
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)?;
let start_pos = ctx.resolve_label(start_label)?;
let offset = (start_pos as isize) - (ctx.bytecode.len() as isize);
let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset));
ctx.emit(opcode::encode(OpCode::FOR_OF_CLOSE, 0, 0, 0));
ctx.pop_label_scopes(n_labeled);
ctx.pop_loop();
Ok(None)
}
}
@@ -0,0 +1,4 @@
pub use super::super::*;
pub mod count;
pub mod emit;
@@ -0,0 +1,9 @@
pub use super::*;
pub mod basic;
pub mod block;
pub mod control;
pub mod declaration;
pub mod exception;
pub mod iteration;
pub mod switch;
@@ -1,6 +1,37 @@
use super::*; use super::*;
impl Compiler { impl Compiler {
fn count_switch_statement(&self, stmt: &oxide_parser::SwitchStatement<'_>, ctx: &mut CompileCtx) {
let id = ctx.next_label_id();
let end_label = Label::SwitchEnd(id);
ctx.push_switch(end_label);
self.count_expression(&stmt.discriminant, ctx);
let compare_reg_checkpoint = ctx.reg_checkpoint();
let cases = &stmt.cases;
for case in cases.iter() {
if let Some(test) = &case.test {
self.count_expression(test, ctx);
ctx.projected_pc += 1;
ctx.alloc_reg();
ctx.projected_pc += 1;
ctx.restore_reg_checkpoint(compare_reg_checkpoint);
}
}
let has_default = cases.iter().any(|c| c.test.is_none());
if !has_default {
ctx.projected_pc += 1;
}
for (case_idx, case) in cases.iter().enumerate() {
let case_label = Label::SwitchCase(id, case_idx as u32);
ctx.labels.label_map.insert(case_label, ctx.projected_pc);
for s in &case.consequent {
self.count_statement(s, ctx);
}
}
ctx.labels.label_map.insert(end_label, ctx.projected_pc);
ctx.pop_switch();
}
fn emit_switch_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> { fn emit_switch_statement(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
let Statement::SwitchStatement(sw) = stmt else { let Statement::SwitchStatement(sw) = stmt else {
return Ok(None); return Ok(None);
@@ -8,17 +39,14 @@ impl Compiler {
let id = ctx.next_label_id(); let id = ctx.next_label_id();
let end_label = Label::SwitchEnd(id); let end_label = Label::SwitchEnd(id);
ctx.push_switch(end_label); ctx.push_switch(end_label);
let disc_reg = self.emit_expression(&sw.discriminant, ctx)?; let disc_reg = self.emit_expression(&sw.discriminant, ctx)?;
let compare_reg_checkpoint = ctx.reg_checkpoint(); let compare_reg_checkpoint = ctx.reg_checkpoint();
let cases = &sw.cases; let cases = &sw.cases;
for (case_idx, case) in cases.iter().enumerate() { for (case_idx, case) in cases.iter().enumerate() {
if let Some(test) = &case.test { if let Some(test) = &case.test {
let test_reg = self.emit_expression(test, ctx)?; let test_reg = self.emit_expression(test, ctx)?;
let eq_reg = ctx.alloc_reg(); let eq_reg = ctx.alloc_reg();
ctx.emit(opcode::encode(OpCode::EQ, eq_reg, disc_reg, test_reg)); ctx.emit(opcode::encode(OpCode::EQ, eq_reg, disc_reg, test_reg));
let case_label = Label::SwitchCase(id, case_idx as u32); let case_label = Label::SwitchCase(id, case_idx as u32);
let body_pos = ctx.resolve_label(case_label)?; let body_pos = ctx.resolve_label(case_label)?;
let offset = (body_pos as isize) - (ctx.bytecode.len() as isize); let offset = (body_pos as isize) - (ctx.bytecode.len() as isize);
@@ -27,7 +55,6 @@ impl Compiler {
ctx.restore_reg_checkpoint(compare_reg_checkpoint); ctx.restore_reg_checkpoint(compare_reg_checkpoint);
} }
} }
let has_default = cases.iter().any(|c| c.test.is_none()); let has_default = cases.iter().any(|c| c.test.is_none());
if !has_default { if !has_default {
let end_pos = ctx.resolve_label(end_label)?; let end_pos = ctx.resolve_label(end_label)?;
@@ -35,20 +62,22 @@ impl Compiler {
let offset = ctx.checked_jump_offset(offset); let offset = ctx.checked_jump_offset(offset);
ctx.emit(opcode::encode_jmp(offset)); ctx.emit(opcode::encode_jmp(offset));
} }
for case in cases.iter() { for case in cases.iter() {
for s in &case.consequent { for s in &case.consequent {
self.emit_statement(s, ctx)?; self.emit_statement(s, ctx)?;
} }
} }
ctx.pop_switch(); ctx.pop_switch();
Ok(None) Ok(None)
} }
pub(in crate::emitter) fn emit_switch_domain( pub(crate) fn count_switch_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) {
&self, stmt: &Statement, ctx: &mut CompileCtx, if let Statement::SwitchStatement(sw) = stmt {
) -> Result<Option<u8>, String> { self.count_switch_statement(sw, ctx);
}
}
pub(crate) fn emit_switch_domain(&self, stmt: &Statement, ctx: &mut CompileCtx) -> Result<Option<u8>, String> {
match stmt { match stmt {
Statement::SwitchStatement(_) => self.emit_switch_statement(stmt, ctx), Statement::SwitchStatement(_) => self.emit_switch_statement(stmt, ctx),
_ => Ok(None), _ => Ok(None),