1
//! Nested BLOCK joins (0014 slice 4.3b): a discarded pass hands each nested
2
//! block its join, so every block compiles at most twice however deep.
3

            
4
use super::compile_block_for_stack;
5
use crate::ast::{Expr, WasmType};
6
use crate::compiler::CompileMode;
7
use crate::compiler::behaviour_oracle::{Outcome, observe};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::compile_for_stack;
11
use crate::compiler::observations::{Leaf, ObservedBlock, StructuralType};
12
use crate::compiler::stats::CompileStats;
13
use crate::error::Result;
14
use crate::host_fn::HostFnSpec;
15
use crate::reader::Reader;
16
use crate::runtime::SymbolTable;
17

            
18
const TEST: &str = "(> (rpc-protocol-version) 0)";
19

            
20
23
fn hosts() -> [HostFnSpec; 1] {
21
23
    [
22
23
        HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
23
23
            .returns(WasmType::I32),
24
23
    ]
25
23
}
26

            
27
5
fn run(source: &str) -> (Vec<Outcome>, (u64, u64)) {
28
5
    let (behaviours, stats) = observe(source, CompileMode::Eval, &hosts());
29
10
    let outcomes = behaviours.into_iter().map(|b| b.outcome).collect();
30
5
    (outcomes, passes(stats))
31
5
}
32

            
33
5
fn passes(stats: CompileStats) -> (u64, u64) {
34
5
    (stats.block_passes_max, stats.block_passes_total)
35
5
}
36

            
37
/// The value in the empty-batch world, where every exit is taken, and in the
38
/// ledger world, where none is.
39
5
fn values(outcomes: &[Outcome]) -> Vec<&str> {
40
5
    outcomes
41
5
        .iter()
42
10
        .map(|outcome| match outcome {
43
10
            Outcome::Value(v) => v.as_str(),
44
            _ => "not a value",
45
10
        })
46
        .collect()
47
5
}
48

            
49
const HALF: &str = "Some(Ratio) [Struct(2), I64(1), I64(2)]";
50
const ONE: &str = "Some(Ratio) [Struct(2), I64(1), I64(1)]";
51

            
52
/// `depth` blocks, each with a literal `1` exit, around a `1/2` tail.
53
2
fn nest(depth: usize) -> String {
54
14
    (1..=depth).rev().fold("1/2".to_string(), |inner, level| {
55
14
        format!("(block b{level} (if {TEST} (return-from b{level} 1)) {inner})")
56
14
    })
57
2
}
58

            
59
#[test]
60
1
fn nested_blocks_whose_arms_disagree_compile_twice_each() {
61
1
    let (outcomes, passes) = run(&nest(2));
62
1
    assert_eq!(values(&outcomes), [ONE, HALF]);
63
1
    assert_eq!(passes, (2, 4));
64
1
}
65

            
66
#[test]
67
1
fn a_deep_nest_takes_two_passes_per_block() {
68
1
    let (outcomes, passes) = run(&nest(12));
69
1
    assert_eq!(values(&outcomes), [ONE, HALF]);
70
1
    assert_eq!(passes, (2, 24));
71
1
}
72

            
73
#[test]
74
1
fn a_settled_block_is_recompiled_for_an_unsettled_nested_one() {
75
1
    let (outcomes, passes) = run(&format!(
76
1
        "(block a (block b (if {TEST} (return-from b 1)) 1/2))"
77
1
    ));
78
1
    assert_eq!(values(&outcomes), [ONE, HALF]);
79
1
    assert_eq!(passes, (2, 4));
80
1
}
81

            
82
#[test]
83
1
fn nested_blocks_whose_arms_agree_take_one_pass_each() {
84
1
    let (outcomes, passes) = run(&format!(
85
1
        "(block a (block b (if {TEST} (return-from b 1)) 2))"
86
1
    ));
87
1
    assert_eq!(
88
1
        values(&outcomes),
89
1
        [
90
1
            "Some(I32) [Struct(2), I64(1), I64(1)]",
91
1
            "Some(I32) [Struct(2), I64(2), I64(1)]"
92
1
        ]
93
    );
94
1
    assert_eq!(passes, (1, 2));
95
1
}
96

            
97
#[test]
98
1
fn a_literal_exit_that_is_a_block_takes_its_join_in_the_second_pass() {
99
1
    let (outcomes, passes) = run(&format!(
100
1
        "(block a (if {TEST} (return-from a 1/2)) (block c 1))"
101
1
    ));
102
1
    assert_eq!(values(&outcomes), [HALF, ONE]);
103
1
    assert_eq!(passes, (2, 4));
104
1
}
105

            
106
7
fn ratio_join(name: &str, body_len: usize) -> ObservedBlock {
107
7
    join(name, body_len, Leaf::Ratio)
108
7
}
109

            
110
9
fn join(name: &str, body_len: usize, result: Leaf) -> ObservedBlock {
111
9
    ObservedBlock {
112
9
        name: name.to_string(),
113
9
        body_len,
114
9
        join: StructuralType {
115
9
            arrows: vec![],
116
9
            result,
117
9
        },
118
9
    }
119
9
}
120

            
121
/// Compiles each source BLOCK in turn while `expected` is the observed list,
122
/// returning each result type and the passes each took.
123
6
fn compile_expecting(
124
6
    expected: Vec<ObservedBlock>,
125
6
    sources: &[String],
126
6
) -> Result<Vec<(WasmType, u64)>> {
127
6
    let mut ctx = CompileContext::new_with_host_fns(&hosts())?;
128
6
    let mut symbols = SymbolTable::with_builtins_for_wasm();
129
6
    symbols.register_host_fns(&hosts());
130
6
    let mut emit = FunctionEmitter::new();
131
6
    ctx.expecting_block_joins(expected, |ctx| {
132
6
        sources
133
6
            .iter()
134
9
            .map(|source| {
135
9
                let before = ctx.compile_stats().block_passes_total;
136
                let ty =
137
9
                    compile_block_for_stack(ctx, &mut emit, &mut symbols, &block_args(source))?;
138
9
                Ok((ty, ctx.compile_stats().block_passes_total - before))
139
9
            })
140
            .collect()
141
6
    })
142
6
}
143

            
144
10
fn block_args(source: &str) -> Vec<Expr> {
145
10
    match Reader::parse(source).map(|program| program.exprs.into_iter().next()) {
146
10
        Ok(Some(Expr::List(elems))) => elems.into_iter().skip(1).collect(),
147
        other => panic!("a BLOCK form: {other:?}"),
148
    }
149
10
}
150

            
151
10
fn unsettled(name: &str) -> String {
152
10
    format!("(block {name} (if {TEST} (return-from {name} 1)) 1/2)")
153
10
}
154

            
155
#[test]
156
1
fn an_expected_join_lets_its_block_compile_once() {
157
1
    let compiled = compile_expecting(vec![ratio_join("B", 2)], &[unsettled("b")]);
158
1
    assert_eq!(compiled.expect("compile"), vec![(WasmType::Ratio, 1)]);
159
1
}
160

            
161
#[test]
162
1
fn a_key_mismatch_falls_back_to_two_passes_and_keeps_the_join_for_its_block() {
163
1
    let compiled = compile_expecting(vec![ratio_join("C", 2)], &[unsettled("b"), unsettled("c")]);
164
1
    assert_eq!(
165
1
        compiled.expect("compile"),
166
1
        vec![(WasmType::Ratio, 2), (WasmType::Ratio, 1)]
167
    );
168
1
}
169

            
170
#[test]
171
1
fn a_body_length_mismatch_falls_back_to_two_passes() {
172
1
    let compiled = compile_expecting(vec![ratio_join("B", 3)], &[unsettled("b")]);
173
1
    assert_eq!(compiled.expect("compile"), vec![(WasmType::Ratio, 2)]);
174
1
}
175

            
176
#[test]
177
1
fn a_stale_join_is_discarded_and_the_block_recompiles_at_its_own() {
178
1
    let compiled = compile_expecting(vec![join("B", 2, Leaf::I32)], &[unsettled("b")]);
179
1
    assert_eq!(compiled.expect("compile"), vec![(WasmType::Ratio, 2)]);
180
1
}
181

            
182
#[test]
183
1
fn a_fallback_second_pass_expects_its_own_joins_and_then_the_outer_ones_resume() {
184
1
    let two_nested = format!(
185
1
        "(block y (if {TEST} (return-from y 1)) {} {})",
186
1
        unsettled("z1"),
187
1
        unsettled("z2")
188
    );
189
1
    let compiled = compile_expecting(
190
1
        vec![ratio_join("X", 2), ratio_join("W", 2)],
191
1
        &[unsettled("x"), two_nested, unsettled("w")],
192
1
    );
193
1
    assert_eq!(
194
1
        compiled.expect("compile"),
195
1
        vec![
196
1
            (WasmType::Ratio, 1),
197
1
            (WasmType::Ratio, 6),
198
1
            (WasmType::Ratio, 1)
199
        ]
200
    );
201
1
}
202

            
203
/// Every arm an integer literal, so the block is an index.
204
const INDEX_VICTIM: &str = "(block b (if (> (rpc-protocol-version) 0) (return-from b 3)) 1)";
205

            
206
#[test]
207
1
fn a_stale_ratio_join_does_not_settle_an_index_block() {
208
1
    let compiled = compile_expecting(vec![ratio_join("B", 2)], &[INDEX_VICTIM.to_string()]);
209
1
    assert_eq!(compiled.expect("compile"), vec![(WasmType::I32, 2)]);
210
1
}
211

            
212
/// Compiles `source`, one form, while `expected` is the observed list.
213
2
fn compile_form_expecting(expected: Vec<ObservedBlock>, source: &str) -> Result<WasmType> {
214
2
    let mut ctx = CompileContext::new_with_host_fns(&hosts())?;
215
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
216
2
    symbols.register_host_fns(&hosts());
217
2
    let mut emit = FunctionEmitter::new();
218
2
    let form = Reader::parse(source)?
219
        .exprs
220
        .into_iter()
221
        .next()
222
2
        .expect("one form");
223
2
    ctx.expecting_block_joins(expected, |ctx| {
224
2
        compile_for_stack(ctx, &mut emit, &mut symbols, &form)
225
2
    })
226
2
}
227

            
228
#[test]
229
1
fn a_stale_ratio_join_leaves_an_enclosing_division_an_index_division() {
230
1
    let division = format!("(let ((v {INDEX_VICTIM})) (/ v 3))");
231
1
    let ty = compile_form_expecting(vec![ratio_join("B", 2)], &division);
232
1
    assert_eq!(ty.expect("compile"), WasmType::I32);
233
1
}
234

            
235
#[test]
236
1
fn a_stale_index_join_beside_a_fraction_is_a_mix() {
237
1
    let sum = format!("(+ 1/2 {INDEX_VICTIM})");
238
1
    let err = compile_form_expecting(vec![join("B", 2, Leaf::I32)], &sum).expect_err("a mix");
239
1
    assert!(
240
1
        err.to_string()
241
1
            .contains("+ cannot mix an index (count) with a scalar"),
242
        "{err}"
243
    );
244
1
}
245

            
246
#[test]
247
1
fn a_failed_block_closes_its_probe() {
248
1
    let failing = format!(
249
        "(block a (block c {} (+ 1/2 (rpc-protocol-version))))",
250
1
        unsettled("b")
251
    );
252
1
    let mut ctx = CompileContext::new_with_host_fns(&hosts()).expect("context");
253
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
254
1
    symbols.register_host_fns(&hosts());
255
1
    let mut emit = FunctionEmitter::new();
256
    let compiled =
257
1
        compile_block_for_stack(&mut ctx, &mut emit, &mut symbols, &block_args(&failing));
258
1
    assert!(compiled.is_err_and(|err| err.to_string().contains("scalar")));
259
1
    assert!(!ctx.open_block_probe().is_open());
260
1
}