1
//! A wasm validation-algorithm simulator (ADR-0034 / plan 0011 Phase 0).
2
//!
3
//! Mirrors the CONTROL-FLOW half of the algorithm in the Wasm spec's
4
//! validation appendix: a stack of control frames, each remembering
5
//! whether it has gone "unreachable" (so code after a `br` /
6
//! `unreachable` / `throw` type-checks polymorphically instead of being
7
//! held to the real operand count). [`FunctionEmitter`](super::FunctionEmitter)
8
//! keeps one of these alongside its raw byte buffer and updates it on
9
//! every structured-control instruction it emits, so
10
//! [`FunctionEmitter::splice`](super::FunctionEmitter::splice) can read a
11
//! scratch buffer's own simulated final reachability — never a caller's
12
//! syntactic belief about it — and merge that into the parent.
13
//!
14
//! Deliberately NOT modelled: the operand-stack half of the algorithm (per-
15
//! instruction push/pop against real value types). `FunctionEmitter` has no
16
//! type registry of its own (struct field counts, array element types, …
17
//! live on `CompileContext`), so a fully general per-instruction operand-
18
//! count model isn't wireable into the real `instr.rs` emit methods without
19
//! guessing arities this layer can't see. An earlier version of this module
20
//! carried a `height: usize` field plus `#[cfg(test)]` `push_val` / `pop_val`
21
//! methods to pin that algorithm's semantics in isolation, ready for a later
22
//! phase to wire in — but nothing in production ever called them (they were
23
//! `#[cfg(test)]`-only), so per CLAUDE.md's no-unneeded-code rule they were
24
//! removed rather than kept as an untested promise. Per-instruction
25
//! stack-effect checking (the plan's "a splice whose recorded stack effect
26
//! disagrees is Error::Compile" acceptance bullet) is not built: it needed
27
//! the typed lowering plan 0014 cut at Branch A (slice 4.9). Instead,
28
//! reachability — proven to matter by two real bugs this phase's own review
29
//! caught (`compile_runtime_if` / `handler_case.rs::emit_dispatch` splicing
30
//! a scratch whose declared belief disagreed with what it actually
31
//! simulated) — is what this simulator checks.
32

            
33
use std::collections::BTreeSet;
34

            
35
use crate::error::{Error, Result};
36

            
37
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38
pub(crate) enum FrameKind {
39
    Block,
40
    Loop,
41
    If,
42
    TryTable,
43
}
44

            
45
#[derive(Debug, Clone, Copy)]
46
struct CtrlFrame {
47
    /// True once a `br` / `br_table` / `throw` / `unreachable` has run
48
    /// inside this frame (and not yet reset by an intervening `else`).
49
    unreachable: bool,
50
    kind: FrameKind,
51
    /// A live branch or `try_table` catch label names this frame's `end`.
52
    end_targeted: bool,
53
    /// The `live` bit when the frame opened.
54
    entry_live: bool,
55
    /// For `If`: `None` until `else`, then whether the `then` arm fell through.
56
    then_fell_through: Option<bool>,
57
}
58

            
59
impl CtrlFrame {
60
42605596
    const fn new(kind: FrameKind, entry_live: bool) -> Self {
61
42605596
        Self {
62
42605596
            unreachable: false,
63
42605596
            kind,
64
42605596
            end_targeted: false,
65
42605596
            entry_live,
66
42605596
            then_fell_through: None,
67
42605596
        }
68
42605596
    }
69

            
70
    /// Whether control can reach the instruction after this frame's `end`,
71
    /// given the `live` bit at the end of its body.
72
29317272
    const fn end_reachable(&self, live: bool) -> bool {
73
29317272
        match (self.kind, self.then_fell_through) {
74
2398456
            (FrameKind::Loop, _) => live,
75
5319507
            (FrameKind::If, Some(then)) => then || live || self.end_targeted,
76
12312332
            (FrameKind::If, None) => live || self.entry_live || self.end_targeted,
77
9286977
            (FrameKind::Block | FrameKind::TryTable, _) => live || self.end_targeted,
78
        }
79
29317272
    }
80
}
81

            
82
/// The simulator's whole state: `base` is the function's top-level
83
/// instruction sequence — never popped, so no accessor can fail — plus one
84
/// `nested` frame per currently-open `block` / `loop` / `if` / `try_table`.
85
/// `live` is the semantic reachability bit: unlike the validator's
86
/// `unreachable` flag it is not reset by `end`, so after a `pop_ctrl` it is
87
/// the closed frame's end-reachability.
88
#[derive(Debug, Clone)]
89
pub(crate) struct ValidationFrame {
90
    base: CtrlFrame,
91
    nested: Vec<CtrlFrame>,
92
    live: bool,
93
    /// Parent-relative depths of live branches that leave this emitter; a
94
    /// set, since a repeated depth names the same parent frame.
95
    exits: BTreeSet<usize>,
96
}
97

            
98
impl ValidationFrame {
99
12622964
    pub(crate) const fn new() -> Self {
100
12622964
        Self {
101
12622964
            base: CtrlFrame::new(FrameKind::Block, true),
102
12622964
            nested: Vec::new(),
103
12622964
            live: true,
104
12622964
            exits: BTreeSet::new(),
105
12622964
        }
106
12622964
    }
107

            
108
    /// Whether every `push_ctrl` has been matched by a `pop_ctrl` — no
109
    /// structured-control frame is left open. A scratch buffer that fails
110
    /// this is a real emitter bug (a `block_start` / `if_block` / …
111
    /// without its closing `block_end`), independent of and cheaper than
112
    /// reachability.
113
12233142
    pub(crate) fn is_balanced(&self) -> bool {
114
12233142
        self.nested.is_empty()
115
12233142
    }
116

            
117
13964541
    fn top(&self) -> CtrlFrame {
118
13964541
        *self.nested.last().unwrap_or(&self.base)
119
13964541
    }
120

            
121
25274000
    fn top_mut(&mut self) -> &mut CtrlFrame {
122
25274000
        self.nested.last_mut().unwrap_or(&mut self.base)
123
25274000
    }
124

            
125
    /// Opens a new control frame (`block` / `loop` / `if` / `try_table`),
126
    /// starting reachable regardless of the enclosing frame's own state —
127
    /// this is what the wasm validation algorithm's `push_ctrl` does
128
    /// (`unreachable` is always seeded `false` on entry), not an
129
    /// approximation of it: dead code nested inside other dead code is
130
    /// still validated strictly, with its OWN polymorphic base starting
131
    /// only once something inside IT marks it unreachable in turn. `live`
132
    /// is inherited, not reset.
133
29982632
    pub(crate) fn push_ctrl(&mut self, kind: FrameKind) {
134
29982632
        self.nested.push(CtrlFrame::new(kind, self.live));
135
29982632
    }
136

            
137
    /// Closes the innermost control frame. The now-discarded frame's own
138
    /// `unreachable` flag is NOT inherited by the parent: falling off a
139
    /// structured `end` always returns to whatever reachability the
140
    /// parent already had when the frame was opened — that is exactly
141
    /// the "frame state after `end`" the wasm validation algorithm
142
    /// defines, independent of whether a `br` happened to target this
143
    /// frame along the way. `live` becomes the closed frame's
144
    /// end-reachability.
145
29317273
    pub(crate) fn pop_ctrl(&mut self) -> Result<()> {
146
29317273
        let frame = self.nested.pop().ok_or_else(|| {
147
1
            Error::Compile("internal: pop_ctrl() called with no open control frame".to_string())
148
1
        })?;
149
29317272
        self.live = frame.end_reachable(self.live);
150
29317272
        Ok(())
151
29317273
    }
152

            
153
    /// Marks the innermost control frame unreachable — the effect of `br` /
154
    /// `br_table` / `throw` / `unreachable` / `return`.
155
19954281
    pub(crate) fn mark_unreachable(&mut self) {
156
19954281
        self.top_mut().unreachable = true;
157
19954281
        self.live = false;
158
19954281
    }
159

            
160
    /// Records that a live branch (or catch label) to each relative `depth`
161
    /// names that frame's `end`. A loop's label is its start, so it is not
162
    /// marked; a depth beyond the open frames leaves this emitter and goes to
163
    /// the summary.
164
12046615
    pub(crate) fn mark_targets(&mut self, depths: impl IntoIterator<Item = u32>) {
165
12046615
        if !self.live {
166
68423
            return;
167
11978192
        }
168
11978192
        for depth in depths {
169
11998800
            self.mark_target(usize::try_from(depth).unwrap_or(usize::MAX));
170
        }
171
12046615
    }
172

            
173
12113972
    fn mark_target(&mut self, depth: usize) {
174
12113972
        let open = self.nested.len();
175
12113972
        match self.nested.iter_mut().rev().nth(depth) {
176
11939293
            Some(frame) if frame.kind != FrameKind::Loop => frame.end_targeted = true,
177
2569581
            Some(_) => {}
178
            None => {
179
174679
                if let Some(outside) = depth.checked_sub(open) {
180
174679
                    self.exits.insert(outside);
181
                }
182
            }
183
        }
184
12113972
    }
185

            
186
    /// Re-opens the current `if` frame's `then` arm as a fresh `else` arm:
187
    /// resets reachability, exactly as opening a sibling branch would.
188
5319719
    pub(crate) fn reset_for_else(&mut self) {
189
5319719
        let live = self.live;
190
5319719
        let top = self.top_mut();
191
5319719
        top.unreachable = false;
192
5319719
        top.then_fell_through = Some(live);
193
5319719
        self.live = top.entry_live;
194
5319719
    }
195

            
196
    /// Merges a balanced scratch's final state: dead if either side is. The
197
    /// scratch's exits are applied to this emitter's frames, or re-exported
198
    /// when they lie beyond them; a splice into dead code contributes none.
199
5033305
    pub(crate) fn merge_spliced(&mut self, source: &Self) {
200
5033305
        if self.live {
201
5029927
            for &exit in &source.exits {
202
115172
                self.mark_target(exit);
203
            }
204
3378
        }
205
5033305
        if !source.is_reachable() {
206
136115
            self.mark_unreachable();
207
4897190
        }
208
5033305
        self.live &= source.is_live();
209
5033305
    }
210

            
211
    /// True unless the innermost frame is unreachable — i.e. whether an
212
    /// instruction placed here would actually run.
213
13964541
    pub(crate) fn is_reachable(&self) -> bool {
214
13964541
        !self.top().unreachable
215
13964541
    }
216

            
217
    /// Whether control can reach the next instruction by the end-reachability
218
    /// rules; never true where [`Self::is_reachable`] is false.
219
76187464
    pub(crate) const fn is_live(&self) -> bool {
220
76187464
        self.live
221
76187464
    }
222
}
223

            
224
impl Default for ValidationFrame {
225
    fn default() -> Self {
226
        Self::new()
227
    }
228
}
229

            
230
#[cfg(test)]
231
#[path = "frame_tests.rs"]
232
mod tests;
233

            
234
#[cfg(test)]
235
#[path = "summary_tests.rs"]
236
mod summary_tests;