1
//! A malformed script must be refused with `Error::Resource`, never abort the
2
//! process by overflowing the native stack of a small compile thread.
3

            
4
use nomiscript::{Compiler, Error, Reader, SymbolTable};
5

            
6
const SELF_BUILDING_CLOSURE: &str = "(defun mk (a) (lambda (x) (let ((p4 4)) (let ((p3 3)) \
7
     (let ((p2 2)) (let ((p1 1)) (let ((p0 0)) (let ((g (mk a))) (funcall g x))))))))) \
8
     (funcall (mk 1) 2)";
9

            
10
58
fn compile_on_thread(stack_bytes: usize, src: &str) -> Result<Vec<u8>, Error> {
11
58
    let src = src.to_string();
12
58
    let worker = std::thread::Builder::new()
13
58
        .stack_size(stack_bytes)
14
58
        .spawn(move || {
15
58
            let program = Reader::parse(&src)?;
16
58
            let mut symbols = SymbolTable::with_builtins_for_wasm();
17
58
            Compiler::new().compile(&program, &mut symbols)
18
58
        })
19
        .map_err(|e| Error::Compile(e.to_string()))?;
20
58
    worker
21
58
        .join()
22
        .unwrap_or_else(|_| Err(Error::Compile("compile thread panicked".to_string())))
23
58
}
24

            
25
#[test]
26
1
fn every_stack_size_reaches_the_shared_ceiling() {
27
1
    for kib in [512, 1024, 8192] {
28
3
        let outcome = compile_on_thread(kib * 1024, SELF_BUILDING_CLOSURE);
29
3
        assert!(
30
3
            matches!(&outcome, Err(Error::Resource(m)) if m.contains("shared budget")),
31
            "{kib} KiB stack: {outcome:?}"
32
        );
33
    }
34
1
}
35

            
36
19
fn nesting_macro(level: usize, width: usize, wrap: &str) -> String {
37
19
    format!(
38
19
        "(defmacro m (n) (if (= n 0) 0 (do ((i 0 (+ i 1)) (x (list 'm (- n 1)) {wrap})) \
39
19
         ((= i {width}) x)))) (m {level})"
40
    )
41
19
}
42

            
43
3
fn nested_lets(depth: usize) -> String {
44
180
    let opens: String = (0..depth).map(|i| format!("(let ((p{i} {i})) ")).collect();
45
3
    format!("{opens}0{}", ")".repeat(depth))
46
3
}
47

            
48
15
fn let_chain_macro(width: usize) -> String {
49
15
    let opens = "(let ((v 1)) ".repeat(width);
50
15
    let closes = ")".repeat(width);
51
15
    format!("(defmacro m (n) (if (= n 0) 0 `{opens}(m ,(- n 1)){closes})) ")
52
15
}
53

            
54
3
fn template_let_chain(width: usize, level: usize) -> String {
55
3
    format!("{}(m {level})", let_chain_macro(width))
56
3
}
57

            
58
const COMPOSED_SCOPES: [(&str, &str); 4] = [
59
    (
60
        "s-do",
61
        "(let ((s 0)) (do ((i 0 (+ i 1))) ((= i 2) s) (setf s (+ s 1)) (funcall (lambda () i)) (m 23)))",
62
    ),
63
    (
64
        "s-defun",
65
        "(defun f (x) (setf x 2) (funcall (lambda () x)) (m 23)) (f 1)",
66
    ),
67
    (
68
        "s-lambdaparam",
69
        "(funcall (lambda (x) (setf x 2) (funcall (lambda () x)) (m 23)) 1)",
70
    ),
71
    ("s-print", "(print (list 1 (m 23)))"),
72
];
73

            
74
3
fn abort_inputs() -> Vec<(String, String)> {
75
3
    let mut inputs = vec![
76
3
        ("let60".to_string(), nested_lets(60)),
77
3
        (
78
3
            "macdeeplet".to_string(),
79
3
            "(defmacro w () (do ((i 0 (+ i 1)) (x 0 (list 'let (list (list 'v i)) x))) \
80
3
             ((= i 120) x))) (w)"
81
3
                .to_string(),
82
3
        ),
83
    ];
84
3
    for level in [6, 23] {
85
6
        inputs.push((
86
6
            format!("mc-plus-L{level}-W120"),
87
6
            nesting_macro(level, 120, "(list '+ 1 x)"),
88
6
        ));
89
6
        inputs.push((
90
6
            format!("mc-if-L{level}-W120"),
91
6
            nesting_macro(level, 120, "(list 'if 't x 0)"),
92
6
        ));
93
    }
94
3
    inputs.push((
95
3
        "mc-let-L23-W100".to_string(),
96
3
        nesting_macro(23, 100, "(list 'let (list (list 'v i)) x)"),
97
3
    ));
98
3
    inputs.push(("let57-top-L23".to_string(), template_let_chain(57, 23)));
99
3
    for (name, scope) in COMPOSED_SCOPES {
100
12
        inputs.push((
101
12
            format!("{name}-L23"),
102
12
            format!("{}{scope}", let_chain_macro(57)),
103
12
        ));
104
    }
105
3
    inputs.push((
106
3
        "cf3-05".to_string(),
107
3
        include_str!("acceptance/cf3-05-factory-lambda-binds-factory.nms").to_string(),
108
3
    ));
109
3
    inputs.push((
110
3
        "5-let-factory".to_string(),
111
3
        SELF_BUILDING_CLOSURE.to_string(),
112
3
    ));
113
3
    inputs
114
3
}
115

            
116
#[test]
117
1
fn deeply_nested_forms_never_abort_on_a_small_stack() {
118
1
    for kib in [512, 1024, 2048] {
119
3
        for (name, src) in &abort_inputs() {
120
42
            let outcome = compile_on_thread(kib * 1024, src);
121
42
            assert!(
122
42
                matches!(&outcome, Ok(_) | Err(Error::Resource(_))),
123
                "{name} on {kib} KiB: {outcome:?}"
124
            );
125
        }
126
    }
127
1
}
128

            
129
/// Macro expansions compose into one tree: two expansions whose summed own depth
130
/// stays at the ceiling compile, one more level each is a resource error.
131
#[test]
132
1
fn composed_expansions_are_bounded_at_the_ceiling() {
133
1
    for kib in [512, 2048] {
134
2
        let at_cap = compile_on_thread(kib * 1024, &nesting_macro(2, 63, "(list '+ 1 x)"));
135
2
        assert!(at_cap.is_ok(), "{kib} KiB at the ceiling: {at_cap:?}");
136
2
        let over = compile_on_thread(kib * 1024, &nesting_macro(2, 64, "(list '+ 1 x)"));
137
2
        assert!(
138
2
            matches!(&over, Err(Error::Resource(m)) if m.contains("nests deeper")),
139
            "{kib} KiB over the ceiling: {over:?}"
140
        );
141
    }
142
1
}
143

            
144
const NESTING_MACRO: &str = "(defmacro w (n) (if (= n 0) 7 (do ((i 0 (+ i 1)) \
145
     (y (list 'w (- n 1)) (list '+ 0 y))) ((= i 120) y))))";
146

            
147
const CAPTURE_NESTING_USE: &str = "(let ((g (lambda (x) (+ x (w 24))))) (funcall g 2))";
148

            
149
4
fn capture_function_chain() -> String {
150
4
    let defs: String = (1..=25)
151
100
        .map(|i| format!("(deff f{i} f{}) ", i + 1))
152
        .rev()
153
        .collect();
154
4
    format!(
155
        "(defmacro deff (name next) (list 'defun name '(x) (do ((i 0 (+ i 1)) \
156
4
         (y (list next 'x) (list '+ 0 y))) ((= i 120) y)))) (defun f26 (x) x) {defs}\
157
         (let ((g (lambda (x) (f1 x)))) (funcall g 2))"
158
    )
159
4
}
160

            
161
9
fn refusal_message(stack_bytes: usize, src: &str) -> String {
162
9
    match compile_on_thread(stack_bytes, src) {
163
9
        Err(Error::Resource(message)) => message,
164
        other => format!("not a resource refusal: {other:?}"),
165
    }
166
9
}
167

            
168
/// The closure capture walk follows macro expansions and function bodies; the
169
/// composed depth must end in the walk's own structured refusal on every stack size.
170
#[test]
171
1
fn the_capture_walk_refuses_composed_depth_on_a_small_stack() {
172
1
    let bare = refusal_message(2 * 1024 * 1024, &format!("{NESTING_MACRO} (w 24)"));
173
1
    assert!(bare.contains("nests deeper than 128 levels"), "{bare}");
174
1
    for kib in [512, 1024, 1536, 2048] {
175
4
        let size = kib * 1024;
176
4
        let nested = refusal_message(size, &format!("{NESTING_MACRO} {CAPTURE_NESTING_USE}"));
177
4
        assert_eq!(nested, bare, "capD24 on {kib} KiB");
178
4
        let chain = refusal_message(size, &capture_function_chain());
179
4
        assert!(
180
4
            chain.contains("shared budget of 24"),
181
            "capfun24 on {kib} KiB: {chain}"
182
        );
183
    }
184
1
}