marwood 1.0.0

Scheme R7RS Virtual Machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Indent-aware Lisp pretty-printer.
//!
//! Renders a [`Cell`] within a target column width. If the value fits
//! on a single line within `width` it's emitted verbatim via the
//! existing [`Display`](crate::cell::Cell) impl. Otherwise the printer
//! breaks the form across lines using a small special-form table so
//! `define` / `let` / `cond` etc. indent the way a Lisp reader expects.
//!
//! Atoms are unbreakable: a single symbol or string longer than
//! `width` overflows rather than being truncated.

use crate::cell::Cell;

/// Render `cell` as a string targeting `width` columns. Lines longer
/// than `width` are only produced when no break is possible (atoms
/// that can't fit, list heads forced onto an already-indented line).
pub fn format(cell: &Cell, width: usize) -> String {
    let mut p = Printer {
        width,
        out: String::new(),
        col: 0,
    };
    p.print(cell);
    p.out
}

struct Printer {
    width: usize,
    out: String,
    col: usize,
}

impl Printer {
    fn raw(&mut self, s: &str) {
        for ch in s.chars() {
            if ch == '\n' {
                self.col = 0;
            } else {
                self.col += 1;
            }
        }
        self.out.push_str(s);
    }

    fn newline(&mut self, indent: usize) {
        self.out.push('\n');
        for _ in 0..indent {
            self.out.push(' ');
        }
        self.col = indent;
    }

    fn fits_single_line(&self, single: &str) -> bool {
        // Single-line renderings never contain '\n' for any Cell variant,
        // so character count == column advance.
        self.col + single.chars().count() <= self.width
    }

    fn print(&mut self, cell: &Cell) {
        let single = format!("{:#}", cell);
        if !forces_multiline(cell) && self.fits_single_line(&single) {
            self.raw(&single);
            return;
        }
        match cell {
            Cell::Pair(_, _) => self.print_pair(cell),
            Cell::Vector(items) => self.print_vector(items),
            Cell::DatumDef(label, value) => {
                self.raw(&format!("#{}=", label));
                self.print(value);
            }
            _ => self.raw(&single),
        }
    }

    fn print_pair(&mut self, cell: &Cell) {
        // Sugar quote-like forms back to their reader prefix.
        if let Some(prefix) = quote_prefix(cell) {
            self.raw(prefix);
            self.print(cell.cadr().unwrap());
            return;
        }
        if cell.is_list() {
            let elts: Vec<&Cell> = cell.iter().collect();
            if elts.is_empty() {
                self.raw("()");
                return;
            }
            match lookup_rule(elts[0]) {
                Rule::Body(n) => self.print_body_form(&elts, n),
                Rule::AlignArgs => self.print_align_args(&elts),
            }
        } else if cell.is_improper_list() {
            self.print_improper(cell);
        } else {
            // A bare dotted pair (a . b). Cell::Display already handles
            // this on a single line; no useful break point.
            self.raw(&format!("{:#}", cell));
        }
    }

    /// `(head arg1 .. arg_special body...)` — the head plus
    /// `special_count` arguments stay on the first line, remaining
    /// elements indent two columns from the open paren.
    fn print_body_form(&mut self, elts: &[&Cell], special_count: usize) {
        let open_col = self.col;
        self.raw("(");
        let body_indent = open_col + 2;
        self.print(elts[0]);
        let limit = (1 + special_count).min(elts.len());
        for elt in &elts[1..limit] {
            self.raw(" ");
            self.print(elt);
        }
        for elt in &elts[limit..] {
            self.newline(body_indent);
            self.print(elt);
        }
        self.raw(")");
    }

    /// `(head arg1 arg2 ...)` — when head is a symbol (a procedure
    /// call) the first arg stays on the open-paren line and subsequent
    /// args align under its column. When head isn't a symbol the form
    /// is treated as data: every element gets its own line aligned
    /// under the first element.
    fn print_align_args(&mut self, elts: &[&Cell]) {
        self.raw("(");
        let first_col = self.col;
        self.print(elts[0]);
        if elts.len() == 1 {
            self.raw(")");
            return;
        }
        if elts[0].as_symbol().is_some() {
            self.raw(" ");
            let arg_col = self.col;
            self.print(elts[1]);
            for elt in &elts[2..] {
                self.newline(arg_col);
                self.print(elt);
            }
        } else {
            for elt in &elts[1..] {
                self.newline(first_col);
                self.print(elt);
            }
        }
        self.raw(")");
    }

    fn print_improper(&mut self, cell: &Cell) {
        let mut elts: Vec<&Cell> = Vec::new();
        let mut tail: Option<&Cell> = None;
        let mut current = cell;
        loop {
            match current {
                Cell::Pair(car, cdr) => {
                    elts.push(car.as_ref());
                    current = cdr.as_ref();
                }
                Cell::Nil => break,
                other => {
                    tail = Some(other);
                    break;
                }
            }
        }
        self.raw("(");
        if elts.is_empty() {
            if let Some(t) = tail {
                self.print(t);
            }
            self.raw(")");
            return;
        }
        self.print(elts[0]);
        if elts.len() == 1 && tail.is_none() {
            self.raw(")");
            return;
        }
        self.raw(" ");
        let align_col = self.col;
        if elts.len() > 1 {
            self.print(elts[1]);
            for elt in &elts[2..] {
                self.newline(align_col);
                self.print(elt);
            }
        }
        if let Some(t) = tail {
            self.newline(align_col);
            self.raw(". ");
            self.print(t);
        }
        self.raw(")");
    }

    fn print_vector(&mut self, items: &[Cell]) {
        self.raw("#(");
        if items.is_empty() {
            self.raw(")");
            return;
        }
        let elt_col = self.col;
        self.print(&items[0]);
        for item in &items[1..] {
            self.newline(elt_col);
            self.print(item);
        }
        self.raw(")");
    }
}

fn quote_prefix(cell: &Cell) -> Option<&'static str> {
    let car = cell.car()?;
    let cdr = cell.cdr()?;
    if !cdr.is_pair() {
        return None;
    }
    if !cdr.cdr()?.is_nil() {
        return None;
    }
    if car.is_quote() {
        Some("'")
    } else if car.is_quasiquote() {
        Some("`")
    } else if car.is_unquote() {
        Some(",")
    } else {
        None
    }
}

enum Rule {
    /// `Body(n)`: head + the next `n` elements stay on the open-paren
    /// line; the rest indent +2 from the open paren.
    Body(usize),
    /// Head + first arg on open-paren line; remaining args align
    /// under the first arg's column.
    AlignArgs,
}

/// Forms that should always render across multiple lines, even when
/// they would fit on a single line. Function definitions and the
/// dispatch forms (cond / case / syntax-rules) are the canonical
/// cases: separating signature from body, or one clause per line,
/// makes file scans and diffs cleaner and visually distinguishes
/// these forms from generic procedure calls.
fn forces_multiline(cell: &Cell) -> bool {
    if !cell.is_list() {
        return false;
    }
    let elts: Vec<&Cell> = cell.iter().collect();
    if elts.is_empty() {
        return false;
    }
    let head = elts[0].as_symbol();

    // Function-shape defines: (define (NAME ...) ...) and
    // (define NAME (lambda ...)).
    if head == Some("define") && elts.len() >= 3 {
        if elts[1].is_pair() {
            return true;
        }
        if elts.len() == 3
            && let Some(body_head) = elts[2].car()
                && body_head.is_lambda() {
                    return true;
                }
    }

    // (define-syntax NAME TRANSFORMER) — same convention as define.
    if head == Some("define-syntax") && elts.len() >= 3 {
        return true;
    }

    // Clause-table forms: each clause / pattern on its own line.
    if matches!(head, Some("cond") | Some("case") | Some("syntax-rules"))
        && elts.len() >= 2
    {
        return true;
    }

    // Multi-section forms that read poorly on a single line.
    if matches!(head, Some("do") | Some("let-syntax") | Some("letrec-syntax"))
        && elts.len() >= 3
    {
        return true;
    }

    false
}

fn lookup_rule(head: &Cell) -> Rule {
    match head.as_symbol() {
        Some(s) => match s {
            // `Body(1)` — first non-head element is the "special" form
            // (binding list, parameter list, condition, etc.)
            "define" | "define-syntax" | "let" | "let*" | "letrec" | "letrec*"
            | "let-values" | "let*-values" | "lambda" | "if" | "do" => Rule::Body(1),
            // `Body(0)` — every body element indents under the head.
            "begin" | "when" | "unless" | "cond" | "case" | "and" | "or"
            | "syntax-rules" => Rule::Body(0),
            _ => Rule::AlignArgs,
        },
        None => Rule::AlignArgs,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse;

    fn p(s: &str) -> Cell {
        parse::parse_text(s).expect("parse failed").0
    }

    #[test]
    fn atom_fits_on_one_line() {
        assert_eq!(format(&p("42"), 80), "42");
        assert_eq!(format(&p("'foo"), 80), "'foo");
        assert_eq!(format(&p("#t"), 80), "#t");
    }

    #[test]
    fn atom_overflows_when_longer_than_width() {
        // Symbols, strings, etc. are unbreakable; they overflow rather
        // than get truncated or wrapped.
        let long_sym = "abcdefghijklmnop";
        assert_eq!(format(&p(long_sym), 8), long_sym);
    }

    #[test]
    fn short_list_stays_on_one_line() {
        assert_eq!(format(&p("(+ 1 2)"), 80), "(+ 1 2)");
        assert_eq!(format(&p("(define x 1)"), 80), "(define x 1)");
    }

    #[test]
    fn list_breaks_when_overflowing() {
        let out = format(&p("(foo a b c d)"), 6);
        assert_eq!(out, "(foo a\n     b\n     c\n     d)");
    }

    #[test]
    fn define_form_indents_body_plus_two() {
        let out = format(&p("(define (f x) (+ x 1) (* x 2))"), 20);
        assert_eq!(out, "(define (f x)\n  (+ x 1)\n  (* x 2))");
    }

    #[test]
    fn lambda_form_indents_body_plus_two() {
        let out = format(&p("(lambda (x y) (+ x y) (- x y))"), 20);
        assert_eq!(out, "(lambda (x y)\n  (+ x y)\n  (- x y))");
    }

    #[test]
    fn let_form_indents_body_plus_two() {
        let out = format(&p("(let ((a 1) (b 2)) (+ a b))"), 18);
        assert_eq!(out, "(let ((a 1) (b 2))\n  (+ a b))");
    }

    #[test]
    fn let_form_breaks_bindings_when_too_wide() {
        let out = format(&p("(let ((aaaaa 1) (bbbbb 2)) body)"), 16);
        assert!(
            out.starts_with("(let ((aaaaa 1)\n"),
            "expected bindings to break, got:\n{}",
            out
        );
        assert!(
            out.contains("\n  body)"),
            "expected body indented +2, got:\n{}",
            out
        );
    }

    #[test]
    fn if_form_indents_branches() {
        let out = format(&p("(if (> x 0) 'positive 'non-positive)"), 16);
        assert_eq!(out, "(if (> x 0)\n  'positive\n  'non-positive)");
    }

    #[test]
    fn cond_clauses_each_on_own_line() {
        // cond is Body(0): every element after the head indents +2.
        let out = format(
            &p("(cond ((= x 1) 'one) ((= x 2) 'two) (else 'other))"),
            24,
        );
        assert_eq!(
            out,
            "(cond\n  ((= x 1) 'one)\n  ((= x 2) 'two)\n  (else 'other))"
        );
    }

    #[test]
    fn begin_body_indents_two() {
        let out = format(&p("(begin (display \"hi\") (newline) 42)"), 16);
        assert_eq!(out, "(begin\n  (display \"hi\")\n  (newline)\n  42)");
    }

    #[test]
    fn quoted_data_keeps_sugar() {
        // 'X stays as 'X, not (quote X).
        assert_eq!(format(&p("'(1 2 3)"), 80), "'(1 2 3)");
        let out = format(&p("'(aaaa bbbb cccc dddd)"), 12);
        assert!(out.starts_with("'("), "expected quote sugar: {}", out);
    }

    #[test]
    fn nested_breaks_propagate() {
        let out = format(
            &p("(define (greet name) (display \"hello, \") (display name) (newline))"),
            30,
        );
        assert_eq!(
            out,
            "(define (greet name)\n  (display \"hello, \")\n  (display name)\n  (newline))"
        );
    }

    #[test]
    fn empty_list_renders_as_paren_pair() {
        assert_eq!(format(&Cell::Nil, 80), "()");
        assert_eq!(format(&p("'()"), 80), "'()");
    }

    #[test]
    fn dotted_pair_single_line() {
        assert_eq!(format(&p("(1 . 2)"), 80), "(1 . 2)");
    }

    #[test]
    fn improper_list_breaks_with_dotted_tail() {
        let out = format(&p("(aaa bbb ccc . ddd)"), 8);
        assert_eq!(out, "(aaa bbb\n     ccc\n     . ddd)");
    }

    #[test]
    fn vector_breaks_into_aligned_elements() {
        let v = Cell::Vector(vec![
            Cell::Symbol("aaaa".into()),
            Cell::Symbol("bbbb".into()),
            Cell::Symbol("cccc".into()),
        ]);
        let out = format(&v, 8);
        assert_eq!(out, "#(aaaa\n  bbbb\n  cccc)");
    }

    #[test]
    fn empty_vector_single_line() {
        assert_eq!(format(&Cell::Vector(vec![]), 80), "#()");
    }

    #[test]
    fn nested_let_in_define() {
        // At width 22 the inner let bindings still fit on one line.
        let out = format(&p("(define (sum a b) (let ((x a) (y b)) (+ x y)))"), 22);
        assert_eq!(out, "(define (sum a b)\n  (let ((x a) (y b))\n    (+ x y)))");
    }

    #[test]
    fn nested_let_breaks_bindings_when_indent_pushes_overflow() {
        // At width 18 the body-indented let bindings don't fit, so
        // the bindings list itself breaks.
        let out = format(&p("(define (sum a b) (let ((x a) (y b)) (+ x y)))"), 18);
        assert_eq!(
            out,
            "(define (sum a b)\n  (let ((x a)\n        (y b))\n    (+ x y)))"
        );
    }

    #[test]
    fn function_call_aligns_args_under_first() {
        let out = format(&p("(very-long-name aaa bbb ccc)"), 22);
        assert_eq!(out, "(very-long-name aaa\n                bbb\n                ccc)");
    }

    #[test]
    fn cycles_render_via_datum_labels() {
        let out = format(&p("#0=(1 2 . #0#)"), 80);
        assert!(out.contains("#0=") && out.contains("#0#"), "got: {}", out);
    }

    #[test]
    fn long_atom_inside_breaking_form_overflows_locally() {
        // The `define` rule still breaks the body; the long atom stays
        // on its own line and overflows width.
        let long = "verylongnamethatdoesntfit";
        let src = format!("(define x {})", long);
        let out = format(&p(&src), 12);
        assert!(out.contains("\n  verylongnamethatdoesntfit"), "got: {}", out);
    }

    #[test]
    fn function_form_define_always_breaks_body() {
        // Even when (define (square x) (* x x)) would fit on one line,
        // function definitions break body to its own line.
        let out = format(&p("(define (square x) (* x x))"), 80);
        assert_eq!(out, "(define (square x)\n  (* x x))");
    }

    #[test]
    fn lambda_aliasing_define_always_breaks_body() {
        // (define name (lambda ...)) is the long-hand of the function
        // form; force the body onto its own line. The lambda itself
        // still follows the normal fit-or-break rule, so a trivial
        // body like `x` stays inline with the lambda head.
        let out = format(&p("(define identity (lambda (x) x))"), 80);
        assert_eq!(out, "(define identity\n  (lambda (x) x))");
    }

    #[test]
    fn lambda_aliasing_define_with_long_body_breaks_lambda_too() {
        // At a width where the lambda body itself doesn't fit, the
        // lambda follows its own (Body(1)) rule and breaks.
        let out = format(&p("(define greet (lambda (name) (display \"hi \") (display name)))"), 30);
        assert_eq!(
            out,
            "(define greet\n  (lambda (name)\n    (display \"hi \")\n    (display name)))"
        );
    }

    #[test]
    fn cond_always_breaks_clauses_even_when_fitting() {
        let out = format(&p("(cond ((null? lst) 0) (else 1))"), 80);
        assert_eq!(out, "(cond\n  ((null? lst) 0)\n  (else 1))");
    }

    #[test]
    fn case_always_breaks_clauses() {
        let out = format(&p("(case x ((1 2) 'small) (else 'big))"), 80);
        assert_eq!(
            out,
            "(case\n  x\n  ((1 2) 'small)\n  (else 'big))"
        );
    }

    #[test]
    fn syntax_rules_always_breaks() {
        let out = format(&p("(syntax-rules () ((_ x) x))"), 80);
        // (syntax-rules) is Body(0): every element after the head goes
        // on its own line indented +2.
        assert_eq!(out, "(syntax-rules\n  ()\n  ((_ x) x))");
    }

    #[test]
    fn empty_cond_still_renders_compactly() {
        // (cond) with no clauses has nothing to break.
        assert_eq!(format(&p("(cond)"), 80), "(cond)");
    }

    #[test]
    fn do_form_always_breaks() {
        let out = format(&p("(do ((i 0 (+ i 1))) ((= i 10)) (display i))"), 80);
        assert_eq!(
            out,
            "(do ((i 0 (+ i 1)))\n  ((= i 10))\n  (display i))"
        );
    }

    #[test]
    fn define_syntax_always_breaks() {
        let out = format(
            &p("(define-syntax swap! (syntax-rules () ((_ a b) (let ((t a)) (set! a b) (set! b t)))))"),
            80,
        );
        assert!(out.starts_with("(define-syntax swap!\n"), "got:\n{}", out);
        assert!(out.contains("(syntax-rules\n"), "got:\n{}", out);
    }

    #[test]
    fn let_syntax_always_breaks() {
        let out = format(&p("(let-syntax ((m (syntax-rules () ((_) 1)))) (m))"), 80);
        assert!(out.starts_with("(let-syntax"), "got:\n{}", out);
        assert!(out.contains("\n"), "expected break:\n{}", out);
    }

    #[test]
    fn value_define_stays_single_line_when_it_fits() {
        // (define NAME EXPR) where EXPR isn't a lambda follows the
        // normal fit-or-break rule.
        assert_eq!(format(&p("(define x 42)"), 80), "(define x 42)");
        assert_eq!(format(&p("(define name \"x\")"), 80), "(define name \"x\")");
        assert_eq!(format(&p("(define ans (+ 1 2))"), 80), "(define ans (+ 1 2))");
    }

    #[test]
    fn formatted_output_round_trips_through_parser() {
        // Whatever shape the printer produces, the result must lex/parse
        // back to the same Cell.
        let original = p("(define (f x) (let ((a 1) (b 2)) (+ a b x)))");
        let formatted = format(&original, 12);
        let reparsed = p(&formatted);
        assert_eq!(reparsed, original);
    }
}