1
//! A runtime-clause `COND` lowers to one flat block, so wasm control nesting
2
//! does not grow with the clause count.
3

            
4
use wasmparser::{FunctionBody, Operator, Parser, Payload};
5

            
6
use super::common::{compile_and_validate, wrap_with_runtime_i32};
7

            
8
150
fn body_control_depth(body: &FunctionBody) -> usize {
9
150
    let reader = body.get_operators_reader().expect("operators reader");
10
150
    let mut depth = 0usize;
11
150
    let mut max = 0usize;
12
150
    for op in reader {
13
5976
        match op.expect("operator") {
14
            Operator::Block { .. }
15
            | Operator::Loop { .. }
16
            | Operator::If { .. }
17
            | Operator::TryTable { .. } => {
18
430
                depth += 1;
19
430
                max = max.max(depth);
20
            }
21
580
            Operator::End => depth = depth.saturating_sub(1),
22
4966
            _ => {}
23
        }
24
    }
25
150
    max
26
150
}
27

            
28
2
fn max_control_depth(wasm: &[u8]) -> usize {
29
2
    Parser::new(0)
30
2
        .parse_all(wasm)
31
2
        .filter_map(Result::ok)
32
174
        .filter_map(|payload| match payload {
33
150
            Payload::CodeSectionEntry(body) => Some(body_control_depth(&body)),
34
24
            _ => None,
35
174
        })
36
        .max()
37
2
        .unwrap_or(0)
38
2
}
39

            
40
2
fn stack_position_cond(clauses: u32) -> Vec<u8> {
41
2
    let body: String = (0..clauses)
42
260
        .map(|i| format!("((= IDX {i}) {i}) "))
43
        .collect();
44
2
    compile_and_validate(&wrap_with_runtime_i32(&format!(
45
2
        "(+ 1 (cond {body}(t -1)))"
46
2
    )))
47
2
}
48

            
49
#[test]
50
1
fn runtime_cond_nesting_does_not_grow_with_the_clause_count() {
51
1
    let small = max_control_depth(&stack_position_cond(4));
52
1
    let large = max_control_depth(&stack_position_cond(256));
53
1
    assert!(small > 0, "a runtime COND must emit control structure");
54
1
    assert_eq!(small, large);
55
1
}