1
//! Tests for `FunctionEmitter::block_end` (moved out of `emit.rs` per
2
//! CLAUDE.md's file-size guideline).
3

            
4
use super::*;
5

            
6
/// Fable review (Phase 3): `block_end` used to hide a mismatched
7
/// `block_start` / `block_end` pair with `saturating_sub`, silently leaving
8
/// `block_depth` at 0 instead of surfacing the misuse. It is now a checked
9
/// subtraction returning a structured `Error::Compile` — the `Result` IS the
10
/// contract, so no `#[spec(requires: ...)]` shadows it with a panic under
11
/// `--cfg anodized_panic`.
12
#[test]
13
1
fn block_end_at_depth_zero_is_a_compile_error_not_a_panic() {
14
1
    let mut emit = FunctionEmitter::new();
15
1
    assert_eq!(emit.block_depth(), 0);
16
1
    let err = emit
17
1
        .block_end()
18
1
        .expect_err("block_end() with no open block frame must error");
19
1
    assert!(
20
1
        err.to_string()
21
1
            .contains("block_end() called with no open block frame")
22
    );
23
1
}
24

            
25
/// A balanced `block_start` / `block_end` pair still succeeds and leaves the
26
/// depth back at 0.
27
#[test]
28
1
fn block_end_after_block_start_succeeds() {
29
1
    let mut emit = FunctionEmitter::new();
30
1
    emit.block_start();
31
1
    assert_eq!(emit.block_depth(), 1);
32
1
    emit.block_end().expect("balanced block_end must succeed");
33
1
    assert_eq!(emit.block_depth(), 0);
34
1
}
35

            
36
/// Second review round, item 5: there is no public raw `end()` any more —
37
/// `finish()` is the only way to close a `FunctionEmitter`'s outermost
38
/// scope, and it structurally refuses an unclosed frame instead of trusting
39
/// every call site to check balance first (the class of bug
40
/// `create_tag.rs`'s stray `emit.end()` produced: valid bytes, but a
41
/// `block_depth` / simulator desync).
42
#[test]
43
1
fn finish_with_an_unclosed_block_is_a_structured_error() {
44
1
    let mut emit = FunctionEmitter::new();
45
1
    emit.block_start();
46
1
    let err = emit
47
1
        .finish(&[])
48
1
        .expect_err("finish() with an open block frame must error");
49
1
    assert!(
50
1
        err.to_string()
51
1
            .contains("finish() called with an unclosed structured-control frame")
52
    );
53
1
}
54

            
55
/// A fully balanced emitter finishes normally.
56
#[test]
57
1
fn finish_with_a_balanced_emitter_succeeds() {
58
1
    let mut emit = FunctionEmitter::new();
59
1
    emit.block_start();
60
1
    emit.block_end().expect("close the block");
61
1
    emit.finish(&[]).expect("balanced emitter must finish");
62
1
}
63

            
64
#[test]
65
1
fn locals_addressed_is_one_past_the_highest_local_named() {
66
1
    let mut emit = FunctionEmitter::new();
67
1
    assert_eq!(emit.locals_addressed().ok(), Some(0));
68
1
    emit.local_get(2);
69
1
    emit.local_set(5);
70
1
    emit.local_tee(3);
71
1
    assert_eq!(emit.locals_addressed().ok(), Some(6));
72
1
}