Lines
89.86 %
Functions
96.4 %
Branches
100 %
//! Lexical control-transfer bookkeeping shared by BLOCK / TAGBODY /
//! UNWIND-PROTECT codegen: `BlockLabel` / `TagFrame` / `UnwindFrame` and the
//! `CompileContext` push/pop/lookup methods over them.
//!
//! All three frame kinds record depths relative to the emitter compiling the
//! CURRENT function — a lambda/catch-each helper starts a fresh emitter at
//! block depth 0, so these stacks are reset (not carried over) by
//! `CompileContext::take_local_pool` / `restore_local_pool`, alongside the
//! local-pool state they already reset.
use anodized::spec;
use super::CompileContext;
use crate::ast::{Expr, WasmType};
use crate::compiler::join::Exit;
use crate::error::Result;
/// One active `(unwind-protect)` frame, live while its protected body
/// compiles. A non-local lexical exit — `(return-from)` / `(go)` whose
/// target lies *outside* this unwind-protect — must run this cleanup before
/// branching (Common-Lisp semantics), so the exit-site codegen walks the
/// frame stack and emits the cleanup of every crossed frame inline, then
/// `br`s. `threshold` is the `block_depth()` the unwind-protect sat at
/// (`parent_depth`); an exit whose target wasm-depth is `<= threshold`
/// leaves this frame and so triggers its cleanup. `cleanup` is the cleanup
/// forms' AST, recompiled for effect at each crossing exit (the normal /
/// exceptional convergence path emits its own copy independently).
#[derive(Debug, Clone)]
pub(in crate::compiler) struct UnwindFrame {
pub threshold: u32,
pub cleanup: Vec<Expr>,
}
/// One frame on the lexical BLOCK stack. `wasm_depth` is the
/// `FunctionEmitter::block_depth()` reading captured *after* the
/// matching `block` instruction was emitted, so a `(return-from name v)`
/// sees a stable br target across nested IF / DOLIST / DO frames inside
/// the body. The frame is popped when control leaves the BLOCK form.
///
/// The block's result type is discovered at emit time: each reachable
/// `(return-from name v)` compiled inside the body records `v`'s [`Exit`]
/// in `recorded_exits`. Because only *compiled* (reachable)
/// exits record — code stored as a value (quote / lambda / labels bodies,
/// discarded macro args) is never compiled in value position — the set is
/// exactly the live exits, with no syntactic pre-scan. `target` is the
/// reconciled result a second pass compiles every exit at.
pub(in crate::compiler) struct BlockLabel {
pub name: String,
pub wasm_depth: u32,
pub target: Option<WasmType>,
pub recorded_exits: Vec<Exit>,
/// One TAGBODY frame. Each tag in the body has a stable ordinal `pc` (its
/// position in the source order, base-zero) and a wasm-block depth captured
/// when emit reaches its segment. `(go tag)` resolves the named tag,
/// stores the next `pc` into `pc_local`, and branches to the dispatcher
/// `loop` so `br_table` re-enters at the right segment.
pub(in crate::compiler) struct TagFrame {
pub tags: Vec<TagEntry>,
pub pc_local: u32,
pub loop_depth: u32,
pub(in crate::compiler) struct TagEntry {
pub pc: u32,
/// The three frame stacks, as a rolled-back scope restores them: a trial
/// may record exits into an enclosing BLOCK or leave a frame pushed.
#[derive(Debug, Default)]
pub(in crate::compiler::context) struct FrameJournal {
block_labels: Vec<BlockLabel>,
hidden_labels: Vec<(usize, usize)>,
tag_frames: Vec<TagFrame>,
unwind_frames: Vec<UnwindFrame>,
impl CompileContext {
pub(in crate::compiler::context) fn frame_journal(&self) -> FrameJournal {
FrameJournal {
block_labels: self.block_labels.clone(),
hidden_labels: self.hidden_labels.clone(),
tag_frames: self.tag_frames.clone(),
unwind_frames: self.unwind_frames.clone(),
pub(in crate::compiler::context) fn take_frames(&mut self) -> FrameJournal {
block_labels: std::mem::take(&mut self.block_labels),
hidden_labels: std::mem::take(&mut self.hidden_labels),
tag_frames: std::mem::take(&mut self.tag_frames),
unwind_frames: std::mem::take(&mut self.unwind_frames),
pub(in crate::compiler::context) fn restore_frames(&mut self, journal: FrameJournal) {
let FrameJournal {
block_labels,
hidden_labels,
tag_frames,
unwind_frames,
} = journal;
self.block_labels = block_labels;
self.hidden_labels = hidden_labels;
self.tag_frames = tag_frames;
self.unwind_frames = unwind_frames;
/// Push a lexical BLOCK frame so a `(return-from name v)` walking
/// the stack from innermost to outermost can resolve the wasm-block
/// it refers to. `wasm_depth` is the emitter's depth the body is
/// compiled at (the depth the `block` frame will occupy once spliced).
pub(in crate::compiler) fn push_block_label(
&mut self,
name: &str,
wasm_depth: u32,
target: Option<WasmType>,
) {
self.block_labels.push(BlockLabel {
name: name.to_string(),
wasm_depth,
target,
recorded_exits: Vec::new(),
});
/// Pop the named BLOCK frame, returning the exits its reachable
/// `(return-from)`s recorded during body emit. The caller reconciles them
/// (with the fall-through tail, if any) into the block's result type.
pub(in crate::compiler) fn pop_block_label(&mut self, name: &str) -> Result<Vec<Exit>> {
match self.block_labels.pop() {
Some(top) if top.name == name => Ok(top.recorded_exits),
Some(top) => Err(crate::error::Error::Compile(format!(
"BLOCK label stack imbalance: expected '{name}' on top, found '{}'",
top.name
))),
None => Err(crate::error::Error::Compile(format!(
"BLOCK label stack imbalance: expected '{name}' on top, found empty stack"
pub(in crate::compiler) fn lookup_block_label(&self, name: &str) -> Option<&BlockLabel> {
let at = self.visible_label(name)?;
self.block_labels.get(at)
/// The innermost BLOCK label named `name` that is not hidden from the
/// current inlined body.
fn visible_label(&self, name: &str) -> Option<usize> {
(0..self.block_labels.len())
.rev()
.find(|&at| !self.is_hidden_label(at) && self.block_labels[at].name == name)
fn is_hidden_label(&self, at: usize) -> bool {
self.hidden_labels
.iter()
.any(|&(from, to)| (from..to).contains(&at))
/// Whether a BLOCK named `name` is open in the code this function body was
/// written in, where a `RETURN-FROM` inside it cannot reach it.
pub(in crate::compiler) fn block_is_out_of_reach(&self, name: &str) -> bool {
self.outer_labels.iter().any(|outer| outer == name)
/// Opens a function body: the block names open here are out of its reach.
/// Returns the names that were out of reach of the code around it.
pub(in crate::compiler::context) fn hide_labels_from_body(&mut self) -> Vec<String> {
let before = self.outer_labels.clone();
// A label hidden from an inlined body was opened after its function was
// written: it does not enclose a lambda written inside that function.
let names: Vec<String> = (0..self.block_labels.len())
.filter(|&at| !self.is_hidden_label(at))
.map(|at| self.block_labels[at].name.clone())
.collect();
self.outer_labels.extend(names);
before
/// A global function's body is compiled where it is called, not where it
/// was written: no block of the call site encloses it.
pub(crate) fn forget_outer_labels(&mut self) {
self.outer_labels.clear();
/// How many BLOCK labels are open: a function defined here sees them.
pub(in crate::compiler) fn block_label_count(&self) -> usize {
self.block_labels.len()
/// Runs `body` (an inlined function's body) with the labels opened since
/// its definition, `from` onward, hidden; restored on every path.
pub(in crate::compiler) fn with_hidden_labels<T>(
from: usize,
body: impl FnOnce(&mut Self) -> crate::error::Result<T>,
) -> crate::error::Result<T> {
self.hidden_labels.push((from, self.block_labels.len()));
let result = body(self);
self.hidden_labels.pop();
result
/// Record a reachable `(return-from name v)` exit into the
/// innermost matching BLOCK frame, so emit-time discovery can reconcile
/// the block's result type from exactly the exits that compile.
pub(in crate::compiler) fn record_block_exit(&mut self, name: &str, exit: Exit) {
if let Some(frame) = self
.visible_label(name)
.and_then(|at| self.block_labels.get_mut(at))
{
frame.recorded_exits.push(exit);
/// Push an `(unwind-protect)` frame so a non-local exit crossing it runs
/// its cleanup. `threshold` is the unwind-protect's `parent_depth`; an
/// exit to a wasm-depth `<= threshold` leaves the frame.
#[spec(requires: self.unwind_frames.last().is_none_or(|top| top.threshold <= threshold))]
pub(in crate::compiler) fn push_unwind_frame(&mut self, threshold: u32, cleanup: Vec<Expr>) {
self.unwind_frames.push(UnwindFrame { threshold, cleanup });
pub(in crate::compiler) fn pop_unwind_frame(&mut self) -> Result<()> {
match self.unwind_frames.pop() {
Some(_) => Ok(()),
None => Err(crate::error::Error::Compile(
"UNWIND-PROTECT frame stack imbalance: pop on empty stack".to_string(),
)),
/// Pop the innermost active unwind-protect frame if an exit to
/// `target_depth` crosses it, i.e. the exit lands at or above (shallower
/// than) its `threshold`. Frames are popped one at a time so the OUTER
/// crossed frames stay active while the popped frame's cleanup is
/// compiled: an exit inside that cleanup then crosses them itself. The
/// caller MUST push the popped frames back with
/// [`Self::restore_unwind_frames`], so sibling branches still see them.
#[spec(
maintains: self.unwind_frames.is_sorted_by_key(|frame| frame.threshold),
captures: before = self.unwind_frames.len(),
ensures: |ref output| [
self.unwind_frames.len() + usize::from(output.is_some()) == before,
output.iter().all(|frame| frame.threshold >= target_depth),
],
)]
pub(in crate::compiler) fn pop_unwind_frame_crossing(
target_depth: u32,
) -> Option<UnwindFrame> {
let crossed = self
.unwind_frames
.last()
.is_some_and(|frame| target_depth <= frame.threshold);
crossed.then(|| self.unwind_frames.pop()).flatten()
/// Restore frames removed by [`Self::pop_unwind_frame_crossing`], in
/// their original (bottom-to-top) order.
requires: [
frames.is_sorted_by_key(|frame| frame.threshold),
self.unwind_frames
.zip(frames.first())
.is_none_or(|(top, first)| top.threshold <= first.threshold),
captures: expected = self.unwind_frames.len() + frames.len(),
ensures: self.unwind_frames.len() == expected,
pub(in crate::compiler) fn restore_unwind_frames(&mut self, frames: Vec<UnwindFrame>) {
self.unwind_frames.extend(frames);
/// Push a TAGBODY frame so `(go tag)` walking the stack from innermost
/// outward can resolve the wasm-loop it has to jump back to. Returned
/// after the matching `loop` instruction is emitted (so `loop_depth`
/// records the emitter's depth at that moment).
pub(in crate::compiler) fn push_tag_frame(&mut self, frame: TagFrame) {
self.tag_frames.push(frame);
pub(in crate::compiler) fn pop_tag_frame(&mut self) -> Result<()> {
match self.tag_frames.pop() {
"TAGBODY frame stack imbalance: pop on empty stack".to_string(),
pub(in crate::compiler) fn lookup_tag(&self, name: &str) -> Option<(&TagFrame, u32)> {
for frame in self.tag_frames.iter().rev() {
if let Some(entry) = frame.tags.iter().find(|t| t.name == name) {
return Some((frame, entry.pc));
None