1
//! Lexical control-transfer bookkeeping shared by BLOCK / TAGBODY /
2
//! UNWIND-PROTECT codegen: `BlockLabel` / `TagFrame` / `UnwindFrame` and the
3
//! `CompileContext` push/pop/lookup methods over them.
4
//!
5
//! All three frame kinds record depths relative to the emitter compiling the
6
//! CURRENT function — a lambda/catch-each helper starts a fresh emitter at
7
//! block depth 0, so these stacks are reset (not carried over) by
8
//! `CompileContext::take_local_pool` / `restore_local_pool`, alongside the
9
//! local-pool state they already reset.
10

            
11
use anodized::spec;
12

            
13
use super::CompileContext;
14
use crate::ast::{Expr, WasmType};
15
use crate::compiler::join::Exit;
16
use crate::error::Result;
17

            
18
/// One active `(unwind-protect)` frame, live while its protected body
19
/// compiles. A non-local lexical exit — `(return-from)` / `(go)` whose
20
/// target lies *outside* this unwind-protect — must run this cleanup before
21
/// branching (Common-Lisp semantics), so the exit-site codegen walks the
22
/// frame stack and emits the cleanup of every crossed frame inline, then
23
/// `br`s. `threshold` is the `block_depth()` the unwind-protect sat at
24
/// (`parent_depth`); an exit whose target wasm-depth is `<= threshold`
25
/// leaves this frame and so triggers its cleanup. `cleanup` is the cleanup
26
/// forms' AST, recompiled for effect at each crossing exit (the normal /
27
/// exceptional convergence path emits its own copy independently).
28
#[derive(Debug, Clone)]
29
pub(in crate::compiler) struct UnwindFrame {
30
    pub threshold: u32,
31
    pub cleanup: Vec<Expr>,
32
}
33

            
34
/// One frame on the lexical BLOCK stack. `wasm_depth` is the
35
/// `FunctionEmitter::block_depth()` reading captured *after* the
36
/// matching `block` instruction was emitted, so a `(return-from name v)`
37
/// sees a stable br target across nested IF / DOLIST / DO frames inside
38
/// the body. The frame is popped when control leaves the BLOCK form.
39
///
40
/// The block's result type is discovered at emit time: each reachable
41
/// `(return-from name v)` compiled inside the body records `v`'s [`Exit`]
42
/// in `recorded_exits`. Because only *compiled* (reachable)
43
/// exits record — code stored as a value (quote / lambda / labels bodies,
44
/// discarded macro args) is never compiled in value position — the set is
45
/// exactly the live exits, with no syntactic pre-scan. `target` is the
46
/// reconciled result a second pass compiles every exit at.
47
#[derive(Debug, Clone)]
48
pub(in crate::compiler) struct BlockLabel {
49
    pub name: String,
50
    pub wasm_depth: u32,
51
    pub target: Option<WasmType>,
52
    pub recorded_exits: Vec<Exit>,
53
}
54

            
55
/// One TAGBODY frame. Each tag in the body has a stable ordinal `pc` (its
56
/// position in the source order, base-zero) and a wasm-block depth captured
57
/// when emit reaches its segment. `(go tag)` resolves the named tag,
58
/// stores the next `pc` into `pc_local`, and branches to the dispatcher
59
/// `loop` so `br_table` re-enters at the right segment.
60
#[derive(Debug, Clone)]
61
pub(in crate::compiler) struct TagFrame {
62
    pub tags: Vec<TagEntry>,
63
    pub pc_local: u32,
64
    pub loop_depth: u32,
65
}
66

            
67
#[derive(Debug, Clone)]
68
pub(in crate::compiler) struct TagEntry {
69
    pub name: String,
70
    pub pc: u32,
71
}
72

            
73
/// The three frame stacks, as a rolled-back scope restores them: a trial
74
/// may record exits into an enclosing BLOCK or leave a frame pushed.
75
#[derive(Debug, Default)]
76
pub(in crate::compiler::context) struct FrameJournal {
77
    block_labels: Vec<BlockLabel>,
78
    hidden_labels: Vec<(usize, usize)>,
79
    tag_frames: Vec<TagFrame>,
80
    unwind_frames: Vec<UnwindFrame>,
81
}
82

            
83
impl CompileContext {
84
161154
    pub(in crate::compiler::context) fn frame_journal(&self) -> FrameJournal {
85
161154
        FrameJournal {
86
161154
            block_labels: self.block_labels.clone(),
87
161154
            hidden_labels: self.hidden_labels.clone(),
88
161154
            tag_frames: self.tag_frames.clone(),
89
161154
            unwind_frames: self.unwind_frames.clone(),
90
161154
        }
91
161154
    }
92

            
93
5099464
    pub(in crate::compiler::context) fn take_frames(&mut self) -> FrameJournal {
94
5099464
        FrameJournal {
95
5099464
            block_labels: std::mem::take(&mut self.block_labels),
96
5099464
            hidden_labels: std::mem::take(&mut self.hidden_labels),
97
5099464
            tag_frames: std::mem::take(&mut self.tag_frames),
98
5099464
            unwind_frames: std::mem::take(&mut self.unwind_frames),
99
5099464
        }
100
5099464
    }
101

            
102
5202116
    pub(in crate::compiler::context) fn restore_frames(&mut self, journal: FrameJournal) {
103
        let FrameJournal {
104
            block_labels,
105
            hidden_labels,
106
            tag_frames,
107
            unwind_frames,
108
5202116
        } = journal;
109
5202116
        self.block_labels = block_labels;
110
5202116
        self.hidden_labels = hidden_labels;
111
5202116
        self.tag_frames = tag_frames;
112
5202116
        self.unwind_frames = unwind_frames;
113
5202116
    }
114

            
115
    /// Push a lexical BLOCK frame so a `(return-from name v)` walking
116
    /// the stack from innermost to outermost can resolve the wasm-block
117
    /// it refers to. `wasm_depth` is the emitter's depth the body is
118
    /// compiled at (the depth the `block` frame will occupy once spliced).
119
67330
    pub(in crate::compiler) fn push_block_label(
120
67330
        &mut self,
121
67330
        name: &str,
122
67330
        wasm_depth: u32,
123
67330
        target: Option<WasmType>,
124
67330
    ) {
125
67330
        self.block_labels.push(BlockLabel {
126
67330
            name: name.to_string(),
127
67330
            wasm_depth,
128
67330
            target,
129
67330
            recorded_exits: Vec::new(),
130
67330
        });
131
67330
    }
132

            
133
    /// Pop the named BLOCK frame, returning the exits its reachable
134
    /// `(return-from)`s recorded during body emit. The caller reconciles them
135
    /// (with the fall-through tail, if any) into the block's result type.
136
67323
    pub(in crate::compiler) fn pop_block_label(&mut self, name: &str) -> Result<Vec<Exit>> {
137
67323
        match self.block_labels.pop() {
138
67323
            Some(top) if top.name == name => Ok(top.recorded_exits),
139
            Some(top) => Err(crate::error::Error::Compile(format!(
140
                "BLOCK label stack imbalance: expected '{name}' on top, found '{}'",
141
                top.name
142
            ))),
143
            None => Err(crate::error::Error::Compile(format!(
144
                "BLOCK label stack imbalance: expected '{name}' on top, found empty stack"
145
            ))),
146
        }
147
67323
    }
148

            
149
90616
    pub(in crate::compiler) fn lookup_block_label(&self, name: &str) -> Option<&BlockLabel> {
150
90616
        let at = self.visible_label(name)?;
151
89949
        self.block_labels.get(at)
152
90616
    }
153

            
154
    /// The innermost BLOCK label named `name` that is not hidden from the
155
    /// current inlined body.
156
180258
    fn visible_label(&self, name: &str) -> Option<usize> {
157
180258
        (0..self.block_labels.len())
158
180258
            .rev()
159
191073
            .find(|&at| !self.is_hidden_label(at) && self.block_labels[at].name == name)
160
180258
    }
161

            
162
194237
    fn is_hidden_label(&self, at: usize) -> bool {
163
194237
        self.hidden_labels
164
194237
            .iter()
165
7776
            .any(|&(from, to)| (from..to).contains(&at))
166
194237
    }
167

            
168
    /// Whether a BLOCK named `name` is open in the code this function body was
169
    /// written in, where a `RETURN-FROM` inside it cannot reach it.
170
666
    pub(in crate::compiler) fn block_is_out_of_reach(&self, name: &str) -> bool {
171
666
        self.outer_labels.iter().any(|outer| outer == name)
172
666
    }
173

            
174
    /// Opens a function body: the block names open here are out of its reach.
175
    /// Returns the names that were out of reach of the code around it.
176
5099464
    pub(in crate::compiler::context) fn hide_labels_from_body(&mut self) -> Vec<String> {
177
5099464
        let before = self.outer_labels.clone();
178
        // A label hidden from an inlined body was opened after its function was
179
        // written: it does not enclose a lambda written inside that function.
180
5099464
        let names: Vec<String> = (0..self.block_labels.len())
181
3164
            .filter(|&at| !self.is_hidden_label(at))
182
3160
            .map(|at| self.block_labels[at].name.clone())
183
            .collect();
184
5099464
        self.outer_labels.extend(names);
185
5099464
        before
186
5099464
    }
187

            
188
    /// A global function's body is compiled where it is called, not where it
189
    /// was written: no block of the call site encloses it.
190
20659
    pub(crate) fn forget_outer_labels(&mut self) {
191
20659
        self.outer_labels.clear();
192
20659
    }
193

            
194
    /// How many BLOCK labels are open: a function defined here sees them.
195
551094
    pub(in crate::compiler) fn block_label_count(&self) -> usize {
196
551094
        self.block_labels.len()
197
551094
    }
198

            
199
    /// Runs `body` (an inlined function's body) with the labels opened since
200
    /// its definition, `from` onward, hidden; restored on every path.
201
413374
    pub(in crate::compiler) fn with_hidden_labels<T>(
202
413374
        &mut self,
203
413374
        from: usize,
204
413374
        body: impl FnOnce(&mut Self) -> crate::error::Result<T>,
205
413374
    ) -> crate::error::Result<T> {
206
413374
        self.hidden_labels.push((from, self.block_labels.len()));
207
413374
        let result = body(self);
208
413374
        self.hidden_labels.pop();
209
413374
        result
210
413374
    }
211

            
212
    /// Record a reachable `(return-from name v)` exit into the
213
    /// innermost matching BLOCK frame, so emit-time discovery can reconcile
214
    /// the block's result type from exactly the exits that compile.
215
89642
    pub(in crate::compiler) fn record_block_exit(&mut self, name: &str, exit: Exit) {
216
89642
        if let Some(frame) = self
217
89642
            .visible_label(name)
218
89642
            .and_then(|at| self.block_labels.get_mut(at))
219
        {
220
89642
            frame.recorded_exits.push(exit);
221
        }
222
89642
    }
223

            
224
    /// Push an `(unwind-protect)` frame so a non-local exit crossing it runs
225
    /// its cleanup. `threshold` is the unwind-protect's `parent_depth`; an
226
    /// exit to a wasm-depth `<= threshold` leaves the frame.
227
35030
    #[spec(requires: self.unwind_frames.last().is_none_or(|top| top.threshold <= threshold))]
228
35030
    pub(in crate::compiler) fn push_unwind_frame(&mut self, threshold: u32, cleanup: Vec<Expr>) {
229
35030
        self.unwind_frames.push(UnwindFrame { threshold, cleanup });
230
35030
    }
231

            
232
35020
    pub(in crate::compiler) fn pop_unwind_frame(&mut self) -> Result<()> {
233
35020
        match self.unwind_frames.pop() {
234
35020
            Some(_) => Ok(()),
235
            None => Err(crate::error::Error::Compile(
236
                "UNWIND-PROTECT frame stack imbalance: pop on empty stack".to_string(),
237
            )),
238
        }
239
35020
    }
240

            
241
    /// Pop the innermost active unwind-protect frame if an exit to
242
    /// `target_depth` crosses it, i.e. the exit lands at or above (shallower
243
    /// than) its `threshold`. Frames are popped one at a time so the OUTER
244
    /// crossed frames stay active while the popped frame's cleanup is
245
    /// compiled: an exit inside that cleanup then crosses them itself. The
246
    /// caller MUST push the popped frames back with
247
    /// [`Self::restore_unwind_frames`], so sibling branches still see them.
248
    #[spec(
249
207676
        maintains: self.unwind_frames.is_sorted_by_key(|frame| frame.threshold),
250
103838
        captures: before = self.unwind_frames.len(),
251
        ensures: |ref output| [
252
103838
            self.unwind_frames.len() + usize::from(output.is_some()) == before,
253
103838
            output.iter().all(|frame| frame.threshold >= target_depth),
254
        ],
255
    )]
256
103838
    pub(in crate::compiler) fn pop_unwind_frame_crossing(
257
103838
        &mut self,
258
103838
        target_depth: u32,
259
103838
    ) -> Option<UnwindFrame> {
260
103838
        let crossed = self
261
103838
            .unwind_frames
262
103838
            .last()
263
4309
            .is_some_and(|frame| target_depth <= frame.threshold);
264
103838
        crossed.then(|| self.unwind_frames.pop()).flatten()
265
103838
    }
266

            
267
    /// Restore frames removed by [`Self::pop_unwind_frame_crossing`], in
268
    /// their original (bottom-to-top) order.
269
    #[spec(
270
        requires: [
271
99528
            frames.is_sorted_by_key(|frame| frame.threshold),
272
99528
            self.unwind_frames
273
99528
                .last()
274
99528
                .zip(frames.first())
275
                .is_none_or(|(top, first)| top.threshold <= first.threshold),
276
        ],
277
199056
        maintains: self.unwind_frames.is_sorted_by_key(|frame| frame.threshold),
278
99528
        captures: expected = self.unwind_frames.len() + frames.len(),
279
99528
        ensures: self.unwind_frames.len() == expected,
280
    )]
281
99528
    pub(in crate::compiler) fn restore_unwind_frames(&mut self, frames: Vec<UnwindFrame>) {
282
99528
        self.unwind_frames.extend(frames);
283
99528
    }
284

            
285
    /// Push a TAGBODY frame so `(go tag)` walking the stack from innermost
286
    /// outward can resolve the wasm-loop it has to jump back to. Returned
287
    /// after the matching `loop` instruction is emitted (so `loop_depth`
288
    /// records the emitter's depth at that moment).
289
9029
    pub(in crate::compiler) fn push_tag_frame(&mut self, frame: TagFrame) {
290
9029
        self.tag_frames.push(frame);
291
9029
    }
292

            
293
6089
    pub(in crate::compiler) fn pop_tag_frame(&mut self) -> Result<()> {
294
6089
        match self.tag_frames.pop() {
295
6089
            Some(_) => Ok(()),
296
            None => Err(crate::error::Error::Compile(
297
                "TAGBODY frame stack imbalance: pop on empty stack".to_string(),
298
            )),
299
        }
300
6089
    }
301

            
302
10098
    pub(in crate::compiler) fn lookup_tag(&self, name: &str) -> Option<(&TagFrame, u32)> {
303
10098
        for frame in self.tag_frames.iter().rev() {
304
11590
            if let Some(entry) = frame.tags.iter().find(|t| t.name == name) {
305
9682
                return Some((frame, entry.pc));
306
208
            }
307
        }
308
416
        None
309
10098
    }
310
}