1
//! Acceptance rows for plan 0011 Phase 0's `Budget` and depth guards: a
2
//! large datum fold and a deep macro expansion each exhaust the shared work
3
//! budget with a structured error instead of running unboundedly; a
4
//! 5000-clause `COND` compiles without the compiler's own native stack ever
5
//! overflowing — surviving the test process at all is the proof of that
6
//! last part. Row E (`C_30`) is covered here only for compile-time
7
//! survival; its "gives `t`" half needs an actual run and lives in
8
//! `rpc::session::tests::plan0011_phase3_acceptance_tests` (row R3 sits
9
//! beside it there for the same reason).
10

            
11
use nomiscript::{Compiler, Reader, SymbolTable};
12

            
13
use super::common::{
14
    compile_and_validate, compile_expect_error, validate_wasm, wrap_with_runtime_i32,
15
};
16

            
17
/// Builds `C_k` per plan row E: `C0 = t`, `Ck = (cond (Ck-1 t))`.
18
2
fn cond_chain_source(depth: u32) -> String {
19
2
    let mut src = "T".to_string();
20
2
    for _ in 0..depth {
21
33
        src = format!("(cond ({src} T))");
22
    }
23
2
    src
24
2
}
25

            
26
/// `C_30` compiles inside the work budget. Before plan 0011 Phase 3 the
27
/// `eval_value` classify-then-apply doubling (`E(k) = 2*E(k-1)`) exhausted
28
/// it, which is what an earlier version of this test pinned as a budget
29
/// error. (Its "gives `t`" half needs an actual run — see this module's doc
30
/// comment.)
31
#[test]
32
1
fn c30_cond_chain_compiles_within_the_work_budget() {
33
1
    let src = cond_chain_source(30);
34
1
    let program = Reader::parse(&src).unwrap_or_else(|e| panic!("parse {src:?}: {e}"));
35
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
36
1
    let mut compiler = Compiler::new();
37
1
    let wasm = compiler
38
1
        .compile(&program, &mut symbols)
39
        .unwrap_or_else(|e| panic!("compile {src:?}: {e}"));
40
1
    validate_wasm(&wasm);
41
1
}
42

            
43
/// A much shallower chain must compile normally and fold to `t` — the
44
/// budget must not reject legitimate, small programs of the same shape.
45
#[test]
46
1
fn a_shallow_cond_chain_still_compiles() {
47
1
    let src = cond_chain_source(3);
48
1
    compile_and_validate(&format!("(defvar *r* {src})"));
49
1
}
50

            
51
5003
fn cond_clause(i: u32) -> String {
52
5003
    format!("((> IDX {i}) {i})")
53
5003
}
54

            
55
/// Row R3 / the plan's "5000-clause COND" bullet: a runtime-clause chain is
56
/// walked in a loop and emitted as one flat block, so this long a chain
57
/// compiles and validates without native recursion.
58
#[test]
59
1
fn five_thousand_runtime_clause_cond_compiles_without_recursing() {
60
1
    let clauses: String = (0..5_000u32).map(cond_clause).collect::<Vec<_>>().join(" ");
61
1
    let src = wrap_with_runtime_i32(&format!("(cond {clauses} (t -1))"));
62
1
    compile_and_validate(&src);
63
1
}
64

            
65
/// A small runtime-clause `COND` (well under the recursion ceiling) must
66
/// still compile — the guard must not reject ordinary programs.
67
#[test]
68
1
fn a_few_runtime_clauses_still_compile() {
69
1
    let clauses: String = (0..3u32).map(cond_clause).collect::<Vec<_>>().join(" ");
70
1
    let src = wrap_with_runtime_i32(&format!("(cond {clauses} (t -1))"));
71
1
    compile_and_validate(&src);
72
1
}
73

            
74
/// A macro whose body constant-folds a huge `LIST` call before ever
75
/// returning its expansion: evaluating each of the 2,000,000 elements
76
/// charges `eval_value` once inside the macro's private expansion
77
/// environment (`expand_macro`), and `expand_macro_then` additionally
78
/// charges the produced expansion's own `datum::cost` — either charge
79
/// alone exhausts the budget with a structured error.
80
#[test]
81
1
fn a_macro_body_building_a_huge_datum_exhausts_the_budget() {
82
1
    let elements: String = std::iter::repeat_n("1", 2_000_000)
83
1
        .collect::<Vec<_>>()
84
1
        .join(" ");
85
1
    let src = format!("(defmacro biglist () (list {elements})) (defvar *r* (biglist))");
86
1
    let err = compile_expect_error(&src);
87
1
    assert!(
88
1
        err.contains("compile-time work budget exceeded"),
89
        "expected a budget error, got: {err}"
90
    );
91
1
}
92

            
93
/// A handful of expansions of the same macro must still compile normally.
94
#[test]
95
1
fn a_few_macro_expansions_still_compile() {
96
1
    let src = "(defmacro noop () 1) (+ (noop) (noop) (noop))";
97
1
    compile_and_validate(src);
98
1
}
99

            
100
/// A fold over a huge constant list is charged upfront by its length
101
/// (`fold::constant_fold_fold`) — large enough to exceed `MAX_ELAB_WORK`
102
/// without ever running the per-element loop.
103
#[test]
104
1
fn folding_a_huge_constant_list_exhausts_the_budget() {
105
1
    let elements: String = std::iter::repeat_n("1", 2_000_000)
106
1
        .collect::<Vec<_>>()
107
1
        .join(" ");
108
1
    let src = format!("(fold (lambda (acc x) (+ acc x)) 0 (list {elements}))");
109
1
    let err = compile_expect_error(&src);
110
1
    assert!(
111
1
        err.contains("compile-time work budget exceeded"),
112
        "expected a budget error, got: {err}"
113
    );
114
1
}
115

            
116
/// Folding a small constant list still compiles and folds to a constant.
117
#[test]
118
1
fn folding_a_small_constant_list_still_compiles() {
119
1
    compile_and_validate("(fold (lambda (acc x) (+ acc x)) 0 (list 1 2 3))");
120
1
}
121

            
122
/// A 25-runtime-clause `COND` (past the shared recursion ceiling of 24) is
123
/// also accepted where the eval mirror classifies it first: a `DEFVAR`
124
/// initializer.
125
#[test]
126
1
fn a_25_runtime_clause_cond_compiles_as_a_defvar_initializer() {
127
25
    let clauses: String = (0..25u32).map(|i| format!("((= IDX {i}) {i}) ")).collect();
128
1
    let src = wrap_with_runtime_i32(&format!("(defvar *r* (cond {clauses}(t -1)))"));
129
1
    compile_and_validate(&src);
130
1
}
131

            
132
/// Same, as a `LET` binding initializer.
133
#[test]
134
1
fn a_25_runtime_clause_cond_compiles_as_a_let_initializer() {
135
25
    let clauses: String = (0..25u32).map(|i| format!("((= IDX {i}) {i}) ")).collect();
136
1
    let src = wrap_with_runtime_i32(&format!("(let ((x (cond {clauses}(t -1)))) x)"));
137
1
    compile_and_validate(&src);
138
1
}
139

            
140
/// Folding cons onto a flat accumulator is linear work, not quadratic: the
141
/// datum depth check never charges the accumulator's size to the budget.
142
#[test]
143
1
fn consing_a_1500_element_fold_stays_within_the_budget() {
144
1500
    let elements: String = (0..1500u32).map(|i| format!("{i} ")).collect();
145
1
    compile_and_validate(&format!(
146
1
        "(length (fold (lambda (acc x) (cons x acc)) nil (list {elements})))"
147
1
    ));
148
1
}
149

            
150
/// The nested list is built at macro-expansion time: a FOLD in ordinary
151
/// code is not fold-safe (0014 Stage 2) and builds its list at runtime,
152
/// where no compile-time depth ceiling applies.
153
2
fn nesting_fold_source(levels: u32) -> String {
154
300
    let elements: String = (0..levels).map(|i| format!("{i} ")).collect();
155
2
    format!(
156
2
        "(defmacro deep () (list 'quote (fold (lambda (acc x) (list acc x)) nil (list {elements})))) \
157
         (length (deep))"
158
    )
159
2
}
160

            
161
/// `MAX_ELAB_DEPTH` counts user-visible list levels: a quoted nested list
162
/// costs one level per list, not two, so 100 levels fit under the 128
163
/// ceiling while 200 are refused.
164
#[test]
165
1
fn a_fold_nesting_100_list_levels_compiles_and_200_are_refused() {
166
1
    compile_and_validate(&nesting_fold_source(100));
167
1
    let err = compile_expect_error(&nesting_fold_source(200));
168
1
    assert!(err.contains("elaboration depth limit"), "{err}");
169
1
}
170

            
171
/// A LET nested in a LET init, each with a nil accumulator, evaluates its
172
/// inits once per level, so the work stays linear in the depth.
173
#[test]
174
1
fn nested_lets_with_nil_accumulators_compile_within_the_work_budget() {
175
1
    let mut src = "(entity-count)".to_string();
176
1
    for _ in 0..16 {
177
16
        src = format!("(let ((a {src}) (b nil)) (setf b (cons a b)) a)");
178
    }
179
1
    compile_and_validate(&format!("(list {src})"));
180
1
}
181

            
182
/// A chain of defuns, each calling the previous one in a LET init beside a
183
/// nil accumulator, evaluates each init once.
184
#[test]
185
1
fn chained_defuns_with_nil_accumulators_compile_within_the_work_budget() {
186
1
    let defuns: String = (1..=14)
187
14
        .map(|i| {
188
14
            format!(
189
14
                "(defun f{i} (x) (let ((y (f{} x)) (acc nil)) (setf acc (cons y acc)) (car acc)))",
190
14
                i - 1
191
            )
192
14
        })
193
        .collect();
194
1
    compile_and_validate(&format!(
195
1
        "(defun f0 (x) x) {defuns} (list (f14 (entity-count)))"
196
1
    ));
197
1
}