1
// Skipped under Miri: spawns the built nms binary (which runs wasm via
2
// wasmtime); subprocess execution and Cranelift can't run under Miri.
3
#![cfg(not(miri))]
4

            
5
//! Smoke tests for the `nms --test PATH` subcommand. Invokes the
6
//! built binary so the runner's argv/exit-code contract is what CI
7
//! actually checks: a non-zero exit code is the only signal an
8
//! external harness sees when a deftest fails.
9

            
10
mod common;
11

            
12
use std::path::PathBuf;
13
use std::process::Command;
14

            
15
#[cfg(unix)]
16
use common::{
17
    assert_fails_cleanly_with, assert_nms_source_prints_with_stack_limit, run_nms_with_stack_limit,
18
};
19
use common::{nms_bin, tempfile_dir};
20

            
21
4
fn samples_dir() -> PathBuf {
22
4
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23
4
        .parent()
24
4
        .unwrap()
25
4
        .join("nomiscript/tests/nms_runner_samples")
26
4
}
27

            
28
#[test]
29
1
fn test_subcommand_runs_all_files_in_dir() {
30
1
    let out = Command::new(nms_bin())
31
1
        .arg("--test")
32
1
        .arg(samples_dir())
33
1
        .output()
34
1
        .expect("invoke nms");
35
1
    let stdout = String::from_utf8_lossy(&out.stdout);
36
1
    let stderr = String::from_utf8_lossy(&out.stderr);
37
1
    assert!(
38
1
        out.status.success(),
39
        "expected success, got {:?}\nstdout: {stdout}\nstderr: {stderr}",
40
        out.status
41
    );
42
1
    assert!(stdout.contains("0 failed"), "stdout: {stdout}");
43
1
}
44

            
45
#[test]
46
1
fn test_subcommand_accepts_single_file() {
47
1
    let path = samples_dir().join("arithmetic.nms");
48
1
    let out = Command::new(nms_bin())
49
1
        .arg("--test")
50
1
        .arg(&path)
51
1
        .output()
52
1
        .expect("invoke nms");
53
1
    assert!(out.status.success(), "stderr: {:?}", out.stderr);
54
1
    let stdout = String::from_utf8_lossy(&out.stdout);
55
1
    assert!(stdout.contains("5 passed"), "stdout: {stdout}");
56
1
}
57

            
58
#[test]
59
1
fn long_and_or_chains_do_not_overflow_the_compiler_stack() {
60
    // Regression: a naive recursive rewrite of `and`/`or` into nested IFs
61
    // (`(and nil t t t ... 50000 times)`) used to recurse the compiler's
62
    // native stack to build/compile the tree, aborting the WHOLE process
63
    // with SIGABRT. Run as a genuine subprocess (not in-process) so a
64
    // regression here crashes only the child — this test can then assert
65
    // on that crash instead of taking the whole test binary down with it.
66
1
    let path = samples_dir().join("long_and_or_chains.nms");
67
1
    let out = Command::new(nms_bin())
68
1
        .arg("--test")
69
1
        .arg(&path)
70
1
        .output()
71
1
        .expect("invoke nms");
72
    #[cfg(unix)]
73
    {
74
        use std::os::unix::process::ExitStatusExt;
75
1
        assert_eq!(
76
1
            out.status.signal(),
77
1
            None,
78
            "nms subprocess was killed by a signal (status: {:?}) — likely a native \
79
             stack overflow (SIGABRT) compiling a long AND/OR chain",
80
            out.status
81
        );
82
    }
83
1
    let stdout = String::from_utf8_lossy(&out.stdout);
84
1
    let stderr = String::from_utf8_lossy(&out.stderr);
85
1
    assert!(
86
1
        out.status.success(),
87
        "expected success, got {:?}\nstdout: {stdout}\nstderr: {stderr}",
88
        out.status
89
    );
90
1
    assert!(stdout.contains("4 passed"), "stdout: {stdout}");
91
1
}
92

            
93
/// Recursing once per clause overflows a 2 MiB stack from ~1000 clauses
94
/// (binding position) and ~500 (stack position); 2000 keeps a 2x margin.
95
const LONG_COND_CHAIN_CLAUSE_COUNT: usize = 2_000;
96
const LONG_COND_CHAIN_STACK_KIB: u32 = 2048;
97

            
98
2
fn long_cond_chain_clauses() -> String {
99
2
    "(nil) ".repeat(LONG_COND_CHAIN_CLAUSE_COUNT)
100
2
}
101

            
102
#[test]
103
#[cfg(unix)]
104
1
fn long_cond_chain_in_binding_position_does_not_overflow_the_compiler_stack() {
105
    // Regression: a naive recursive rewrite of a long flat COND's
106
    // constant-false clause prefix (`(cond (nil) (nil) ... (t 7))`) used to
107
    // self-recurse once per clause to build/compile the chain, aborting the
108
    // WHOLE process with SIGABRT under a 2 MiB stack. This covers the eval
109
    // path (a `let` binding's initializer).
110
1
    let source = format!("(let ((x (cond {}(t 7)))) x)\n", long_cond_chain_clauses());
111
1
    assert_nms_source_prints_with_stack_limit(
112
1
        "nms_long_cond_chain_binding_",
113
1
        &source,
114
1
        "7",
115
1
        LONG_COND_CHAIN_STACK_KIB,
116
1
    );
117
1
}
118

            
119
#[test]
120
#[cfg(unix)]
121
1
fn long_cond_chain_in_stack_position_does_not_overflow_the_compiler_stack() {
122
    // Same regression as above, covering the stack path (COND as a bare
123
    // top-level value-producing form).
124
1
    let source = format!("(cond {}(t 7))\n", long_cond_chain_clauses());
125
1
    assert_nms_source_prints_with_stack_limit(
126
1
        "nms_long_cond_chain_stack_",
127
1
        &source,
128
1
        "7",
129
1
        LONG_COND_CHAIN_STACK_KIB,
130
1
    );
131
1
}
132

            
133
#[test]
134
#[cfg(unix)]
135
1
fn cond_clauses_with_bodies_iterate_under_a_constrained_native_stack() {
136
    // Codex regression: constant-false COND clauses WITH A BODY (not just
137
    // bodyless ones) used to recurse through `if_form` once per clause —
138
    // `(and t (cond (nil 8) (nil 8) ... (t 7)))` with 128 such clauses
139
    // SIGABRTs under a 2 MiB stack (an 8 MiB stack survives it, masking the
140
    // bug). Constant-test clauses, with or without a body, now iterate.
141
1
    let clauses = "(nil 8) ".repeat(128);
142
1
    let source = format!("(and t (cond {clauses}(t 7)))\n");
143
1
    assert_nms_source_prints_with_stack_limit("nms_cond_body_clauses_2mib_", &source, "7", 2048);
144
1
}
145

            
146
/// The nomiscript source shape (a `(cond ...)` or `(and ...)`) that
147
/// exercises exactly `count` genuinely-runtime clauses/operands — each
148
/// built from a non-foldable `(primary-entity-idx)` call so the compiler
149
/// cannot constant-fold past the recursive runtime-guard path
150
/// `MAX_SHARED_RECURSION_DEPTH` protects.
151
3
fn runtime_chain_source(head: &str, count: usize) -> String {
152
3
    match head {
153
        "COND" => {
154
2
            let clauses: String = (0..count)
155
144
                .map(|i| format!("((= (primary-entity-idx) {}) {i}) ", i + 1))
156
                .collect();
157
2
            format!("(cond {clauses}(t 999))\n")
158
        }
159
        "AND" => {
160
1
            let chain: String = (0..count)
161
128
                .map(|i| format!("(= (primary-entity-idx) {}) ", i + 1000))
162
                .collect();
163
1
            format!("(and {chain}999)\n")
164
        }
165
        _ => unreachable!("only COND/AND are exercised here"),
166
    }
167
3
}
168

            
169
#[test]
170
#[cfg(unix)]
171
1
fn cond_runtime_chain_past_the_old_depth_ceiling_compiles_and_runs() {
172
    // COND's runtime-clause chain is walked in a loop and charges no shared
173
    // recursion budget, so 128 runtime clauses compile and run under a
174
    // 2 MiB stack. AND/OR (below) still recurse and keep the ceiling.
175
1
    let source = runtime_chain_source("COND", 128);
176
1
    assert_nms_source_prints_with_stack_limit("nms_cond_depth_ceiling_", &source, "999", 2048);
177
1
}
178

            
179
#[test]
180
#[cfg(unix)]
181
1
fn and_runtime_chain_past_the_depth_ceiling_errors_not_crashes() {
182
    // Same reasoning as the COND test above: `MAX_SHARED_RECURSION_DEPTH`
183
    // is the sole ceiling.
184
1
    let source = runtime_chain_source("AND", 128);
185
1
    let out = run_nms_with_stack_limit("nms_and_depth_ceiling_", &source, 2048);
186
1
    assert_fails_cleanly_with(&out, "shared budget");
187
1
}
188

            
189
#[test]
190
#[cfg(unix)]
191
1
fn cond_runtime_chain_under_the_depth_ceiling_still_runs_under_a_constrained_stack() {
192
    // A realistic-depth genuinely-runtime chain (well under
193
    // `MAX_SHARED_RECURSION_DEPTH`) still compiles and runs correctly
194
    // under the same constrained 2 MiB stack.
195
1
    let source = runtime_chain_source("COND", 16);
196
1
    assert_nms_source_prints_with_stack_limit("nms_cond_depth_ok_", &source, "999", 2048);
197
1
}
198

            
199
/// A nomiscript source combining four INDEPENDENTLY-ceilinged compile-time
200
/// recursion families, each nested inside the last: `defun_depth` chained
201
/// defuns (f0 calls f1 calls f2 … the last calls `(m0)`), `macro_depth`
202
/// chained macro expansions (m0 expands to m1 expands to m2 … the last
203
/// expands to `9`), then a top-level form that runs an `and_operands`-long
204
/// genuinely-runtime AND chain followed by a `cond_clauses`-long
205
/// genuinely-runtime COND, whose final `(t (f0))` clause enters the
206
/// defun/macro chain. Each family alone can stay individually under its own
207
/// ceiling while the combination still exhausts a constrained native stack
208
/// (`primary-entity-idx` — a non-foldable entity accessor — is what forces
209
/// each AND/COND test to be GENUINELY runtime rather than constant-folded).
210
2
fn combined_recursion_source(
211
2
    defun_depth: usize,
212
2
    macro_depth: usize,
213
2
    and_operands: usize,
214
2
    cond_clauses: usize,
215
2
) -> String {
216
2
    let mut lines = Vec::new();
217
2
    for i in 0..defun_depth {
218
32
        let body = if i + 1 < defun_depth {
219
30
            format!("(f{})", i + 1)
220
        } else {
221
2
            "(m0)".to_string()
222
        };
223
32
        lines.push(format!("(defun f{i} () {body})"));
224
    }
225
2
    for i in 0..macro_depth {
226
62
        let body = if i + 1 < macro_depth {
227
60
            format!("(m{})", i + 1)
228
        } else {
229
2
            "9".to_string()
230
        };
231
62
        lines.push(format!("(defmacro m{i} () '{body})"));
232
    }
233
2
    let and_preds = "(= (primary-entity-idx) 0) ".repeat(and_operands);
234
2
    let cond_clauses_src = "((= (primary-entity-idx) 1) 1) ".repeat(cond_clauses);
235
2
    lines.push(format!(
236
2
        "(and {and_preds}(cond {cond_clauses_src}(t (f0))))"
237
2
    ));
238
2
    lines.join("\n") + "\n"
239
2
}
240

            
241
#[test]
242
#[cfg(unix)]
243
1
fn combined_recursion_families_do_not_overflow_the_compiler_stack() {
244
    // Codex regression: 30 nested defuns + 60 nested macro expansions + a
245
    // 31-operand runtime AND + a 31-clause runtime COND — every individual
246
    // counter (defun inlining ≤ 32, macro expansion ≤ 64, AND/OR ≤ 32,
247
    // COND ≤ 32) stays under its OWN ceiling, but nothing previously
248
    // bounded the combination, and their native-stack costs add up. Must
249
    // now fail with the STRUCTURED shared-budget error, never a crash.
250
1
    let source = combined_recursion_source(30, 60, 31, 31);
251
1
    let out = run_nms_with_stack_limit("nms_combined_recursion_", &source, 2048);
252
1
    assert_fails_cleanly_with(&out, "shared budget");
253
1
}
254

            
255
#[test]
256
#[cfg(unix)]
257
1
fn combined_recursion_families_under_the_shared_budget_still_run_under_a_constrained_stack() {
258
    // A small, realistic mix of all four families together — well under
259
    // the shared ceiling — still compiles and runs correctly under the
260
    // same constrained 2 MiB stack.
261
1
    let source = combined_recursion_source(2, 2, 2, 2);
262
1
    assert_nms_source_prints_with_stack_limit("nms_combined_recursion_ok_", &source, "9", 2048);
263
1
}
264

            
265
#[test]
266
1
fn test_subcommand_nonzero_exit_on_failure() {
267
1
    let dir = tempfile_dir("nms_runner_failure_");
268
1
    std::fs::write(
269
1
        dir.join("a.nms"),
270
1
        "(deftest will-fail (assert-equal 1 2))\n",
271
1
    )
272
1
    .unwrap();
273
1
    let out = Command::new(nms_bin())
274
1
        .arg("--test")
275
1
        .arg(&dir)
276
1
        .output()
277
1
        .expect("invoke nms");
278
1
    assert!(!out.status.success(), "expected non-zero exit on failure");
279
1
    let stdout = String::from_utf8_lossy(&out.stdout);
280
1
    assert!(stdout.contains("1 failed"), "stdout: {stdout}");
281
1
}
282

            
283
#[test]
284
1
fn coverage_flag_appends_coverage_section() {
285
1
    let out = Command::new(nms_bin())
286
1
        .arg("--test")
287
1
        .arg(samples_dir())
288
1
        .arg("--coverage")
289
1
        .output()
290
1
        .expect("invoke nms");
291
1
    assert!(out.status.success(), "stderr: {:?}", out.stderr);
292
1
    let stdout = String::from_utf8_lossy(&out.stdout);
293
1
    assert!(stdout.contains("--- coverage ---"), "stdout: {stdout}");
294
    // sandbox nms has no host fns registered, so the dump is the
295
    // explanatory placeholder rather than a native-fn list. The rpc
296
    // crate's unit tests assert the populated path.
297
1
    assert!(
298
1
        stdout.contains("(no native fns referenced)"),
299
        "stdout: {stdout}"
300
    );
301
1
}
302

            
303
#[test]
304
1
fn invalid_profile_strategy_errors_with_clear_message() {
305
1
    let out = Command::new(nms_bin())
306
1
        .arg("--profile=bogus")
307
1
        .arg("-e")
308
1
        .arg("(+ 1 2)")
309
1
        .output()
310
1
        .expect("invoke nms");
311
1
    assert!(!out.status.success(), "expected non-zero exit");
312
1
    let stderr = String::from_utf8_lossy(&out.stderr);
313
1
    assert!(
314
1
        stderr.contains("unknown --profile strategy"),
315
        "stderr: {stderr}"
316
    );
317
1
}
318

            
319
#[test]
320
1
fn perfmap_profile_strategy_accepted() {
321
    // PerfMap is the lighter Linux profiler agent. We don't validate
322
    // the output file (path depends on PID); just confirm the flag is
323
    // accepted and the eval completes.
324
1
    let out = Command::new(nms_bin())
325
1
        .arg("--profile=perfmap")
326
1
        .arg("-e")
327
1
        .arg("(+ 2 2)")
328
1
        .output()
329
1
        .expect("invoke nms");
330
1
    assert!(out.status.success(), "stderr: {:?}", out.stderr);
331
1
    let stdout = String::from_utf8_lossy(&out.stdout);
332
1
    assert!(stdout.contains('4'), "stdout: {stdout}");
333
1
}
334

            
335
#[test]
336
1
fn test_subcommand_errors_on_empty_dir() {
337
1
    let dir = tempfile_dir("nms_runner_empty_");
338
1
    let out = Command::new(nms_bin())
339
1
        .arg("--test")
340
1
        .arg(&dir)
341
1
        .output()
342
1
        .expect("invoke nms");
343
1
    assert!(!out.status.success(), "expected non-zero exit on empty dir");
344
1
}