//! Function, closure and class compilation plus the frame-slot helpers:
//! `WasmModuleEmitter::{compile_function, compile_closure,
//! compile_class_constructor, compile_class_method}`, `constructor_of`, and the
//! `FuncEmitCtx` frame-slot helpers (`emit_frame_begin`, `emit_slot_addr`,
//! `emit_store_arg`, `emit_store_const`, `emit_local_or_global_get`).
use super::closures::reads_this;
use super::*;
use perry_hir::walker::stmt_any_expr;
/// The parameters and body `new C(...)` runs for a class.
pub(super) struct Constructor {
pub params: Vec,
pub body: Vec,
}
/// The declared constructor, or JavaScript's implicit one when `new` has work to
/// do without it: `constructor() {}` runs the field initializers, and a derived
/// class's `constructor(...args) { super(...args) }` runs the parent's. A wasm
/// constructor has fixed parameters, so the derived form forwards the parent's.
pub(super) fn constructor_of(
class: &perry_hir::ir::Class,
classes: &BTreeMap<&str, &perry_hir::ir::Class>,
) -> Option {
if let Some(ctor) = &class.constructor {
return Some(Constructor {
params: ctor.params.clone(),
body: ctor.body.clone(),
});
}
let parent = class
.extends_name
.as_deref()
.and_then(|name| classes.get(name))
.and_then(|parent| constructor_of(parent, classes));
if let Some(parent) = parent {
let params: Vec = parent
.params
.into_iter()
.map(|p| Param { default: None, ..p })
.collect();
let args = params.iter().map(|p| Expr::LocalGet(p.id)).collect();
return Some(Constructor {
params,
body: vec![Stmt::Expr(Expr::SuperCall(args))],
});
}
class
.fields
.iter()
.any(|f| f.init.is_some())
.then(|| Constructor {
params: Vec::new(),
body: Vec::new(),
})
}
impl WasmModuleEmitter {
pub(super) fn compile_function(&self, hir_func: &perry_hir::ir::Function) -> Function {
self.compile_function_with_signature(hir_func, /*force_returning=*/ false)
}
/// Same as `compile_function` but allows the caller to force `wasm_returns_i64 = true`.
///
/// Class static methods need this: the type-section pass at func_section
/// emits their type as `(params) -> i64` unconditionally (mod.rs:1701),
/// but the body-based `body.iter().any(has_return)` heuristic returns
/// false for static methods that only `throw` (no explicit return). The
/// mismatch produced a `return` instruction with an empty operand stack
/// inside the compiled body — V8 rejected the WASM with
/// "expected i64 but nothing on stack" (#1081 sibling instance).
pub(super) fn compile_function_with_signature(
&self,
hir_func: &perry_hir::ir::Function,
force_returning: bool,
) -> Function {
self.compile_function_in(hir_func, force_returning, None)
}
/// A static method or static block of `class`: `(params) -> i64`, `this` its class.
pub(super) fn compile_static_method(
&self,
class: &perry_hir::ir::Class,
method: &perry_hir::ir::Function,
) -> Function {
self.compile_function_in(method, true, Some(&class.name))
}
fn compile_function_in(
&self,
hir_func: &perry_hir::ir::Function,
force_returning: bool,
static_class: Option<&str>,
) -> Function {
// Build local map: param locals come first, then body locals
let mut local_map = BTreeMap::new();
for (i, param) in hir_func.params.iter().enumerate() {
local_map.insert(param.id, i as u32);
}
// Scan body for local variable declarations
let param_count = hir_func.params.len() as u32;
let mut extra_locals = 0u32;
collect_param_locals(
&hir_func.params,
&mut local_map,
&mut extra_locals,
param_count,
);
collect_locals(
&hir_func.body,
&mut local_map,
&mut extra_locals,
param_count,
);
// A static method that reads `this` takes it once, on entry, into its own local.
let static_this = static_class.filter(|_| {
hir_func
.body
.iter()
.any(|s| stmt_any_expr(s, &mut reads_this))
});
extra_locals += u32::from(static_this.is_some());
let temp_local_idx = param_count + extra_locals;
let temp_i32_idx = temp_local_idx + 3;
let locals = vec![(extra_locals + 3, ValType::I64), (1, ValType::I32)];
let mut func = Function::new(locals);
// Must match func_section: `main` is always emitted as `()->i64` even when the body has no
// `return` statement (HIR doesn't guarantee tail-return lowering yet). Class static
// methods get `force_returning=true` because func_section also declares them as `-> i64`
// unconditionally — see compile_function_with_signature's doc-comment.
let wasm_returns_i64 =
force_returning || hir_func.body.iter().any(has_return) || hir_func.name == "main";
let mut ctx = FuncEmitCtx::new(self, &local_map, temp_local_idx, temp_i32_idx);
ctx.returns_value = wasm_returns_i64;
ctx.static_class = static_class.map(str::to_string);
ctx.emit_box_params(&mut func, &hir_func.params);
if let Some(class_name) = static_this {
let local = temp_local_idx - 1;
let ctor_slot = ctx.class_ctor_slot(class_name);
ctx.emit_class_bridge(
&mut func,
"class_static_method_this",
class_name,
&[
&Expr::Number(ctor_slot),
&Expr::String(hir_func.name.clone()),
],
);
func.instruction(&Instruction::LocalSet(local));
ctx.static_this_local = Some(local);
}
for stmt in &hir_func.body {
ctx.emit_stmt(&mut func, stmt, wasm_returns_i64);
}
// If the Wasm signature includes an i64 result, fallthrough must leave one value on stack.
if wasm_returns_i64 {
func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64));
}
func.instruction(&Instruction::End);
func
}
pub(super) fn compile_closure(
&self,
params: &[Param],
body: &[Stmt],
captures: &[LocalId],
mutable_captures: &[LocalId],
this: ClosureThis,
home_class: Option<&str>,
) -> Function {
// Closure parameters: captures, the captured `this`, then declared params
let mut local_map = BTreeMap::new();
let mut param_idx = 0u32;
for cap in captures {
local_map.insert(*cap, param_idx);
param_idx += 1;
}
for cap in mutable_captures {
local_map.insert(*cap, param_idx);
param_idx += 1;
}
let captured_this = (this == ClosureThis::Captured).then_some(param_idx);
param_idx += u32::from(captured_this.is_some());
for param in params {
local_map.insert(param.id, param_idx);
param_idx += 1;
}
// Scan body for additional locals
let mut extra_locals = 0u32;
collect_param_locals(params, &mut local_map, &mut extra_locals, param_idx);
collect_locals(body, &mut local_map, &mut extra_locals, param_idx);
let receiver = param_idx + extra_locals;
if this == ClosureThis::Receiver {
extra_locals += 1;
}
let temp_local_idx = param_idx + extra_locals;
let temp_i32_idx = temp_local_idx + 3;
let locals = vec![(extra_locals + 3, ValType::I64), (1, ValType::I32)];
let mut func = Function::new(locals);
let mut ctx = FuncEmitCtx::new(self, &local_map, temp_local_idx, temp_i32_idx);
ctx.current_class = home_class.map(str::to_string);
ctx.this_local = captured_this;
if this == ClosureThis::Receiver {
// First, before any other call can take the pending receiver.
ctx.emit_frame_begin(&mut func, 0);
ctx.emit_memcall(&mut func, "closure_this", 0);
func.instruction(&Instruction::LocalSet(receiver));
ctx.this_local = Some(receiver);
}
ctx.emit_box_params(&mut func, params);
// A captured cell already exists; a `let` of it in the body (a lowered
// generator re-declares its locals per state) fills that cell.
for cap in captures.iter().chain(mutable_captures) {
if ctx.is_boxed(cap) {
ctx.preallocated.insert(*cap);
}
}
let _has_ret = body.iter().any(has_return);
for stmt in body {
ctx.emit_stmt(&mut func, stmt, true); // closures always "return"
}
// Default return undefined
func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64));
func.instruction(&Instruction::End);
func
}
pub(super) fn compile_class_constructor(
&self,
class: &perry_hir::ir::Class,
ctor: &Constructor,
) -> Function {
// Local 0 = this (the instance handle)
// Params start at local index 1
let mut local_map = BTreeMap::new();
// Don't insert this into local_map — Expr::This emits LocalGet(0) directly
for (i, param) in ctor.params.iter().enumerate() {
local_map.insert(param.id, (i + 1) as u32);
}
let param_count = 1 + ctor.params.len();
let mut extra_locals = 0u32;
collect_param_locals(
&ctor.params,
&mut local_map,
&mut extra_locals,
param_count as u32,
);
for field in &class.fields {
if let Some(init) = &field.init {
collect_expr_locals(init, &mut local_map, &mut extra_locals, param_count as u32);
}
}
collect_locals(
&ctor.body,
&mut local_map,
&mut extra_locals,
param_count as u32,
);
let temp_local_idx = param_count as u32 + extra_locals;
let temp_i32_idx = temp_local_idx + 3;
let locals = vec![(extra_locals + 3, ValType::I64), (1, ValType::I32)];
let mut func = Function::new(locals);
let _rt = self.rt.as_ref().unwrap();
// Field initializers: class_set_field(this, field_name, value) via mem_call
let emit_field_inits = |func: &mut Function| {
for field in &class.fields {
let Some(init) = &field.init else { continue };
let mut ctx = FuncEmitCtx::new(self, &local_map, temp_local_idx, temp_i32_idx);
// A computed field is named by the key its class definition resolved
// into the hidden slot `field.name`.
if field.key_expr.is_some() {
let slot = Expr::String(field.name.clone());
ctx.emit_class_bridge(
func,
"class_init_computed_field",
&class.name,
&[&slot, &Expr::This, init],
);
func.instruction(&Instruction::Drop);
continue;
}
ctx.emit_frame_begin(func, 3);
// Compute base address (sp - 24) and save to temp_i32 local
let sp = self.nan_temp_global;
func.instruction(&Instruction::GlobalGet(sp));
func.instruction(&Instruction::I32Const(24));
func.instruction(&Instruction::I32Sub);
func.instruction(&Instruction::LocalSet(temp_i32_idx));
// Store this handle to slot 0
func.instruction(&Instruction::LocalGet(temp_i32_idx));
func.instruction(&Instruction::LocalGet(0)); // this
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
// Store field name to slot 1
let field_id = self
.string_map
.get(field.name.as_str())
.copied()
.unwrap_or(0);
let field_bits = (STRING_TAG << 48) | (field_id as u64);
func.instruction(&Instruction::LocalGet(temp_i32_idx));
func.instruction(&Instruction::I32Const(8));
func.instruction(&Instruction::I32Add);
func.instruction(&Instruction::I64Const(field_bits as i64));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
// Store value to slot 2
ctx.emit_store_arg(func, 2, init);
// Call via mem_call
ctx.emit_memcall_void(func, "class_set_field", 3);
}
};
// A derived class initializes its fields when `super()` returns, so the parent
// constructor sees none of them; a base class initializes them on entry. A
// `super()` nested below the top level falls back to entry.
let super_at = ctor
.body
.iter()
.position(|stmt| matches!(stmt, Stmt::Expr(Expr::SuperCall(_))));
if super_at.is_none() {
emit_field_inits(&mut func);
}
// Emit constructor body.
//
// Constructors are declared in func_section as `(this, ...params) -> i64`
// unconditionally (see mod.rs around line 1688). Pass `in_returning_func=true`
// so that any explicit `return;` / `return expr;` inside the constructor
// body properly leaves an i64 on the operand stack before the WASM `return`
// instruction. Without this, an early `return` produced a bare `return`
// with empty stack, failing V8 validation with
// "expected i64 but nothing on stack" (#1081 sibling instance, constructor case).
let mut ctx = FuncEmitCtx::new(self, &local_map, temp_local_idx, temp_i32_idx);
ctx.current_class = Some(class.name.clone());
ctx.this_local = Some(0);
ctx.emit_box_params(&mut func, &ctor.params);
for (index, stmt) in ctor.body.iter().enumerate() {
ctx.emit_stmt(&mut func, stmt, true);
if super_at == Some(index) {
emit_field_inits(&mut func);
}
}
// Fallthrough: return `this` as the constructor's result.
func.instruction(&Instruction::LocalGet(0));
func.instruction(&Instruction::End);
func
}
pub(super) fn compile_class_method(
&self,
class_name: &str,
method: &perry_hir::ir::Function,
) -> Function {
// Local 0 = this, params start at 1
let mut local_map = BTreeMap::new();
for (i, param) in method.params.iter().enumerate() {
local_map.insert(param.id, (i + 1) as u32);
}
let param_count = 1 + method.params.len();
let mut extra_locals = 0u32;
collect_param_locals(
&method.params,
&mut local_map,
&mut extra_locals,
param_count as u32,
);
collect_locals(
&method.body,
&mut local_map,
&mut extra_locals,
param_count as u32,
);
let temp_local_idx = param_count as u32 + extra_locals;
let temp_i32_idx = temp_local_idx + 3;
let locals = vec![(extra_locals + 3, ValType::I64), (1, ValType::I32)];
let mut func = Function::new(locals);
let _has_ret = method.body.iter().any(has_return);
let mut ctx = FuncEmitCtx::new(self, &local_map, temp_local_idx, temp_i32_idx);
ctx.current_class = Some(class_name.to_string());
ctx.this_local = Some(0);
ctx.emit_box_params(&mut func, &method.params);
for stmt in &method.body {
ctx.emit_stmt(&mut func, stmt, true); // methods always return f64
}
// Always push default return (method type is always -> f64)
func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64));
func.instruction(&Instruction::End);
func
}
}
impl<'a> FuncEmitCtx<'a> {
// emit_nan_safe_const removed - all values are i64 now, NaN canonicalization is not an issue.
/// Advance the sp and record the frame size for emit_store_arg.
pub(super) fn emit_frame_begin(&mut self, func: &mut Function, frame_size: u32) {
let sp = self.emitter.nan_temp_global;
self.frame_stack.push(self.current_frame_size);
self.current_frame_size = frame_size;
func.instruction(&Instruction::GlobalGet(sp));
func.instruction(&Instruction::I32Const((frame_size * 8) as i32));
func.instruction(&Instruction::I32Add);
func.instruction(&Instruction::GlobalSet(sp));
}
/// Compute memory address for a slot in the current frame.
/// Address = sp - (current_frame_size - slot) * 8
/// This works correctly across nested calls because sp was advanced by emit_frame_begin.
#[track_caller]
pub(super) fn emit_slot_addr(&self, func: &mut Function, slot: u32) {
debug_assert!(
slot < self.current_frame_size,
"slot {slot} lies outside the open frame of {} slots",
self.current_frame_size
);
let sp = self.emitter.nan_temp_global;
let offset_from_sp = (self.current_frame_size - slot) * 8;
func.instruction(&Instruction::GlobalGet(sp));
func.instruction(&Instruction::I32Const(offset_from_sp as i32));
func.instruction(&Instruction::I32Sub);
}
/// Store an expression's result to memory at the current frame's slot.
#[track_caller]
pub(super) fn emit_store_arg(&mut self, func: &mut Function, slot: u32, expr: &Expr) {
match expr {
Expr::String(s) => {
let string_id = self
.emitter
.string_map
.get(s.as_str())
.copied()
.unwrap_or(0);
let bits = (STRING_TAG << 48) | (string_id as u64);
self.emit_slot_addr(func, slot);
func.instruction(&Instruction::I64Const(bits as i64));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
_ => {
// Evaluate expression first, save to dedicated temp_store_local.
// Prevents slot address (i32) from sitting on stack during nested memcalls.
self.emit_expr(func, expr);
func.instruction(&Instruction::LocalSet(self.temp_store_local));
self.emit_slot_addr(func, slot);
func.instruction(&Instruction::LocalGet(self.temp_store_local));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
}
}
#[track_caller]
pub(super) fn emit_store_const(&self, func: &mut Function, slot: u32, val: f64) {
let bits = val.to_bits();
self.emit_slot_addr(func, slot);
func.instruction(&Instruction::I64Const(bits as i64));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
/// Emit a load of a HIR local by id. Top-level `let`s are stored in WASM globals
/// (not locals), so we must check `module_let_globals` before `local_map`. Falls
/// back to `TAG_UNDEFINED`. A boxed local is read through its cell.
pub(super) fn emit_local_or_global_get(&mut self, func: &mut Function, id: &LocalId) {
if self.scoped_temp_ids.contains(id) {
func.instruction(&Instruction::LocalGet(self.local_map[id]));
} else if let Some(&gidx) = self
.emitter
.module_let_globals
.get(&(self.emitter.current_mod_idx, *id))
{
func.instruction(&Instruction::GlobalGet(gidx));
} else if let Some(&idx) = self.local_map.get(id) {
func.instruction(&Instruction::LocalGet(idx));
if self.is_boxed(id) {
self.emit_box_call(func, "box_get");
}
} else {
func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64));
}
}
pub(super) fn is_boxed(&self, id: &LocalId) -> bool {
self.emitter
.boxed_locals
.contains(&(self.emitter.current_mod_idx, *id))
}
/// Calls a one-argument cell bridge on the value on the stack: `box_new(value)`
/// leaves a new cell, `box_get(cell)` its value.
pub(super) fn emit_box_call(&mut self, func: &mut Function, bridge: &str) {
func.instruction(&Instruction::LocalSet(self.temp_store_local));
self.emit_frame_begin(func, 1);
self.emit_slot_addr(func, 0);
func.instruction(&Instruction::LocalGet(self.temp_store_local));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
self.emit_memcall(func, bridge, 1);
}
/// Stores the value on the stack into the cell local `idx` holds, leaving the value.
pub(super) fn emit_box_set(&mut self, func: &mut Function, idx: u32) {
func.instruction(&Instruction::LocalSet(self.temp_store_local));
self.emit_frame_begin(func, 2);
for (slot, local) in [(0, idx), (1, self.temp_store_local)] {
self.emit_slot_addr(func, slot);
func.instruction(&Instruction::LocalGet(local));
func.instruction(&Instruction::I64Store(wasm_encoder::MemArg {
offset: 0,
align: 3,
memory_index: 0,
}));
}
self.emit_memcall(func, "box_set", 2);
}
/// Moves each boxed parameter's incoming value into a fresh cell.
pub(super) fn emit_box_params(&mut self, func: &mut Function, params: &[Param]) {
for param in params {
if let Some(&idx) = self.local_map.get(¶m.id) {
if self.is_boxed(¶m.id) {
func.instruction(&Instruction::LocalGet(idx));
self.emit_box_call(func, "box_new");
func.instruction(&Instruction::LocalSet(idx));
}
}
}
}
}