1
//! The fixpoint against the observable behaviour of the programs it emits.
2

            
3
use crate::compiler::CompileMode;
4
use crate::compiler::behaviour_oracle::{Outcome, observe};
5
use crate::{HostFnSpec, WasmType};
6

            
7
11
fn outcomes(source: &str) -> Vec<Outcome> {
8
11
    observe(source, CompileMode::Script, &[])
9
11
        .0
10
11
        .into_iter()
11
22
        .map(|behaviour| behaviour.outcome)
12
        .collect()
13
11
}
14

            
15
/// The ratio `numer/denom`, in both worlds.
16
4
fn ratio(numer: i64, denom: i64) -> Vec<Outcome> {
17
4
    let text = format!("Number(Scalar(Ratio {{ numer: {numer}, denom: {denom} }}))");
18
4
    vec![Outcome::Value(text); 2]
19
4
}
20

            
21
7
fn index(n: i64) -> Vec<Outcome> {
22
7
    vec![Outcome::Value(format!("Number(Index({n}))")); 2]
23
7
}
24

            
25
/// The first pass guesses `i32` and observes a closure whose signature it
26
/// interned itself; the second pass must re-intern that signature rather
27
/// than reuse an id the rollback dropped.
28
#[test]
29
1
fn a_closure_return_type_survives_the_pass_rollback() {
30
1
    let source = "(let* ((idx (entity-count)))
31
1
                    (defun f (n) (let ((g (lambda (y) (* y 1/1)))) (when (> n 0) (f (- n 1))) g))
32
1
                    (let ((h (f idx))) (funcall h 1/2)))";
33
1
    assert_eq!(outcomes(source), ratio(1, 2));
34
1
}
35

            
36
/// A helper queued while the body compiles must not take the body's
37
/// code-section slot.
38
#[test]
39
1
fn a_lambda_inside_the_body_keeps_its_own_code_slot() {
40
1
    let source = "(let* ((idx (entity-count)))
41
1
                    (defun f (n) (let ((g (lambda (y) (* y 2/1)))) (when (> n 0) (f (- n 1))) (funcall g 1/2)))
42
1
                    (f idx))";
43
1
    assert_eq!(outcomes(source), ratio(1, 1));
44
1
}
45

            
46
/// `ev` runs inside `od`'s pass, so its body is queued first; each must
47
/// still land in its own code slot. The worlds answer 1 and 0, so `ev` sees
48
/// 4 and 3.
49
#[test]
50
1
fn mutually_recursive_monomorphs_keep_their_own_code_slots() {
51
1
    let hosts = [
52
1
        HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
53
1
            .returns(WasmType::I32),
54
1
    ];
55
1
    let source = "(defun ev (k) (if (= k 0) t (od (- k 1))))
56
1
                  (defun od (k) (if (= k 0) nil (ev (- k 1))))
57
1
                  (ev (+ (rpc-protocol-version) 3))";
58
1
    let outcomes: Vec<Outcome> = observe(source, CompileMode::Eval, &hosts)
59
1
        .0
60
1
        .into_iter()
61
2
        .map(|behaviour| behaviour.outcome)
62
        .collect();
63
2
    let answer = |truth: &str| Outcome::Value(format!("Some(AnyRef) [{truth}]"));
64
1
    assert_eq!(outcomes, vec![answer("T"), answer("Null")]);
65
1
}
66

            
67
/// The helper is a separate wasm function: it takes the cell that backs the
68
/// assigned global as a parameter, so it reads what the unit stored last.
69
#[test]
70
1
fn a_helper_reads_the_cell_of_an_assigned_global() {
71
1
    let hosts = [
72
1
        HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
73
1
            .returns(WasmType::I32),
74
1
    ];
75
1
    let source = "(defparameter *k* 2)
76
1
                  (defun f (n) (if (= n 0) 1 (* *k* (f (- n 1)))))
77
1
                  (setf *k* 3)
78
1
                  (f (+ (rpc-protocol-version) 2))";
79
1
    let outcomes: Vec<Outcome> = observe(source, CompileMode::Script, &hosts)
80
1
        .0
81
1
        .into_iter()
82
2
        .map(|behaviour| behaviour.outcome)
83
        .collect();
84
2
    let value = |n: i64| Outcome::Value(format!("Number(Index({n}))"));
85
1
    assert_eq!(outcomes, vec![value(27), value(9)]);
86
1
}
87

            
88
/// `ev` and `od` each wrap the call to the other in `depth` blocks that
89
/// disagree with their tail, so every block is unsettled in the first pass.
90
8
fn mutual_recursion_around_a_nest(depth: usize) -> String {
91
16
    let nest = |callee: &str| {
92
16
        (1..=depth)
93
16
            .rev()
94
324
            .fold(format!("({callee} (- k 1))"), |inner, level| {
95
324
                format!(
96
324
                    "(block b{level} (if (> (rpc-protocol-version) 0) (return-from b{level} 1)) {inner})"
97
                )
98
324
            })
99
16
    };
100
8
    format!(
101
        "(defun ev (k) (if (= k 0) 1/2 {})) (defun od (k) (if (= k 0) 1/2 {})) (ev (+ (rpc-protocol-version) 3))",
102
8
        nest("od"),
103
8
        nest("ev")
104
    )
105
8
}
106

            
107
8
fn block_passes(depth: usize) -> (Vec<Outcome>, u64) {
108
8
    let hosts = [
109
8
        HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
110
8
            .returns(WasmType::I32),
111
8
    ];
112
8
    let (behaviours, stats) = observe(
113
8
        &mutual_recursion_around_a_nest(depth),
114
8
        CompileMode::Eval,
115
8
        &hosts,
116
8
    );
117
16
    let outcomes = behaviours.into_iter().map(|b| b.outcome).collect();
118
8
    (outcomes, stats.block_passes_total)
119
8
}
120

            
121
/// A function body is compiled apart from the blocks around its call, and a
122
/// discarded pass hands its blocks' joins to the next, so a deeper nest costs
123
/// proportionally more block passes, not quadratically more.
124
#[test]
125
1
fn block_passes_around_mutual_recursion_grow_linearly() {
126
1
    let (shallow_outcomes, shallow) = block_passes(4);
127
1
    let (deep_outcomes, deep) = block_passes(6);
128
1
    let answers = vec![
129
1
        Outcome::Value("Some(AnyRef) [I31(1)]".to_string()),
130
1
        Outcome::Value("Some(AnyRef) [Struct(2), I64(1), I64(2)]".to_string()),
131
    ];
132
1
    assert_eq!(
133
1
        (shallow_outcomes, deep_outcomes),
134
1
        (answers.clone(), answers)
135
    );
136
1
    assert_eq!((shallow, deep), (88, 132));
137
1
}
138

            
139
/// A nest deeper than the shared recursion ceiling is a structured resource
140
/// error in both worlds, never a native stack overflow.
141
#[test]
142
1
fn a_deep_block_nest_around_mutual_recursion_ends_in_a_resource_error() {
143
1
    for depth in [16, 20, 40] {
144
3
        let (outcomes, _) = block_passes(depth);
145
3
        assert_eq!(outcomes.len(), 2, "depth {depth}");
146
3
        for outcome in outcomes {
147
6
            assert!(
148
6
                matches!(&outcome, Outcome::CompileError(message) if message.contains("shared budget")),
149
                "depth {depth}: {outcome:?}"
150
            );
151
        }
152
    }
153
1
}
154

            
155
/// The resource error is reached with the stack to spare: half the default
156
/// test thread's.
157
#[test]
158
1
fn a_deep_block_nest_ends_in_a_resource_error_on_a_one_mib_stack() {
159
1
    let handle = std::thread::Builder::new()
160
1
        .stack_size(1024 * 1024)
161
3
        .spawn(|| [16, 20, 40].map(|depth| block_passes(depth).0).concat())
162
1
        .expect("spawn bounded-stack thread");
163
1
    let outcomes = handle.join().expect("must not overflow the stack");
164
1
    assert_eq!(outcomes.len(), 6);
165
1
    for outcome in outcomes {
166
6
        assert!(
167
6
            matches!(&outcome, Outcome::CompileError(message) if message.contains("shared budget")),
168
            "{outcome:?}"
169
        );
170
    }
171
1
}
172

            
173
#[test]
174
1
fn helper_names_differ_by_slot_type_and_pair_element() {
175
    use super::next_monomorph_helper_name;
176
    use crate::ast::PairElement;
177
    use crate::compiler::context::monomorph::{MonomorphKey, Slot};
178
    let key = |ty| MonomorphKey {
179
4
        name: "f".to_string(),
180
4
        definition: 1,
181
4
        epoch: 0,
182
4
        params: vec![WasmType::I32],
183
4
        closures: vec![None],
184
4
        slots: vec![Slot {
185
4
            name: "x".to_string(),
186
4
            ty,
187
4
            cell: false,
188
4
        }],
189
4
    };
190
4
    let name = |ty| next_monomorph_helper_name(&key(ty), &[WasmType::I32]);
191
1
    assert_ne!(name(WasmType::I32), name(WasmType::Ratio));
192
1
    assert_ne!(
193
1
        name(WasmType::PairRef(PairElement::I32)),
194
1
        name(WasmType::PairRef(PairElement::Ratio))
195
    );
196
1
}
197

            
198
const WALK: &str = "(defun walk (f n) (if (= n 0) 0 (+ (funcall f n) (walk f (- n 1)))))";
199
const WALK_SCALAR: &str =
200
    "(defun walk (f n) (if (= n 0/1) 0/1 (+ (funcall f n) (walk f (- n 1/1)))))";
201

            
202
#[test]
203
1
fn a_recursive_defun_passes_its_lambda_parameter_on() {
204
    let source =
205
1
        format!("{WALK_SCALAR} (walk (lambda (k) k) (index->scalar (+ 3 (entity-count))))");
206
1
    assert_eq!(outcomes(&source).first(), ratio(6, 1).first());
207
1
}
208

            
209
#[test]
210
1
fn two_lambdas_of_one_signature_get_their_own_helpers() {
211
1
    let source = format!(
212
1
        "{WALK_SCALAR} (let ((n (index->scalar (+ 2 (entity-count))))) \
213
         (+ (walk (lambda (k) k) n) (walk (lambda (k) (* k 2/1)) n)))"
214
    );
215
1
    assert_eq!(outcomes(&source).first(), ratio(9, 1).first());
216
1
}
217

            
218
#[test]
219
1
fn a_defun_calls_its_lambda_parameter() {
220
1
    let source = "(defun app (f v) (funcall f v)) (app (lambda (x) (+ x 1)) 4)";
221
1
    assert_eq!(outcomes(source), index(5));
222
1
}
223

            
224
#[test]
225
1
fn an_index_count_into_a_lambda_parameter_compiles_the_lambda_for_it() {
226
1
    let source = format!("{WALK} (walk (lambda (k) k) (+ 3 (entity-count)))");
227
1
    assert_eq!(outcomes(&source).first(), index(6).first());
228
1
}
229

            
230
#[test]
231
1
fn a_function_in_head_position_wins_over_a_closure_parameter() {
232
1
    let source = "(defun f (x) 100) (defun app (f v) (f v)) (app (lambda (x) (+ x 1)) 4)";
233
1
    assert_eq!(outcomes(source), index(100));
234
1
}
235

            
236
#[test]
237
1
fn a_function_argument_the_body_never_uses_is_not_compiled() {
238
1
    assert_eq!(
239
1
        outcomes("(defun k (f v) v) (k (lambda (x) (car x)) 4)"),
240
1
        index(4)
241
    );
242
1
}
243

            
244
#[test]
245
1
fn funcall_reaches_a_closure_variable_named_like_a_function() {
246
1
    let source = "(defun f (x) 100) (let ((f (lambda (x) (+ x 1)))) (funcall f 4))";
247
1
    assert_eq!(outcomes(source), index(5));
248
1
}
249

            
250
#[test]
251
1
fn an_intermediate_binding_keeps_the_function_head() {
252
1
    let source = "(defun f (x) 100) (defun app (f v) (f v)) (let ((f 3)) (app (lambda (x) 2) 4))";
253
1
    assert_eq!(outcomes(source), index(100));
254
1
}
255

            
256
#[test]
257
1
fn a_macro_expanding_to_funcall_of_the_parameter_lifts_it() {
258
1
    let source = "(defmacro call-it (v) (list 'funcall 'f v)) \
259
1
                  (defun app (f v) (call-it v)) (app (lambda (x) (+ x 1)) 4)";
260
1
    assert_eq!(outcomes(source), index(5));
261
1
}