1
use std::fs;
2
use std::io::{self, BufRead, IsTerminal, Read, Write};
3
use std::path::{Path, PathBuf};
4

            
5
use anyhow::Context as _;
6
use clap::Parser;
7
use scripting::nomiscript::{Reader, Value};
8
use uuid::Uuid;
9

            
10
use nms::interpreter;
11
use scripting::runtime::ProfilerStrategy;
12
mod repl;
13
mod rpc_eval;
14
mod slynk;
15
mod ssh_eval;
16

            
17
97
fn parse_profiler(s: Option<&str>) -> anyhow::Result<ProfilerStrategy> {
18
97
    match s {
19
95
        None => Ok(ProfilerStrategy::None),
20
        Some("jitdump") => Ok(ProfilerStrategy::JitDump),
21
1
        Some("perfmap") => Ok(ProfilerStrategy::PerfMap),
22
1
        Some(other) => Err(anyhow::anyhow!(
23
1
            "unknown --profile strategy '{other}' (expected: jitdump, perfmap)"
24
1
        )),
25
    }
26
97
}
27

            
28
#[derive(Parser)]
29
#[command(name = "nms")]
30
#[command(about = "Nomiscript interpreter", long_about = None)]
31
struct Cli {
32
    /// File to evaluate (use - for stdin)
33
    #[arg(value_name = "FILE")]
34
    file: Option<String>,
35

            
36
    /// Evaluate a string expression
37
    #[arg(short, long, value_name = "EXPR")]
38
    eval: Option<String>,
39

            
40
    /// Compile a source file to WASM bytecode
41
    #[arg(long, value_name = "FILE")]
42
    compile: Option<String>,
43

            
44
    /// Where `--compile` writes the bytecode (default: FILE with a `.wasm`
45
    /// extension, beside the source)
46
    #[arg(short, long, value_name = "FILE", requires = "compile")]
47
    output: Option<String>,
48

            
49
    /// Load and run a pre-compiled WASM file
50
    #[arg(long, value_name = "FILE")]
51
    load: Option<String>,
52

            
53
    /// Use TUI mode for the REPL
54
    #[arg(short, long)]
55
    tui: bool,
56

            
57
    /// Enable debug-level tracing output
58
    #[arg(long)]
59
    debug: bool,
60

            
61
    /// Route forms through `rpc::Session` for the given user, exposing
62
    /// the DB-touching natives (list-accounts, get-commodity, ...).
63
    /// Requires DATABASE_URL. Without this flag, `nms` is a pure language
64
    /// sandbox and the rpc/server crates are dormant.
65
    #[arg(long, value_name = "UUID")]
66
    rpc_user: Option<Uuid>,
67

            
68
    /// Start a SLYNK server on the given TCP port instead of a terminal REPL,
69
    /// so Emacs SLY can drive nomiscript via `M-x sly-connect localhost PORT`.
70
    /// Evaluates through `rpc::Session` — pass `--rpc-user <UUID>` (and set
71
    /// DATABASE_URL) to expose the DB-backed natives; without it the session
72
    /// runs as the nil user.
73
    #[arg(long, value_name = "PORT")]
74
    slynk_port: Option<u16>,
75

            
76
    /// Connect to a remote `nomisync-eval` subsystem over SSH and run
77
    /// forms there instead of a local session. Shells out to the system
78
    /// `ssh`, so authentication (key, ssh-agent, `~/.ssh/config`, or a
79
    /// password prompt) is OpenSSH's job and the SSH identity maps to a
80
    /// nomisync user server-side — no DATABASE_URL is needed locally.
81
    /// Value: `[user@]host`. Combine with `-e`/FILE for one-shot runs,
82
    /// or omit both for an interactive REPL.
83
    #[arg(long, value_name = "[USER@]HOST")]
84
    ssh: Option<String>,
85

            
86
    /// TCP port for `--ssh` (defaults to your ssh config / port 22).
87
    #[arg(long, value_name = "PORT")]
88
    ssh_port: Option<u16>,
89

            
90
    /// Disable inline kitty-graphics rendering of `Value::Bytes`
91
    /// image payloads. Forces the textual `#u8(...)` fallback even
92
    /// when the surrounding terminal advertises kitty support — use
93
    /// this in CI captures and when piping output through a tool
94
    /// that can't strip APC sequences.
95
    #[arg(long)]
96
    no_graphics: bool,
97

            
98
    /// Load every `*.nms` file under PATH (file or directory),
99
    /// then run `(run-tests)`. Exits non-zero if any test failed.
100
    /// PATH defaults to `tests/` when omitted as a bare flag.
101
    #[arg(long, value_name = "PATH")]
102
    test: Option<String>,
103

            
104
    /// With `--test`: also print the `(coverage-dump)` output after
105
    /// the test run. Useful for verifying every native fn the host
106
    /// exposes has at least one test that compiles against it (the
107
    /// parity contract from plan §"All-32 enumeration"). Off by
108
    /// default to keep CI output terse.
109
    #[arg(long)]
110
    coverage: bool,
111

            
112
    /// Enable wasmtime's JitDump profiler — emits a `jit-<pid>.dump`
113
    /// next to the working directory consumable by `perf record` and
114
    /// flame-graph tooling. Linux only; requires building with
115
    /// `--features profile-jitdump` (off by default to avoid the
116
    /// extra dep on non-Linux). Use `perfmap` for the lighter symbol-
117
    /// only variant.
118
    #[arg(long, value_name = "STRATEGY")]
119
    profile: Option<String>,
120
}
121

            
122
/// Render policy for `Value::Bytes` image payloads. Computed once at
123
/// startup from the `--no-graphics` flag + current env + stdout
124
/// terminal-state so every value printer sees the same decision.
125
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126
struct GraphicsPolicy {
127
    inline: bool,
128
}
129

            
130
impl GraphicsPolicy {
131
97
    fn from_cli(no_graphics: bool) -> Self {
132
        // `--no-graphics` or non-TTY stdout disables inline. Otherwise
133
        // we honour the terminal capability check in
134
        // `rpc::chart::env_speaks_kitty`.
135
97
        let inline = !no_graphics
136
37
            && io::stdout().is_terminal()
137
            && rpc::chart::env_speaks_kitty(|name| std::env::var(name).ok());
138
97
        Self { inline }
139
97
    }
140
}
141

            
142
97
fn main() -> anyhow::Result<()> {
143
97
    let cli = Cli::parse();
144
97
    let graphics = GraphicsPolicy::from_cli(cli.no_graphics);
145
97
    let profiler = parse_profiler(cli.profile.as_deref())?;
146

            
147
96
    if let Some(target) = cli.ssh.as_deref() {
148
        return run_ssh_mode(target, cli.ssh_port, &cli);
149
96
    } else if let Some(port) = cli.slynk_port {
150
        return run_slynk_mode(port, cli.rpc_user);
151
96
    } else if let Some(path) = cli.test.as_deref() {
152
6
        return run_test_mode(path, cli.debug, cli.coverage);
153
90
    } else if let Some(user_id) = cli.rpc_user {
154
        run_rpc_mode(user_id, &cli)?;
155
90
    } else if let Some(source) = cli.compile {
156
3
        compile_file(&source, cli.output.as_deref())?;
157
87
    } else if let Some(wasm_path) = cli.load {
158
        load_wasm(&wasm_path, cli.debug, graphics)?;
159
87
    } else if let Some(expr_str) = cli.eval {
160
7
        eval_string(&expr_str, cli.debug, graphics, profiler)?;
161
80
    } else if let Some(file) = cli.file {
162
20
        if file == "-" {
163
            eval_stdin(cli.debug, graphics, profiler)?;
164
        } else {
165
20
            eval_file(&file, cli.debug, graphics, profiler)?;
166
        }
167
60
    } else if cli.tui {
168
        repl::run()?;
169
    } else {
170
60
        plain_repl(cli.debug, graphics)?;
171
    }
172

            
173
90
    Ok(())
174
97
}
175

            
176
/// `nms --slynk-port PORT [--rpc-user UUID]`: serve SLY over SLYNK. Uses a
177
/// multi-thread runtime so the connection's reader task can act on an
178
/// `(:emacs-interrupt)` (epoch-bump the engine) while an eval is in flight on
179
/// the eval task. `user_id` defaults to the nil user when `--rpc-user` is
180
/// omitted; the DB-backed natives then error per-call rather than at startup.
181
fn run_slynk_mode(port: u16, user_id: Option<Uuid>) -> anyhow::Result<()> {
182
    // With a user, the DB-backed natives (list-accounts, set-split-tag, …) run
183
    // through `server::command::*`, which lazily connects to `DATABASE_URL`.
184
    // Verify it up front so a missing env surfaces as a clean startup error
185
    // rather than a panic deep inside the first DB-touching native (matching
186
    // the `--rpc-user` REPL). Without a user, nms is a pure-language sandbox
187
    // and no DB is needed.
188
    let database_url_set = std::env::var("DATABASE_URL")
189
        .map(|url| !url.trim().is_empty())
190
        .unwrap_or(false);
191
    if user_id.is_some() && !database_url_set {
192
        anyhow::bail!(
193
            "--rpc-user needs DATABASE_URL so the DB-backed natives can reach \
194
             Postgres; export it (or drop --rpc-user for a sandbox-only server)"
195
        );
196
    }
197
    let runtime = tokio::runtime::Builder::new_multi_thread()
198
        .enable_all()
199
        .build()
200
        .context("slynk-mode tokio runtime build failed")?;
201
    runtime.block_on(slynk::serve(port, user_id.unwrap_or_else(Uuid::nil)))
202
}
203

            
204
fn run_rpc_mode(user_id: Uuid, cli: &Cli) -> anyhow::Result<()> {
205
    let mut rpc = rpc_eval::RpcEval::new(user_id)?;
206
    if let Some(expr) = cli.eval.as_deref() {
207
        println!("{}", rpc.eval(expr));
208
        return Ok(());
209
    }
210
    if let Some(file) = cli.file.as_deref() {
211
        let content = if file == "-" {
212
            let mut s = String::new();
213
            io::stdin().read_to_string(&mut s)?;
214
            s
215
        } else {
216
            fs::read_to_string(file)?
217
        };
218
        for form in split_forms(&content) {
219
            println!("{}", rpc.eval(&form));
220
        }
221
        return Ok(());
222
    }
223
    rpc_repl(&mut rpc)
224
}
225

            
226
/// `nms --ssh [USER@]HOST`: drive a remote `nomisync-eval` subsystem
227
/// over the system `ssh`. `-e EXPR` runs one form, a FILE argument runs
228
/// each top-level form, and neither yields an interactive REPL — the
229
/// same dispatch shape as `--rpc-user`, but the session lives on the
230
/// server and auth is the SSH identity, so no local DATABASE_URL.
231
fn run_ssh_mode(target: &str, port: Option<u16>, cli: &Cli) -> anyhow::Result<()> {
232
    let mut ssh = ssh_eval::SshEval::connect(target, port)?;
233
    if let Some(expr) = cli.eval.as_deref() {
234
        println!("{}", ssh.eval(expr)?);
235
        return Ok(());
236
    }
237
    if let Some(file) = cli.file.as_deref() {
238
        let content = if file == "-" {
239
            let mut s = String::new();
240
            io::stdin().read_to_string(&mut s)?;
241
            s
242
        } else {
243
            fs::read_to_string(file)?
244
        };
245
        for form in split_forms(&content) {
246
            println!("{}", ssh.eval(&form)?);
247
        }
248
        return Ok(());
249
    }
250
    ssh_repl(&mut ssh)
251
}
252

            
253
/// Line REPL over an [`ssh_eval::SshEval`] connection. Buffers input
254
/// until the form is balanced (same rule as the local REPLs), sends it,
255
/// and prints the response envelope. A transport error (the ssh process
256
/// died / the connection dropped) ends the loop.
257
fn ssh_repl(ssh: &mut ssh_eval::SshEval) -> anyhow::Result<()> {
258
    let stdin = io::stdin();
259
    let mut stdout = io::stdout();
260
    let mut buffer = String::new();
261
    loop {
262
        if buffer.is_empty() {
263
            print!("\nssh-nms> ");
264
        } else {
265
            print!("    ");
266
        }
267
        stdout.flush()?;
268
        let mut line = String::new();
269
        if stdin.lock().read_line(&mut line)? == 0 {
270
            break;
271
        }
272
        if buffer.is_empty() && line.trim().is_empty() {
273
            continue;
274
        }
275
        buffer.push_str(&line);
276
        if Reader::is_incomplete(&buffer) {
277
            continue;
278
        }
279
        let input = buffer.trim();
280
        if !input.is_empty() {
281
            match ssh.eval(input) {
282
                Ok(response) => println!("{response}"),
283
                Err(err) => {
284
                    eprintln!("ssh-eval: {err}");
285
                    break;
286
                }
287
            }
288
        }
289
        buffer.clear();
290
    }
291
    Ok(())
292
}
293

            
294
/// `nms --test PATH`: collect every `*.nms` file under PATH (file
295
/// argument is treated as a single file; directories are walked one
296
/// level), load each into a single Interpreter so test registrations
297
/// accumulate, then call `(run-tests)`. Exits 1 if any test failed.
298
6
fn run_test_mode(path: &str, debug: bool, coverage: bool) -> anyhow::Result<()> {
299
6
    let files = collect_nms_files(path)?;
300
6
    if files.is_empty() {
301
1
        return Err(anyhow::anyhow!("no .nms files found at {path}"));
302
5
    }
303
5
    let mut interp = interpreter::Interpreter::new(debug)?;
304
5
    let use_color = io::stderr().is_terminal();
305
5
    for file in &files {
306
11
        let content = fs::read_to_string(file)?;
307
11
        if let Err(e) = interp.eval(&content) {
308
            eprintln!("loading {}:", file.display());
309
            eprint!("{}", e.render(use_color));
310
            std::process::exit(1);
311
11
        }
312
    }
313
5
    let results = interp
314
5
        .eval("(run-tests)")
315
        .map_err(|e| anyhow::anyhow!("run-tests failed: {}", e.render(use_color)))?;
316
5
    let summary = match results.last() {
317
5
        Some(Value::String(s)) => s.clone(),
318
        Some(other) => scripting::nomiscript::format_value(other),
319
        None => return Err(anyhow::anyhow!("run-tests produced no result")),
320
    };
321
5
    println!("{summary}");
322
5
    if coverage {
323
1
        let cov = interp
324
1
            .eval("(coverage-dump)")
325
            .map_err(|e| anyhow::anyhow!("coverage-dump failed: {}", e.render(use_color)))?;
326
1
        let dump = match cov.last() {
327
1
            Some(Value::String(s)) if s.is_empty() => "(no native fns referenced)".to_string(),
328
            Some(Value::String(s)) => s.clone(),
329
            Some(other) => scripting::nomiscript::format_value(other),
330
            None => "(no coverage output)".to_string(),
331
        };
332
1
        println!("--- coverage ---");
333
1
        println!("{dump}");
334
4
    }
335
5
    if test_summary_failed(&summary) {
336
1
        std::process::exit(1);
337
4
    }
338
4
    Ok(())
339
5
}
340

            
341
6
fn collect_nms_files(path: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
342
6
    let p = Path::new(path);
343
6
    if !p.exists() {
344
        return Err(anyhow::anyhow!("path does not exist: {path}"));
345
6
    }
346
6
    if p.is_file() {
347
2
        return Ok(vec![p.to_path_buf()]);
348
4
    }
349
4
    let mut files: Vec<_> = fs::read_dir(p)?
350
4
        .filter_map(Result::ok)
351
9
        .map(|e| e.path())
352
9
        .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("nms"))
353
        .collect();
354
4
    files.sort();
355
4
    Ok(files)
356
6
}
357

            
358
5
fn test_summary_failed(summary: &str) -> bool {
359
5
    summary
360
5
        .split_once("passed, ")
361
5
        .and_then(|(_, rest)| rest.split_once(" failed"))
362
5
        .and_then(|(num, _)| num.trim().parse::<usize>().ok())
363
5
        .is_some_and(|n| n > 0)
364
5
}
365

            
366
fn rpc_repl(rpc: &mut rpc_eval::RpcEval) -> anyhow::Result<()> {
367
    let stdin = io::stdin();
368
    let mut stdout = io::stdout();
369
    let mut buffer = String::new();
370
    loop {
371
        if buffer.is_empty() {
372
            print!("\nrpc> ");
373
        } else {
374
            print!("   ");
375
        }
376
        stdout.flush()?;
377
        let mut line = String::new();
378
        if stdin.lock().read_line(&mut line)? == 0 {
379
            break;
380
        }
381
        if buffer.is_empty() && line.trim().is_empty() {
382
            continue;
383
        }
384
        buffer.push_str(&line);
385
        if Reader::is_incomplete(&buffer) {
386
            continue;
387
        }
388
        let input = buffer.trim();
389
        if !input.is_empty() {
390
            println!("{}", rpc.eval(input));
391
        }
392
        buffer.clear();
393
    }
394
    Ok(())
395
}
396

            
397
/// Splits whitespace-separated top-level s-expressions in source order.
398
/// Used by file/stdin rpc-mode runs so each form gets its own envelope.
399
/// Splits a source file into the top-level forms to dispatch (one rpc
400
/// envelope per form). A chunk is emitted only once it parses as a COMPLETE
401
/// program carrying at least one expression — comment-only / blank chunks
402
/// (which `Reader::parse` yields as zero-expression programs) are dropped
403
/// rather than wrapped into a bogus `(:id N :form ; comment)` envelope whose
404
/// `;` would comment out the closing paren.
405
5
fn split_forms(content: &str) -> Vec<String> {
406
5
    let mut forms = Vec::new();
407
5
    let mut current = String::new();
408
5
    for line in content.lines() {
409
16
        current.push_str(line);
410
16
        current.push('\n');
411
16
        let trimmed = current.trim();
412
16
        if trimmed.is_empty() || Reader::is_incomplete(trimmed) {
413
5
            continue;
414
11
        }
415
        // A complete chunk with no expression is pure comments/whitespace —
416
        // discard it; otherwise emit and reset.
417
11
        if Reader::parse(trimmed)
418
11
            .map(|p| !p.exprs.is_empty())
419
11
            .unwrap_or(true)
420
        {
421
6
            forms.push(trimmed.to_string());
422
5
        }
423
11
        current.clear();
424
    }
425
5
    let tail = current.trim();
426
5
    if !tail.is_empty()
427
        && Reader::parse(tail)
428
            .map(|p| !p.exprs.is_empty())
429
            .unwrap_or(true)
430
    {
431
        forms.push(tail.to_string());
432
5
    }
433
5
    forms
434
5
}
435

            
436
60
fn plain_repl(debug: bool, graphics: GraphicsPolicy) -> anyhow::Result<()> {
437
60
    let stdin = io::stdin();
438
60
    let mut stdout = io::stdout();
439
60
    let use_color = stdout.is_terminal();
440
60
    let mut interp = interpreter::Interpreter::new(debug)?;
441
60
    let mut buffer = String::new();
442

            
443
    loop {
444
234
        if buffer.is_empty() {
445
234
            print!("\n> ");
446
        } else {
447
            print!("  ");
448
        }
449
234
        stdout.flush()?;
450

            
451
234
        let mut line = String::new();
452
234
        if stdin.lock().read_line(&mut line)? == 0 {
453
60
            break;
454
174
        }
455

            
456
174
        if buffer.is_empty() && line.trim().is_empty() {
457
1
            continue;
458
173
        }
459

            
460
173
        buffer.push_str(&line);
461

            
462
173
        if Reader::is_incomplete(&buffer) {
463
            continue;
464
173
        }
465

            
466
173
        let input = buffer.trim();
467
173
        if input.is_empty() {
468
            buffer.clear();
469
            continue;
470
173
        }
471

            
472
173
        match interp.eval(input) {
473
            Ok(values) => {
474
173
                for value in values {
475
106
                    println!("{}", format_value(&value, use_color, graphics));
476
                }
477
            }
478
            Err(e) => eprint!("{}", e.render(use_color)),
479
        }
480
173
        buffer.clear();
481
    }
482

            
483
60
    Ok(())
484
60
}
485

            
486
3
fn compile_file(path: &str, output: Option<&str>) -> anyhow::Result<()> {
487
3
    let content = fs::read_to_string(path)?;
488
3
    match rpc::compile_script(&content) {
489
        Ok(wasm) => {
490
            let out_path =
491
2
                output.map_or_else(|| Path::new(path).with_extension("wasm"), PathBuf::from);
492
2
            fs::write(&out_path, &wasm)?;
493
2
            eprintln!("wrote {}", out_path.display());
494
2
            Ok(())
495
        }
496
        Err(e) => {
497
1
            eprintln!("{e}");
498
1
            std::process::exit(1);
499
        }
500
    }
501
2
}
502

            
503
fn load_wasm(path: &str, debug: bool, graphics: GraphicsPolicy) -> anyhow::Result<()> {
504
    let wasm = fs::read(path)?;
505
    let interp = interpreter::Interpreter::new(debug)?;
506
    let use_color = io::stderr().is_terminal();
507
    match interp.run_wasm(&wasm) {
508
        Ok(value) => {
509
            let use_color = io::stdout().is_terminal();
510
            if let Some(value) = value {
511
                println!("{}", format_value(&value, use_color, graphics));
512
            }
513
            Ok(())
514
        }
515
        Err(e) => {
516
            eprint!("{}", e.render(use_color));
517
            std::process::exit(1);
518
        }
519
    }
520
}
521

            
522
7
fn eval_string(
523
7
    input: &str,
524
7
    debug: bool,
525
7
    graphics: GraphicsPolicy,
526
7
    profiler: ProfilerStrategy,
527
7
) -> anyhow::Result<()> {
528
7
    let mut interp = interpreter::Interpreter::with_profiler(debug, profiler)?;
529
7
    print_results(&mut interp, input, graphics)
530
7
}
531

            
532
20
fn eval_file(
533
20
    path: &str,
534
20
    debug: bool,
535
20
    graphics: GraphicsPolicy,
536
20
    profiler: ProfilerStrategy,
537
20
) -> anyhow::Result<()> {
538
20
    let content = fs::read_to_string(path)?;
539
20
    let mut interp = interpreter::Interpreter::with_profiler(debug, profiler)?;
540
20
    print_results(&mut interp, &content, graphics)
541
20
}
542

            
543
fn eval_stdin(
544
    debug: bool,
545
    graphics: GraphicsPolicy,
546
    profiler: ProfilerStrategy,
547
) -> anyhow::Result<()> {
548
    let mut content = String::new();
549
    io::stdin().read_to_string(&mut content)?;
550
    let mut interp = interpreter::Interpreter::with_profiler(debug, profiler)?;
551
    print_results(&mut interp, &content, graphics)
552
}
553

            
554
27
fn print_results(
555
27
    interp: &mut interpreter::Interpreter,
556
27
    input: &str,
557
27
    graphics: GraphicsPolicy,
558
27
) -> anyhow::Result<()> {
559
27
    let use_color = io::stderr().is_terminal();
560
27
    match interp.eval(input) {
561
        Ok(values) => {
562
14
            let use_color = io::stdout().is_terminal();
563
14
            for value in values {
564
13
                println!("{}", format_value(&value, use_color, graphics));
565
            }
566
        }
567
        Err(e) => {
568
13
            eprint!("{}", e.render(use_color));
569
13
            std::process::exit(1);
570
        }
571
    }
572
14
    Ok(())
573
14
}
574

            
575
119
fn format_value(value: &Value, use_color: bool, graphics: GraphicsPolicy) -> String {
576
119
    match value {
577
        Value::Nil => {
578
6
            if use_color {
579
                "\x1b[90mnil\x1b[0m".to_string()
580
            } else {
581
6
                "nil".to_string()
582
            }
583
        }
584
        Value::T => {
585
            if use_color {
586
                "\x1b[32mt\x1b[0m".to_string()
587
            } else {
588
                "t".to_string()
589
            }
590
        }
591
        Value::Number(n) => {
592
21
            let text = n.to_string();
593
21
            if use_color {
594
                format!("\x1b[36m{text}\x1b[0m")
595
            } else {
596
21
                text
597
            }
598
        }
599
        Value::String(s) => {
600
5
            if use_color {
601
                format!("\x1b[33m{s}\x1b[0m")
602
            } else {
603
5
                s.clone()
604
            }
605
        }
606
        Value::Symbol(s) => {
607
44
            if use_color {
608
                format!("\x1b[35m{s}\x1b[0m")
609
            } else {
610
44
                s.clone()
611
            }
612
        }
613
        Value::Bytes(b) => {
614
            if graphics.inline
615
                && let Some(apc) =
616
                    nms::graphics::try_render_inline(b, |name| std::env::var(name).ok())
617
            {
618
                return apc;
619
            }
620
            let parts: Vec<String> = b.iter().map(u8::to_string).collect();
621
            let text = format!("#u8({})", parts.join(" "));
622
            if use_color {
623
                format!("\x1b[33m{text}\x1b[0m")
624
            } else {
625
                text
626
            }
627
        }
628
13
        Value::Pair(_) => scripting::nomiscript::format_value(value),
629
        Value::Vector(_) => "<vector>".to_string(),
630
13
        Value::Closure(_) | Value::Condition => scripting::nomiscript::format_value(value),
631
        Value::Struct { .. } => {
632
17
            let text = scripting::nomiscript::format_value(value);
633
17
            if use_color {
634
                format!("\x1b[94m{text}\x1b[0m")
635
            } else {
636
17
                text
637
            }
638
        }
639
        Value::Commodity {
640
            amount,
641
            commodity_id,
642
        } => {
643
            let amt = scripting::nomiscript::format_amount(*amount);
644
            let text = format!("(:commodity {amt} :id \"{commodity_id}\")");
645
            if use_color {
646
                format!("\x1b[36m{text}\x1b[0m")
647
            } else {
648
                text
649
            }
650
        }
651
    }
652
119
}
653

            
654
#[cfg(test)]
655
mod tests {
656
    use super::split_forms;
657

            
658
    #[test]
659
1
    fn split_forms_drops_comment_only_chunks() {
660
        // Regression: leading comment lines used to each become a bogus form,
661
        // wrapped as `(:id N :form ; comment)` whose `;` ate the closing paren.
662
1
        let src = "\
663
1
; a leading comment
664
1
; another comment
665
1
(defun f (x) x)
666
1
; trailing-style comment between forms
667
1
(f 1)
668
1
";
669
1
        assert_eq!(split_forms(src), vec!["(defun f (x) x)", "(f 1)"]);
670
1
    }
671

            
672
    #[test]
673
1
    fn split_forms_handles_multiline_forms() {
674
1
        let src = "(defun g (x)\n  (+ x\n     1))\n(g 2)\n";
675
1
        let forms = split_forms(src);
676
1
        assert_eq!(forms.len(), 2);
677
1
        assert!(forms[0].contains("defun g"));
678
1
        assert_eq!(forms[1], "(g 2)");
679
1
    }
680

            
681
    #[test]
682
1
    fn split_forms_all_comments_yields_nothing() {
683
1
        assert!(split_forms("; just a comment\n;; and another\n").is_empty());
684
1
    }
685

            
686
    #[test]
687
1
    fn split_forms_keeps_form_with_trailing_comment() {
688
        // A real form with a same-line trailing comment parses to a non-empty
689
        // program, so it is emitted (not dropped as a comment-only chunk).
690
1
        assert_eq!(split_forms("(f 1) ; note\n"), vec!["(f 1) ; note"]);
691
1
    }
692

            
693
    #[test]
694
1
    fn split_forms_tolerates_blank_and_comment_lines_inside_a_form() {
695
        // Blank + comment lines inside an incomplete multi-line form are reader
696
        // whitespace; the form stays one chunk and is emitted intact.
697
1
        let src = "(defun h (x)\n\n  ; midway comment\n  (+ x 1))\n";
698
1
        let forms = split_forms(src);
699
1
        assert_eq!(forms.len(), 1);
700
1
        assert!(forms[0].contains("defun h") && forms[0].contains("(+ x 1)"));
701
1
    }
702
}