Lines
95.51 %
Functions
92.5 %
Branches
100 %
//! A wasm validation-algorithm simulator (ADR-0034 / plan 0011 Phase 0).
//!
//! Mirrors the CONTROL-FLOW half of the algorithm in the Wasm spec's
//! validation appendix: a stack of control frames, each remembering
//! whether it has gone "unreachable" (so code after a `br` /
//! `unreachable` / `throw` type-checks polymorphically instead of being
//! held to the real operand count). [`FunctionEmitter`](super::FunctionEmitter)
//! keeps one of these alongside its raw byte buffer and updates it on
//! every structured-control instruction it emits, so
//! [`FunctionEmitter::splice`](super::FunctionEmitter::splice) can read a
//! scratch buffer's own simulated final reachability — never a caller's
//! syntactic belief about it — and merge that into the parent.
//! Deliberately NOT modelled: the operand-stack half of the algorithm (per-
//! instruction push/pop against real value types). `FunctionEmitter` has no
//! type registry of its own (struct field counts, array element types, …
//! live on `CompileContext`), so a fully general per-instruction operand-
//! count model isn't wireable into the real `instr.rs` emit methods without
//! guessing arities this layer can't see. An earlier version of this module
//! carried a `height: usize` field plus `#[cfg(test)]` `push_val` / `pop_val`
//! methods to pin that algorithm's semantics in isolation, ready for a later
//! phase to wire in — but nothing in production ever called them (they were
//! `#[cfg(test)]`-only), so per CLAUDE.md's no-unneeded-code rule they were
//! removed rather than kept as an untested promise. Per-instruction
//! stack-effect checking (the plan's "a splice whose recorded stack effect
//! disagrees is Error::Compile" acceptance bullet) is not built: it needed
//! the typed lowering plan 0014 cut at Branch A (slice 4.9). Instead,
//! reachability — proven to matter by two real bugs this phase's own review
//! caught (`compile_runtime_if` / `handler_case.rs::emit_dispatch` splicing
//! a scratch whose declared belief disagreed with what it actually
//! simulated) — is what this simulator checks.
use std::collections::BTreeSet;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FrameKind {
Block,
Loop,
If,
TryTable,
}
#[derive(Debug, Clone, Copy)]
struct CtrlFrame {
/// True once a `br` / `br_table` / `throw` / `unreachable` has run
/// inside this frame (and not yet reset by an intervening `else`).
unreachable: bool,
kind: FrameKind,
/// A live branch or `try_table` catch label names this frame's `end`.
end_targeted: bool,
/// The `live` bit when the frame opened.
entry_live: bool,
/// For `If`: `None` until `else`, then whether the `then` arm fell through.
then_fell_through: Option<bool>,
impl CtrlFrame {
const fn new(kind: FrameKind, entry_live: bool) -> Self {
Self {
unreachable: false,
kind,
end_targeted: false,
entry_live,
then_fell_through: None,
/// Whether control can reach the instruction after this frame's `end`,
/// given the `live` bit at the end of its body.
const fn end_reachable(&self, live: bool) -> bool {
match (self.kind, self.then_fell_through) {
(FrameKind::Loop, _) => live,
(FrameKind::If, Some(then)) => then || live || self.end_targeted,
(FrameKind::If, None) => live || self.entry_live || self.end_targeted,
(FrameKind::Block | FrameKind::TryTable, _) => live || self.end_targeted,
/// The simulator's whole state: `base` is the function's top-level
/// instruction sequence — never popped, so no accessor can fail — plus one
/// `nested` frame per currently-open `block` / `loop` / `if` / `try_table`.
/// `live` is the semantic reachability bit: unlike the validator's
/// `unreachable` flag it is not reset by `end`, so after a `pop_ctrl` it is
/// the closed frame's end-reachability.
#[derive(Debug, Clone)]
pub(crate) struct ValidationFrame {
base: CtrlFrame,
nested: Vec<CtrlFrame>,
live: bool,
/// Parent-relative depths of live branches that leave this emitter; a
/// set, since a repeated depth names the same parent frame.
exits: BTreeSet<usize>,
impl ValidationFrame {
pub(crate) const fn new() -> Self {
base: CtrlFrame::new(FrameKind::Block, true),
nested: Vec::new(),
live: true,
exits: BTreeSet::new(),
/// Whether every `push_ctrl` has been matched by a `pop_ctrl` — no
/// structured-control frame is left open. A scratch buffer that fails
/// this is a real emitter bug (a `block_start` / `if_block` / …
/// without its closing `block_end`), independent of and cheaper than
/// reachability.
pub(crate) fn is_balanced(&self) -> bool {
self.nested.is_empty()
fn top(&self) -> CtrlFrame {
*self.nested.last().unwrap_or(&self.base)
fn top_mut(&mut self) -> &mut CtrlFrame {
self.nested.last_mut().unwrap_or(&mut self.base)
/// Opens a new control frame (`block` / `loop` / `if` / `try_table`),
/// starting reachable regardless of the enclosing frame's own state —
/// this is what the wasm validation algorithm's `push_ctrl` does
/// (`unreachable` is always seeded `false` on entry), not an
/// approximation of it: dead code nested inside other dead code is
/// still validated strictly, with its OWN polymorphic base starting
/// only once something inside IT marks it unreachable in turn. `live`
/// is inherited, not reset.
pub(crate) fn push_ctrl(&mut self, kind: FrameKind) {
self.nested.push(CtrlFrame::new(kind, self.live));
/// Closes the innermost control frame. The now-discarded frame's own
/// `unreachable` flag is NOT inherited by the parent: falling off a
/// structured `end` always returns to whatever reachability the
/// parent already had when the frame was opened — that is exactly
/// the "frame state after `end`" the wasm validation algorithm
/// defines, independent of whether a `br` happened to target this
/// frame along the way. `live` becomes the closed frame's
/// end-reachability.
pub(crate) fn pop_ctrl(&mut self) -> Result<()> {
let frame = self.nested.pop().ok_or_else(|| {
Error::Compile("internal: pop_ctrl() called with no open control frame".to_string())
})?;
self.live = frame.end_reachable(self.live);
Ok(())
/// Marks the innermost control frame unreachable — the effect of `br` /
/// `br_table` / `throw` / `unreachable` / `return`.
pub(crate) fn mark_unreachable(&mut self) {
self.top_mut().unreachable = true;
self.live = false;
/// Records that a live branch (or catch label) to each relative `depth`
/// names that frame's `end`. A loop's label is its start, so it is not
/// marked; a depth beyond the open frames leaves this emitter and goes to
/// the summary.
pub(crate) fn mark_targets(&mut self, depths: impl IntoIterator<Item = u32>) {
if !self.live {
return;
for depth in depths {
self.mark_target(usize::try_from(depth).unwrap_or(usize::MAX));
fn mark_target(&mut self, depth: usize) {
let open = self.nested.len();
match self.nested.iter_mut().rev().nth(depth) {
Some(frame) if frame.kind != FrameKind::Loop => frame.end_targeted = true,
Some(_) => {}
None => {
if let Some(outside) = depth.checked_sub(open) {
self.exits.insert(outside);
/// Re-opens the current `if` frame's `then` arm as a fresh `else` arm:
/// resets reachability, exactly as opening a sibling branch would.
pub(crate) fn reset_for_else(&mut self) {
let live = self.live;
let top = self.top_mut();
top.unreachable = false;
top.then_fell_through = Some(live);
self.live = top.entry_live;
/// Merges a balanced scratch's final state: dead if either side is. The
/// scratch's exits are applied to this emitter's frames, or re-exported
/// when they lie beyond them; a splice into dead code contributes none.
pub(crate) fn merge_spliced(&mut self, source: &Self) {
if self.live {
for &exit in &source.exits {
self.mark_target(exit);
if !source.is_reachable() {
self.mark_unreachable();
self.live &= source.is_live();
/// True unless the innermost frame is unreachable — i.e. whether an
/// instruction placed here would actually run.
pub(crate) fn is_reachable(&self) -> bool {
!self.top().unreachable
/// Whether control can reach the next instruction by the end-reachability
/// rules; never true where [`Self::is_reachable`] is false.
pub(crate) const fn is_live(&self) -> bool {
self.live
impl Default for ValidationFrame {
fn default() -> Self {
Self::new()
#[cfg(test)]
#[path = "frame_tests.rs"]
mod tests;
#[path = "summary_tests.rs"]
mod summary_tests;