Lines
95.53 %
Functions
90.63 %
Branches
100 %
mod frame;
mod instr;
use wasm_encoder::{BlockType, Catch, Encode, Function, Instruction, ValType};
use crate::error::{Error, Result};
use frame::{FrameKind, ValidationFrame};
pub struct FunctionEmitter {
bytes: Vec<u8>,
block_depth: u32,
/// The `block_depth` this emitter started at — 0 for [`Self::new`], the
/// caller's depth for [`Self::new_seeded`]. A scratch buffer that is
/// internally balanced (every opened frame closed) ends back at this
/// same depth; [`Self::splice`] checks that before trusting anything
/// else about the scratch.
seeded_depth: u32,
frame: ValidationFrame,
/// `bytes.len()` right after the last `unreachable` / `throw` / `br` /
/// `br_table`: the one position known to hold no concrete operand.
polymorphic_at: Option<usize>,
}
impl FunctionEmitter {
pub fn new() -> Self {
Self {
bytes: Vec::new(),
block_depth: 0,
seeded_depth: 0,
frame: ValidationFrame::new(),
polymorphic_at: None,
/// A fresh scratch emitter whose `block_depth` is pre-seeded to
/// `depth`, as if it were already nested that many structured-control
/// frames deep. Used by BLOCK emit-time exit discovery: the body is
/// compiled into a scratch buffer seeded at the depth the block's
/// frame will occupy, so every relative `br` (RETURN-FROM / GO,
/// including exits to outer blocks) computes the same target it will
/// need once the bytes are spliced into the parent after the parent
/// opens the block. Pair with [`Self::splice`].
pub fn new_seeded(depth: u32) -> Self {
block_depth: depth,
seeded_depth: depth,
/// Borrow the raw instruction bytes for splicing without consuming the
/// emitter (e.g. handler-case keeps several clause scratches and splices
/// each in turn).
pub fn bytes_ref(&self) -> &[u8] {
&self.bytes
/// Whether this emitter's simulated position is currently reachable —
/// i.e. whether an instruction placed here would actually run.
pub fn is_reachable(&self) -> bool {
self.frame.is_reachable()
/// Whether control can reach the next instruction by the frames'
/// end-reachability rules; never true where [`Self::is_reachable`] is false.
pub fn is_live(&self) -> bool {
self.frame.is_live()
/// Reports a type error unless an operand already exited (`return-from`,
/// `error`): the value it would mistype never exists, so the program is
/// well-typed and the rest is dead code.
pub fn reject_if_live(&self, err: Error) -> Result<()> {
if self.is_reachable() {
Err(err)
} else {
Ok(())
/// Appends `source`'s raw instruction bytes and merges its simulated
/// final reachability into `self` — never a caller's syntactic belief
/// about either. A caller that thinks an arm "diverges" is wrong exactly
/// often enough to matter (`form_diverges` doesn't see through AND/OR
/// into a tail `ERROR`, doesn't know GO, …); reading the scratch's own
/// simulator state instead is the fix, not a declared/actual comparison
/// that such a belief could still get backwards.
///
/// Before trusting that reachability, checks that `source` is internally
/// balanced — every `block_start` / `if_block` / `try_table` it opened
/// has a matching `block_end` — and ends at the same `block_depth` it
/// was seeded with. Both are cheap, unconditional emitter-bug guards: a
/// scratch that fails either has a real mismatched-frame bug, independent
/// of whatever any caller believes about divergence.
pub fn splice(&mut self, source: &FunctionEmitter) -> Result<()> {
if !source.frame.is_balanced() {
return Err(Error::Compile(
"internal: splice source has an unclosed structured-control frame".to_string(),
));
if source.block_depth != source.seeded_depth {
return Err(Error::Compile(format!(
"internal: splice source ended at block depth {} but was seeded at {}",
source.block_depth, source.seeded_depth
)));
self.bytes.extend_from_slice(source.bytes_ref());
self.frame.merge_spliced(&source.frame);
if source.ends_polymorphic() {
self.mark_polymorphic();
/// Runs `compile` once on a live scratch seeded at this depth and splices
/// it in; answers its value and whether the scratch ends reachable. Dead
/// code compiled this way is typed by what it pushes when reached.
pub fn on_live_scratch<T>(
&mut self,
compile: impl FnOnce(&mut FunctionEmitter) -> Result<T>,
) -> Result<(T, bool)> {
let mut scratch = FunctionEmitter::new_seeded(self.block_depth);
let value = compile(&mut scratch)?;
self.splice(&scratch)?;
Ok((value, scratch.is_reachable()))
/// Current wasm structured-control depth — the number of open
/// `block` / `loop` / `if` frames around the next instruction. Used
/// by labelled exits (BLOCK / RETURN-FROM, TAGBODY / GO) to compute
/// the relative `br` depth.
pub fn block_depth(&self) -> u32 {
self.block_depth
/// The count of locals the emitted code addresses: one past the highest
/// index any `local.get` / `local.set` / `local.tee` names.
pub fn locals_addressed(&self) -> Result<u32> {
use wasmparser::{BinaryReader, Operator, OperatorsReader};
let mut ops = OperatorsReader::new(BinaryReader::new(&self.bytes, 0));
let mut addressed = 0;
while !ops.eof() {
let operator = ops
.read()
.map_err(|e| Error::Compile(format!("internal: unreadable emitted code: {e}")))?;
if let Operator::LocalGet { local_index }
| Operator::LocalSet { local_index }
| Operator::LocalTee { local_index } = operator
{
addressed = addressed.max(local_index.saturating_add(1));
Ok(addressed)
/// Emits the terminating `End` and finishes the function. The ONLY way
/// to close a `FunctionEmitter`'s outermost scope — there is no public
/// raw `end()` — so a structured-control frame this emitter opened and
/// never closed (the exact class of bug `create_tag.rs`'s
/// `emit.end()` instead of `emit.block_end()` produced: valid bytes,
/// but a `block_depth` / simulator desync a later splice could act on)
/// is caught HERE, structurally, rather than depending on every call
/// site remembering to check balance before finishing.
pub fn finish(mut self, locals: &[(u32, ValType)]) -> Result<Function> {
if !self.frame.is_balanced() || self.block_depth != self.seeded_depth {
"internal: finish() called with an unclosed structured-control frame".to_string(),
self.seal_residue();
Instruction::End.encode(&mut self.bytes);
let mut func = Function::new(locals.iter().copied());
func.raw(self.bytes);
Ok(func)
pub fn if_block(&mut self, block_type: BlockType) {
Instruction::If(block_type).encode(&mut self.bytes);
self.block_depth += 1;
self.frame.push_ctrl(FrameKind::If);
pub fn else_block(&mut self) {
Instruction::Else.encode(&mut self.bytes);
self.frame.reset_for_else();
pub fn block_start(&mut self) {
Instruction::Block(BlockType::Empty).encode(&mut self.bytes);
self.frame.push_ctrl(FrameKind::Block);
/// Open a wasm `block` whose result type is known up-front. Used
/// by BLOCK / RETURN-FROM where the lexically-named block carries
/// a value-yielding result.
pub fn block_start_typed(&mut self, block_type: BlockType) {
Instruction::Block(block_type).encode(&mut self.bytes);
pub fn loop_start(&mut self) {
Instruction::Loop(BlockType::Empty).encode(&mut self.bytes);
self.frame.push_ctrl(FrameKind::Loop);
/// Closes the innermost open structured-control frame. Errors — rather
/// than silently absorbing the underflow with `saturating_sub` — when
/// `block_depth` is already zero: a mismatched `block_start` /
/// `block_end` pair is a compiler bug, and letting it wrap silently would
/// ship wasm with wrong `br` depths instead of surfacing the mistake.
/// Seals the position after `end` with `unreachable` when the closed
/// frame is not end-reachable but the validator still is: the one place
/// a dead fallthrough is made polymorphic. A dead residue before the
/// `end` is sealed first, as for `else`.
pub fn block_end(&mut self) -> Result<()> {
let depth = self.block_depth.checked_sub(1).ok_or_else(|| {
Error::Compile("internal: block_end() called with no open block frame".to_string())
})?;
self.frame.pop_ctrl()?;
self.block_depth = depth;
if !self.is_live() && self.is_reachable() {
self.unreachable();
pub fn br(&mut self, depth: u32) {
Instruction::Br(depth).encode(&mut self.bytes);
self.frame.mark_targets([depth]);
self.frame.mark_unreachable();
pub fn br_if(&mut self, depth: u32) {
Instruction::BrIf(depth).encode(&mut self.bytes);
/// Indexed branch — pops an i32 selector, jumps to `targets[i]` when the
/// selector is in range, else `default`. Used by TAGBODY / GO to dispatch
/// to the segment matching the current pc.
pub fn br_table(&mut self, targets: &[u32], default: u32) {
Instruction::BrTable(std::borrow::Cow::Borrowed(targets), default).encode(&mut self.bytes);
self.frame
.mark_targets(targets.iter().copied().chain([default]));
/// Emit `unreachable`. Used after a `br` out of a value-yielding
/// block where the validator still expects a typed value on the
/// stack but control will never reach the next instruction —
/// wasm's stack-polymorphism after `unreachable` keeps the
/// type-check happy without forcing us to materialize a real value.
pub fn unreachable(&mut self) {
Instruction::Unreachable.encode(&mut self.bytes);
/// Open a `try_table` frame (exception-handling proposal). `catches`
/// routes matching `throw`s to a relative `br` depth resolved against
/// the open blocks. Opens one structured-control frame like `block`,
/// so `block_depth` increments — keeping `(return-from name v)` and
/// `(go tag)` relative-`br` math correct across a wrapped body. Pair
/// with [`Self::block_end`]. Used by the Tier 3 boundary wrapper and
/// by `(handler-case)` / `(unwind-protect)` (ADR-0026).
pub fn try_table(&mut self, block_type: BlockType, catches: &[Catch]) {
Instruction::TryTable(block_type, std::borrow::Cow::Borrowed(catches))
.encode(&mut self.bytes);
self.frame.mark_targets(catches.iter().map(catch_label));
self.frame.push_ctrl(FrameKind::TryTable);
/// Throw the exception with the given tag index, consuming one stack
/// value per tag parameter (the `$nomi_error` tag takes a single
/// `(ref null $nomi_condition)`). Control never returns past a
/// `throw`, so the stack goes polymorphic — value-position callers
/// pair this with a trailing type the validator accepts.
pub fn throw(&mut self, tag_idx: u32) {
Instruction::Throw(tag_idx).encode(&mut self.bytes);
fn mark_polymorphic(&mut self) {
self.polymorphic_at = Some(self.bytes.len());
fn ends_polymorphic(&self) -> bool {
self.polymorphic_at == Some(self.bytes.len())
/// Seals dead code before `else` / `end`: code compiled past a `throw` or
/// `br` (`(progn (error …) 1)`) pushes a concrete operand that the
/// validator's polymorphic stack does not absorb, and the frame boundary
/// would type-check it against the block's result.
fn seal_residue(&mut self) {
if !self.is_live() && !self.ends_polymorphic() {
const fn catch_label(catch: &Catch) -> u32 {
match *catch {
Catch::One { label, .. }
| Catch::OneRef { label, .. }
| Catch::All { label }
| Catch::AllRef { label } => label,
impl Default for FunctionEmitter {
fn default() -> Self {
Self::new()
#[cfg(test)]
#[path = "emit_tests.rs"]
mod tests;
#[path = "splice_tests.rs"]
mod splice_tests;
#[path = "frame_live_tests.rs"]
mod frame_live_tests;
#[path = "seal_tests.rs"]
mod seal_tests;
#[path = "residue_seal_tests.rs"]
mod residue_seal_tests;