1
mod frame;
2
mod instr;
3

            
4
use wasm_encoder::{BlockType, Catch, Encode, Function, Instruction, ValType};
5

            
6
use crate::error::{Error, Result};
7

            
8
use frame::{FrameKind, ValidationFrame};
9

            
10
pub struct FunctionEmitter {
11
    bytes: Vec<u8>,
12
    block_depth: u32,
13
    /// The `block_depth` this emitter started at — 0 for [`Self::new`], the
14
    /// caller's depth for [`Self::new_seeded`]. A scratch buffer that is
15
    /// internally balanced (every opened frame closed) ends back at this
16
    /// same depth; [`Self::splice`] checks that before trusting anything
17
    /// else about the scratch.
18
    seeded_depth: u32,
19
    frame: ValidationFrame,
20
    /// `bytes.len()` right after the last `unreachable` / `throw` / `br` /
21
    /// `br_table`: the one position known to hold no concrete operand.
22
    polymorphic_at: Option<usize>,
23
}
24

            
25
impl FunctionEmitter {
26
7466345
    pub fn new() -> Self {
27
7466345
        Self {
28
7466345
            bytes: Vec::new(),
29
7466345
            block_depth: 0,
30
7466345
            seeded_depth: 0,
31
7466345
            frame: ValidationFrame::new(),
32
7466345
            polymorphic_at: None,
33
7466345
        }
34
7466345
    }
35

            
36
    /// A fresh scratch emitter whose `block_depth` is pre-seeded to
37
    /// `depth`, as if it were already nested that many structured-control
38
    /// frames deep. Used by BLOCK emit-time exit discovery: the body is
39
    /// compiled into a scratch buffer seeded at the depth the block's
40
    /// frame will occupy, so every relative `br` (RETURN-FROM / GO,
41
    /// including exits to outer blocks) computes the same target it will
42
    /// need once the bytes are spliced into the parent after the parent
43
    /// opens the block. Pair with [`Self::splice`].
44
5156610
    pub fn new_seeded(depth: u32) -> Self {
45
5156610
        Self {
46
5156610
            bytes: Vec::new(),
47
5156610
            block_depth: depth,
48
5156610
            seeded_depth: depth,
49
5156610
            frame: ValidationFrame::new(),
50
5156610
            polymorphic_at: None,
51
5156610
        }
52
5156610
    }
53

            
54
    /// Borrow the raw instruction bytes for splicing without consuming the
55
    /// emitter (e.g. handler-case keeps several clause scratches and splices
56
    /// each in turn).
57
5942770
    pub fn bytes_ref(&self) -> &[u8] {
58
5942770
        &self.bytes
59
5942770
    }
60

            
61
    /// Whether this emitter's simulated position is currently reachable —
62
    /// i.e. whether an instruction placed here would actually run.
63
8931227
    pub fn is_reachable(&self) -> bool {
64
8931227
        self.frame.is_reachable()
65
8931227
    }
66

            
67
    /// Whether control can reach the next instruction by the frames'
68
    /// end-reachability rules; never true where [`Self::is_reachable`] is false.
69
71154095
    pub fn is_live(&self) -> bool {
70
71154095
        self.frame.is_live()
71
71154095
    }
72

            
73
    /// Reports a type error unless an operand already exited (`return-from`,
74
    /// `error`): the value it would mistype never exists, so the program is
75
    /// well-typed and the rest is dead code.
76
17717
    pub fn reject_if_live(&self, err: Error) -> Result<()> {
77
17717
        if self.is_reachable() {
78
16445
            Err(err)
79
        } else {
80
1272
            Ok(())
81
        }
82
17717
    }
83

            
84
    /// Appends `source`'s raw instruction bytes and merges its simulated
85
    /// final reachability into `self` — never a caller's syntactic belief
86
    /// about either. A caller that thinks an arm "diverges" is wrong exactly
87
    /// often enough to matter (`form_diverges` doesn't see through AND/OR
88
    /// into a tail `ERROR`, doesn't know GO, …); reading the scratch's own
89
    /// simulator state instead is the fix, not a declared/actual comparison
90
    /// that such a belief could still get backwards.
91
    ///
92
    /// Before trusting that reachability, checks that `source` is internally
93
    /// balanced — every `block_start` / `if_block` / `try_table` it opened
94
    /// has a matching `block_end` — and ends at the same `block_depth` it
95
    /// was seeded with. Both are cheap, unconditional emitter-bug guards: a
96
    /// scratch that fails either has a real mismatched-frame bug, independent
97
    /// of whatever any caller believes about divergence.
98
5033307
    pub fn splice(&mut self, source: &FunctionEmitter) -> Result<()> {
99
5033307
        if !source.frame.is_balanced() {
100
2
            return Err(Error::Compile(
101
2
                "internal: splice source has an unclosed structured-control frame".to_string(),
102
2
            ));
103
5033305
        }
104
5033305
        if source.block_depth != source.seeded_depth {
105
            return Err(Error::Compile(format!(
106
                "internal: splice source ended at block depth {} but was seeded at {}",
107
                source.block_depth, source.seeded_depth
108
            )));
109
5033305
        }
110
5033305
        self.bytes.extend_from_slice(source.bytes_ref());
111
5033305
        self.frame.merge_spliced(&source.frame);
112
5033305
        if source.ends_polymorphic() {
113
115241
            self.mark_polymorphic();
114
4918064
        }
115
5033305
        Ok(())
116
5033307
    }
117

            
118
    /// Runs `compile` once on a live scratch seeded at this depth and splices
119
    /// it in; answers its value and whether the scratch ends reachable. Dead
120
    /// code compiled this way is typed by what it pushes when reached.
121
788
    pub fn on_live_scratch<T>(
122
788
        &mut self,
123
788
        compile: impl FnOnce(&mut FunctionEmitter) -> Result<T>,
124
788
    ) -> Result<(T, bool)> {
125
788
        let mut scratch = FunctionEmitter::new_seeded(self.block_depth);
126
788
        let value = compile(&mut scratch)?;
127
783
        self.splice(&scratch)?;
128
783
        Ok((value, scratch.is_reachable()))
129
788
    }
130

            
131
    /// Current wasm structured-control depth — the number of open
132
    /// `block` / `loop` / `if` frames around the next instruction. Used
133
    /// by labelled exits (BLOCK / RETURN-FROM, TAGBODY / GO) to compute
134
    /// the relative `br` depth.
135
16564143
    pub fn block_depth(&self) -> u32 {
136
16564143
        self.block_depth
137
16564143
    }
138

            
139
    /// The count of locals the emitted code addresses: one past the highest
140
    /// index any `local.get` / `local.set` / `local.tee` names.
141
209944
    pub fn locals_addressed(&self) -> Result<u32> {
142
        use wasmparser::{BinaryReader, Operator, OperatorsReader};
143
209944
        let mut ops = OperatorsReader::new(BinaryReader::new(&self.bytes, 0));
144
209944
        let mut addressed = 0;
145
1868960
        while !ops.eof() {
146
1659016
            let operator = ops
147
1659016
                .read()
148
                .map_err(|e| Error::Compile(format!("internal: unreadable emitted code: {e}")))?;
149
1659016
            if let Operator::LocalGet { local_index }
150
1659016
            | Operator::LocalSet { local_index }
151
1659016
            | Operator::LocalTee { local_index } = operator
152
            {
153
717862
                addressed = addressed.max(local_index.saturating_add(1));
154
941154
            }
155
        }
156
209944
        Ok(addressed)
157
209944
    }
158

            
159
    /// Emits the terminating `End` and finishes the function. The ONLY way
160
    /// to close a `FunctionEmitter`'s outermost scope — there is no public
161
    /// raw `end()` — so a structured-control frame this emitter opened and
162
    /// never closed (the exact class of bug `create_tag.rs`'s
163
    /// `emit.end()` instead of `emit.block_end()` produced: valid bytes,
164
    /// but a `block_depth` / simulator desync a later splice could act on)
165
    /// is caught HERE, structurally, rather than depending on every call
166
    /// site remembering to check balance before finishing.
167
7199835
    pub fn finish(mut self, locals: &[(u32, ValType)]) -> Result<Function> {
168
7199835
        if !self.frame.is_balanced() || self.block_depth != self.seeded_depth {
169
1
            return Err(Error::Compile(
170
1
                "internal: finish() called with an unclosed structured-control frame".to_string(),
171
1
            ));
172
7199834
        }
173
7199834
        self.seal_residue();
174
7199834
        Instruction::End.encode(&mut self.bytes);
175
7199834
        let mut func = Function::new(locals.iter().copied());
176
7199834
        func.raw(self.bytes);
177
7199834
        Ok(func)
178
7199835
    }
179

            
180
17637271
    pub fn if_block(&mut self, block_type: BlockType) {
181
17637271
        Instruction::If(block_type).encode(&mut self.bytes);
182
17637271
        self.block_depth += 1;
183
17637271
        self.frame.push_ctrl(FrameKind::If);
184
17637271
    }
185

            
186
5319718
    pub fn else_block(&mut self) {
187
5319718
        self.seal_residue();
188
5319718
        Instruction::Else.encode(&mut self.bytes);
189
5319718
        self.frame.reset_for_else();
190
5319718
    }
191

            
192
4045487
    pub fn block_start(&mut self) {
193
4045487
        Instruction::Block(BlockType::Empty).encode(&mut self.bytes);
194
4045487
        self.block_depth += 1;
195
4045487
        self.frame.push_ctrl(FrameKind::Block);
196
4045487
    }
197

            
198
    /// Open a wasm `block` whose result type is known up-front. Used
199
    /// by BLOCK / RETURN-FROM where the lexically-named block carries
200
    /// a value-yielding result.
201
3411806
    pub fn block_start_typed(&mut self, block_type: BlockType) {
202
3411806
        Instruction::Block(block_type).encode(&mut self.bytes);
203
3411806
        self.block_depth += 1;
204
3411806
        self.frame.push_ctrl(FrameKind::Block);
205
3411806
    }
206

            
207
2407914
    pub fn loop_start(&mut self) {
208
2407914
        Instruction::Loop(BlockType::Empty).encode(&mut self.bytes);
209
2407914
        self.block_depth += 1;
210
2407914
        self.frame.push_ctrl(FrameKind::Loop);
211
2407914
    }
212

            
213
    /// Closes the innermost open structured-control frame. Errors — rather
214
    /// than silently absorbing the underflow with `saturating_sub` — when
215
    /// `block_depth` is already zero: a mismatched `block_start` /
216
    /// `block_end` pair is a compiler bug, and letting it wrap silently would
217
    /// ship wasm with wrong `br` depths instead of surfacing the mistake.
218
    ///
219
    /// Seals the position after `end` with `unreachable` when the closed
220
    /// frame is not end-reachable but the validator still is: the one place
221
    /// a dead fallthrough is made polymorphic. A dead residue before the
222
    /// `end` is sealed first, as for `else`.
223
29317271
    pub fn block_end(&mut self) -> Result<()> {
224
29317271
        let depth = self.block_depth.checked_sub(1).ok_or_else(|| {
225
1
            Error::Compile("internal: block_end() called with no open block frame".to_string())
226
1
        })?;
227
29317270
        self.seal_residue();
228
29317270
        self.frame.pop_ctrl()?;
229
29317270
        Instruction::End.encode(&mut self.bytes);
230
29317270
        self.block_depth = depth;
231
29317270
        if !self.is_live() && self.is_reachable() {
232
2528741
            self.unreachable();
233
26788529
        }
234
29317270
        Ok(())
235
29317271
    }
236

            
237
7158514
    pub fn br(&mut self, depth: u32) {
238
7158514
        Instruction::Br(depth).encode(&mut self.bytes);
239
7158514
        self.frame.mark_targets([depth]);
240
7158514
        self.frame.mark_unreachable();
241
7158514
        self.mark_polymorphic();
242
7158514
    }
243

            
244
2398928
    pub fn br_if(&mut self, depth: u32) {
245
2398928
        Instruction::BrIf(depth).encode(&mut self.bytes);
246
2398928
        self.frame.mark_targets([depth]);
247
2398928
    }
248

            
249
    /// Indexed branch — pops an i32 selector, jumps to `targets[i]` when the
250
    /// selector is in range, else `default`. Used by TAGBODY / GO to dispatch
251
    /// to the segment matching the current pc.
252
9033
    pub fn br_table(&mut self, targets: &[u32], default: u32) {
253
9033
        Instruction::BrTable(std::borrow::Cow::Borrowed(targets), default).encode(&mut self.bytes);
254
9033
        self.frame
255
9033
            .mark_targets(targets.iter().copied().chain([default]));
256
9033
        self.frame.mark_unreachable();
257
9033
        self.mark_polymorphic();
258
9033
    }
259

            
260
    /// Emit `unreachable`. Used after a `br` out of a value-yielding
261
    /// block where the validator still expects a typed value on the
262
    /// stack but control will never reach the next instruction —
263
    /// wasm's stack-polymorphism after `unreachable` keeps the
264
    /// type-check happy without forcing us to materialize a real value.
265
12145882
    pub fn unreachable(&mut self) {
266
12145882
        Instruction::Unreachable.encode(&mut self.bytes);
267
12145882
        self.frame.mark_unreachable();
268
12145882
        self.mark_polymorphic();
269
12145882
    }
270

            
271
    /// Open a `try_table` frame (exception-handling proposal). `catches`
272
    /// routes matching `throw`s to a relative `br` depth resolved against
273
    /// the open blocks. Opens one structured-control frame like `block`,
274
    /// so `block_depth` increments — keeping `(return-from name v)` and
275
    /// `(go tag)` relative-`br` math correct across a wrapped body. Pair
276
    /// with [`Self::block_end`]. Used by the Tier 3 boundary wrapper and
277
    /// by `(handler-case)` / `(unwind-protect)` (ADR-0026).
278
2480138
    pub fn try_table(&mut self, block_type: BlockType, catches: &[Catch]) {
279
2480138
        Instruction::TryTable(block_type, std::borrow::Cow::Borrowed(catches))
280
2480138
            .encode(&mut self.bytes);
281
2480138
        self.frame.mark_targets(catches.iter().map(catch_label));
282
2480138
        self.block_depth += 1;
283
2480138
        self.frame.push_ctrl(FrameKind::TryTable);
284
2480138
    }
285

            
286
    /// Throw the exception with the given tag index, consuming one stack
287
    /// value per tag parameter (the `$nomi_error` tag takes a single
288
    /// `(ref null $nomi_condition)`). Control never returns past a
289
    /// `throw`, so the stack goes polymorphic — value-position callers
290
    /// pair this with a trailing type the validator accepts.
291
504732
    pub fn throw(&mut self, tag_idx: u32) {
292
504732
        Instruction::Throw(tag_idx).encode(&mut self.bytes);
293
504732
        self.frame.mark_unreachable();
294
504732
        self.mark_polymorphic();
295
504732
    }
296

            
297
19933402
    fn mark_polymorphic(&mut self) {
298
19933402
        self.polymorphic_at = Some(self.bytes.len());
299
19933402
    }
300

            
301
24458778
    fn ends_polymorphic(&self) -> bool {
302
24458778
        self.polymorphic_at == Some(self.bytes.len())
303
24458778
    }
304

            
305
    /// Seals dead code before `else` / `end`: code compiled past a `throw` or
306
    /// `br` (`(progn (error …) 1)`) pushes a concrete operand that the
307
    /// validator's polymorphic stack does not absorb, and the frame boundary
308
    /// would type-check it against the block's result.
309
41836822
    fn seal_residue(&mut self) {
310
41836822
        if !self.is_live() && !self.ends_polymorphic() {
311
53835
            self.unreachable();
312
41782987
        }
313
41836822
    }
314
}
315

            
316
2480134
const fn catch_label(catch: &Catch) -> u32 {
317
2480134
    match *catch {
318
        Catch::One { label, .. }
319
        | Catch::OneRef { label, .. }
320
        | Catch::All { label }
321
2480134
        | Catch::AllRef { label } => label,
322
    }
323
2480134
}
324

            
325
impl Default for FunctionEmitter {
326
    fn default() -> Self {
327
        Self::new()
328
    }
329
}
330

            
331
#[cfg(test)]
332
#[path = "emit_tests.rs"]
333
mod tests;
334

            
335
#[cfg(test)]
336
#[path = "splice_tests.rs"]
337
mod splice_tests;
338

            
339
#[cfg(test)]
340
#[path = "frame_live_tests.rs"]
341
mod frame_live_tests;
342

            
343
#[cfg(test)]
344
#[path = "seal_tests.rs"]
345
mod seal_tests;
346

            
347
#[cfg(test)]
348
#[path = "residue_seal_tests.rs"]
349
mod residue_seal_tests;