lini 0.3.0

A small, human-readable language for plain-text diagrams that compiles to clean SVG
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Canonical source formatter (SPEC §14). Parses to the AST and re-emits a
//! normalized form: the three phases in order (stylesheet → instances → wires),
//! `key: value;` declarations in `{ }` blocks, `name::base` defines, 2-space
//! indent, space-separated value groups (comma between groups). Comments and
//! blank-line groupings are preserved; sibling nodes align their id/type
//! columns. Idempotent: `fmt(fmt(x)) == fmt(x)`.

use crate::ast::{Side, WireOp};
use crate::error::Error;
use crate::lexer;
use crate::span::Span;
use crate::syntax::ast::{
    Block, Child, Decl, Define, Endpoint, File, Node, Rule, SelPart, Selector, StyleItem, Value,
    Wire, WireBlock,
};
use crate::syntax::parser;

mod trivia;
use trivia::{Trivia, TriviaToken, scan_trivia};

const INDENT: &str = "  ";

/// A declarations-only block collapses onto one line (`.hot { stroke: red; }`)
/// when the whole line fits within this budget; past it, or once the block holds
/// a child node/wire, it breaks across lines. Prettier's print-width, give or take.
const MAX_LINE: usize = 80;

pub fn format(src: &str) -> Result<String, Error> {
    let tokens = lexer::lex(src)?;
    let file = parser::parse(&tokens)?;
    let trivia = scan_trivia(src);
    let mut out = String::new();
    Emitter {
        trivia: &trivia,
        cursor: 0,
        out: &mut out,
        align: true,
        terse: true,
    }
    .emit_file(&file, src.len());
    Ok(out)
}

/// Emit an AST with no source to draw trivia from — for a synthesized `File`
/// (the desugar pass), whose nodes carry no real spans. Same emitter, empty
/// trivia: clean output, comments dropped.
pub(crate) fn print_file(file: &File) -> String {
    let mut out = String::new();
    Emitter {
        trivia: &[],
        cursor: 0,
        out: &mut out,
        align: false,
        terse: false,
    }
    .emit_file(file, 0);
    out
}

struct Emitter<'a> {
    trivia: &'a [TriviaToken],
    cursor: usize,
    out: &'a mut String,
    /// Column-align sibling id/type columns. On for canonical `fmt`; off for
    /// `print_file` (synthesized ASTs, where mixing anonymous sugar children
    /// with named nodes would pad oddly).
    align: bool,
    /// Contract a text-only block to trailing labels (`api |box| "API"`). On for
    /// `fmt`; off for `print_file` (desugar), which expands sugar to the block.
    terse: bool,
}

impl Emitter<'_> {
    fn emit_file(&mut self, file: &File, src_len: usize) {
        let mut phases_emitted = 0;
        if !file.stylesheet.is_empty() {
            // Root config declarations group on one line like a block's, the same
            // CSS-shaped style (SPEC §20); rules, defines, and `--var`s each take
            // their own line.
            let items = &file.stylesheet;
            let mut i = 0;
            while i < items.len() {
                if matches!(items[i], StyleItem::RootDecl(_)) {
                    let start = i;
                    while i < items.len() && matches!(items[i], StyleItem::RootDecl(_)) {
                        i += 1;
                    }
                    let run: Vec<&Decl> = items[start..i]
                        .iter()
                        .map(|it| match it {
                            StyleItem::RootDecl(d) => d,
                            _ => unreachable!(),
                        })
                        .collect();
                    self.emit_grouped_decls(&run, 0);
                } else {
                    self.emit_trivia_before(style_item_span(&items[i]).start, 0);
                    self.emit_style_item(&items[i], 0);
                    self.cursor = style_item_span(&items[i]).end;
                    i += 1;
                }
            }
            phases_emitted += 1;
        }
        if !file.instances.is_empty() {
            self.section_break(phases_emitted);
            self.emit_children(&file.instances, 0);
            phases_emitted += 1;
        }
        if !file.wires.is_empty() {
            self.section_break(phases_emitted);
            for w in &file.wires {
                self.emit_trivia_before(w.span.start, 0);
                self.emit_wire(w, 0);
                self.out.push('\n');
                self.cursor = w.span.end;
            }
        }
        self.emit_trivia_before(src_len, 0);
        if self.out.is_empty() {
            return;
        }
        if !self.out.ends_with('\n') {
            self.out.push('\n');
        }
    }

    /// One blank line between two non-empty phases (only once any phase has been
    /// written), unless the running output already ends in one.
    fn section_break(&mut self, phases_emitted: usize) {
        if phases_emitted > 0 && !self.out.is_empty() && !self.out.ends_with("\n\n") {
            self.out.push('\n');
        }
    }

    // ───────── Stylesheet ─────────

    fn emit_style_item(&mut self, item: &StyleItem, depth: usize) {
        match item {
            StyleItem::RootDecl(d) => {
                self.indent(depth);
                self.emit_decl(d, false);
                self.out.push('\n');
            }
            StyleItem::Var(d) => {
                self.indent(depth);
                self.emit_decl(d, true);
                self.out.push('\n');
            }
            StyleItem::Rule(r) => self.emit_rule(r, depth),
            StyleItem::Define(d) => self.emit_define(d, depth),
        }
    }

    fn emit_rule(&mut self, rule: &Rule, depth: usize) {
        self.indent(depth);
        self.emit_selector(&rule.selector);
        self.emit_decl_block(&rule.decls, rule.span.end, depth);
        self.out.push('\n');
    }

    fn emit_define(&mut self, def: &Define, depth: usize) {
        self.indent(depth);
        self.out.push_str(&def.name);
        self.out.push_str("::");
        self.out.push_str(&def.base);
        self.emit_block(&def.body, def.span.end, depth);
        self.out.push('\n');
    }

    fn emit_selector(&mut self, sel: &Selector) {
        // The wire-defaults rule carries the reserved `wire` selector internally
        // but is written with the wire glyph.
        if let [SelPart::Type(t)] = sel.parts.as_slice()
            && t == "wire"
        {
            self.out.push_str("->");
            return;
        }
        for (i, part) in sel.parts.iter().enumerate() {
            if i > 0 {
                self.out.push(' ');
            }
            match part {
                SelPart::Type(t) => self.out.push_str(t),
                SelPart::Class(c) => {
                    self.out.push('.');
                    self.out.push_str(c);
                }
            }
        }
    }

    // ───────── Instances ─────────

    fn emit_children(&mut self, children: &[Child], depth: usize) {
        let widths = if self.align {
            align::child_widths(children, self.trivia)
        } else {
            vec![align::NodeWidths::default(); children.len()]
        };
        for (i, c) in children.iter().enumerate() {
            let span = child_span(c);
            self.emit_trivia_before(span.start, depth);
            match c {
                Child::Box(n) => self.emit_node(n, depth, widths[i]),
                Child::Text(t) => {
                    self.indent(depth);
                    self.emit_string(&t.text);
                }
            }
            self.out.push('\n');
            self.cursor = span.end;
        }
    }

    /// The column count if this block is a grid whose children are *all* bare
    /// text (a `|table|`) and no comment sits between the cells — then the cells
    /// align into columns (SPEC §8/§14). Any box cell or interleaved comment
    /// returns `None`, falling the body back to one child per line.
    fn table_cols(&self, block: &Block) -> Option<usize> {
        let cells = &block.children;
        if cells.is_empty() || !cells.iter().all(|c| matches!(c, Child::Text(_))) {
            return None;
        }
        let start = child_span(&cells[0]).start;
        let end = child_span(cells.last().unwrap()).end;
        if self.has_trivia_between(start, end) {
            return None;
        }
        count_columns(&block.decls)
    }

    /// Emit bare-text cells as aligned rows: each column padded to its widest
    /// cell, a single space between columns, `columns` cells per row.
    fn emit_aligned_cells(&mut self, cells: &[Child], cols: usize, depth: usize) {
        let texts: Vec<String> = cells
            .iter()
            .map(|c| match c {
                Child::Text(t) => quoted(&t.text),
                Child::Box(_) => String::new(), // table_cols guarantees all-text
            })
            .collect();
        let mut widths = vec![0usize; cols];
        for (i, s) in texts.iter().enumerate() {
            widths[i % cols] = widths[i % cols].max(s.len());
        }
        for (i, s) in texts.iter().enumerate() {
            let col = i % cols;
            if col == 0 {
                self.indent(depth);
            } else {
                self.out.push(' ');
            }
            self.out.push_str(s);
            if col == cols - 1 || i == texts.len() - 1 {
                self.out.push('\n');
            } else {
                pad(self.out, widths[col] - s.len());
            }
        }
        self.cursor = child_span(cells.last().unwrap()).end;
    }

    fn emit_node(&mut self, node: &Node, depth: usize, w: align::NodeWidths) {
        self.indent(depth);
        // Head tokens — `id |type| "labels" .classes` — each separated from the
        // last by one space, with the alignment widths padding the id/type
        // columns out to the group's max. `wrote` tracks whether any token (or a
        // reserved-but-empty column) precedes, so the separator never leads.
        let mut wrote = false;
        if let Some(id) = &node.id {
            self.out.push_str(id);
            pad(self.out, w.id.saturating_sub(id.len()));
            wrote = true;
        } else if w.id > 0 {
            pad(self.out, w.id);
            wrote = true;
        }
        if let Some(ty) = &node.ty {
            self.space_if(wrote);
            let t = format!("|{}|", ty);
            self.out.push_str(&t);
            pad(self.out, w.ty.saturating_sub(t.len()));
            wrote = true;
        } else if w.ty > 0 {
            self.space_if(wrote);
            pad(self.out, w.ty);
            wrote = true;
        }
        for class in &node.classes {
            self.space_if(wrote);
            self.out.push('.');
            self.out.push_str(class);
            wrote = true;
        }
        if let Some(block) = &node.block
            && !self.try_trailing_labels(
                &block.children,
                block.decls.is_empty() && block.wires.is_empty(),
                node.span.end,
            )
        {
            self.emit_block(block, node.span.end, depth);
        }
    }

    /// In terse mode, a block that is only text (≥1 child, no decls / boxes /
    /// wires / comment) is written as trailing labels — `… "a" "b"`, no braces.
    /// Returns whether it did so (and advanced the cursor).
    fn try_trailing_labels(&mut self, children: &[Child], no_config: bool, end: usize) -> bool {
        let text_only =
            !children.is_empty() && children.iter().all(|c| matches!(c, Child::Text(_)));
        if !self.terse || !no_config || !text_only || self.has_trivia_between(self.cursor, end) {
            return false;
        }
        for c in children {
            if let Child::Text(t) = c {
                self.out.push(' ');
                self.emit_string(&t.text);
            }
        }
        self.cursor = end;
        true
    }

    fn space_if(&mut self, cond: bool) {
        if cond {
            self.out.push(' ');
        }
    }

    /// Emit a run of declarations grouped onto as few lines as the source's
    /// trivia allows (SPEC §20): consecutive decls with nothing between them
    /// share one line (`cell: 1 2; layout: column; gap: 16;`), and a comment or
    /// blank line starts a fresh one. They never share the opening brace's line.
    fn emit_grouped_decls(&mut self, decls: &[&Decl], depth: usize) {
        let mut mid_line = false;
        for d in decls {
            if mid_line && self.has_trivia_between(self.cursor, d.span.start) {
                self.out.push('\n');
                mid_line = false;
            }
            self.emit_trivia_before(d.span.start, depth);
            if mid_line {
                self.out.push(' ');
            } else {
                self.indent(depth);
            }
            self.emit_decl(d, false);
            self.cursor = d.span.end;
            mid_line = true;
        }
        if mid_line {
            self.out.push('\n');
        }
    }

    fn has_trivia_between(&self, start: usize, end: usize) -> bool {
        self.trivia.iter().any(|t| t.pos >= start && t.pos < end)
    }

    /// Try to collapse a body of declarations + bare-text labels onto the current
    /// line — ` { cell: 1 1; "Cat" }`. Restores and returns `false` if there's a
    /// comment/blank inside or the finished line exceeds [`MAX_LINE`], so the
    /// caller falls through to the multi-line form. A box child or internal wire
    /// is the caller's cue never to try.
    fn try_inline(&mut self, decls: &[Decl], texts: &[&str], end: usize) -> bool {
        if self.has_trivia_between(self.cursor, end) {
            return false;
        }
        let line_start = self.out.rfind('\n').map_or(0, |i| i + 1);
        let saved = self.out.len();
        self.out.push_str(" { ");
        let mut first = true;
        for d in decls {
            if !first {
                self.out.push(' ');
            }
            self.emit_decl(d, false);
            first = false;
        }
        for t in texts {
            if !first {
                self.out.push(' ');
            }
            self.emit_string(t);
            first = false;
        }
        self.out.push_str(" }");
        if self.out.len() - line_start <= MAX_LINE {
            self.cursor = end;
            true
        } else {
            self.out.truncate(saved);
            false
        }
    }

    fn emit_block(&mut self, block: &Block, end: usize, depth: usize) {
        let empty = block.decls.is_empty() && block.children.is_empty() && block.wires.is_empty();
        if empty && !self.has_comment_in(self.cursor, end) {
            self.out.push_str(" {}");
            self.cursor = end;
            return;
        }
        // A box child or internal wire forces the multi-line form, as does a
        // multi-row table (it always breaks into aligned rows); otherwise a body
        // of only declarations and bare text may collapse onto one line.
        let has_box = block.children.iter().any(|c| matches!(c, Child::Box(_)));
        let table = self.table_cols(block);
        let multi_row = matches!(table, Some(cols) if block.children.len() > cols);
        if !has_box && block.wires.is_empty() && !multi_row {
            let texts = text_strs(&block.children);
            if self.try_inline(&block.decls, &texts, end) {
                return;
            }
        }
        self.out.push_str(" {\n");
        let decls: Vec<&Decl> = block.decls.iter().collect();
        self.emit_grouped_decls(&decls, depth + 1);
        // A grid of bare-text cells (a `|table|`) aligns into columns; any other
        // cell kind, or a comment between cells, falls back to one-per-line.
        match table {
            Some(cols) => self.emit_aligned_cells(&block.children, cols, depth + 1),
            None => self.emit_children(&block.children, depth + 1),
        }
        for wire in &block.wires {
            self.emit_trivia_before(wire.span.start, depth + 1);
            self.emit_wire(wire, depth + 1);
            self.out.push('\n');
            self.cursor = wire.span.end;
        }
        self.emit_trivia_before(end, depth + 1);
        self.indent(depth);
        self.out.push('}');
    }

    /// A rule body: only declarations, same braces.
    fn emit_decl_block(&mut self, decls: &[Decl], end: usize, depth: usize) {
        if decls.is_empty() && !self.has_comment_in(self.cursor, end) {
            self.out.push_str(" {}");
            self.cursor = end;
            return;
        }
        if self.try_inline(decls, &[], end) {
            return;
        }
        self.out.push_str(" {\n");
        let refs: Vec<&Decl> = decls.iter().collect();
        self.emit_grouped_decls(&refs, depth + 1);
        self.emit_trivia_before(end, depth + 1);
        self.indent(depth);
        self.out.push('}');
    }

    // ───────── Wires ─────────

    fn emit_wire(&mut self, w: &Wire, depth: usize) {
        self.indent(depth);
        for (i, group) in w.chain.iter().enumerate() {
            if i > 0 {
                self.out.push(' ');
                self.out.push_str(&wire_op_str(w.op));
                self.out.push(' ');
            }
            for (j, ep) in group.endpoints.iter().enumerate() {
                if j > 0 {
                    self.out.push_str(" & ");
                }
                self.emit_endpoint(ep);
            }
        }
        for class in &w.classes {
            self.out.push_str(" .");
            self.out.push_str(class);
        }
        if let Some(block) = &w.block
            && !self.try_trailing_labels(&block.labels, block.decls.is_empty(), w.span.end)
        {
            self.emit_wire_block(block, w.span.end, depth);
        }
    }

    fn emit_endpoint(&mut self, ep: &Endpoint) {
        self.out.push_str(&ep.path.join("."));
        if let Some(side) = ep.side {
            self.out.push('.');
            self.out.push_str(side_str(side));
        }
    }

    fn emit_wire_block(&mut self, block: &WireBlock, end: usize, depth: usize) {
        let empty = block.decls.is_empty() && block.labels.is_empty();
        if empty && !self.has_comment_in(self.cursor, end) {
            self.out.push_str(" {}");
            self.cursor = end;
            return;
        }
        let has_box = block.labels.iter().any(|c| matches!(c, Child::Box(_)));
        if !has_box {
            let texts = text_strs(&block.labels);
            if self.try_inline(&block.decls, &texts, end) {
                return;
            }
        }
        self.out.push_str(" {\n");
        let decls: Vec<&Decl> = block.decls.iter().collect();
        self.emit_grouped_decls(&decls, depth + 1);
        self.emit_children(&block.labels, depth + 1);
        self.emit_trivia_before(end, depth + 1);
        self.indent(depth);
        self.out.push('}');
    }

    // ───────── Declarations & values ─────────

    fn emit_decl(&mut self, decl: &Decl, is_var: bool) {
        if is_var {
            self.out.push_str("--");
        }
        self.out.push_str(&decl.name);
        self.out.push_str(": ");
        for (i, group) in decl.groups.iter().enumerate() {
            if i > 0 {
                self.out.push_str(", ");
            }
            for (j, v) in group.iter().enumerate() {
                if j > 0 {
                    self.out.push(' ');
                }
                self.emit_value(v);
            }
        }
        self.out.push(';');
    }

    fn emit_value(&mut self, v: &Value) {
        match v {
            Value::Number(n) => self.out.push_str(&format_number(*n)),
            Value::String(s) => self.emit_string(s),
            Value::Hex(h) => {
                self.out.push('#');
                self.out.push_str(h);
            }
            Value::Ident(s) => self.out.push_str(s),
            Value::Var(name) => {
                self.out.push_str("--");
                self.out.push_str(name);
            }
            Value::Call(c) => {
                self.out.push_str(&c.name);
                self.out.push('(');
                for (i, arg) in c.args.iter().enumerate() {
                    if i > 0 {
                        self.out.push_str(", ");
                    }
                    self.emit_value(arg);
                }
                self.out.push(')');
            }
        }
    }

    fn emit_string(&mut self, s: &str) {
        self.out.push_str(&quoted(s));
    }

    // ───────── Trivia ─────────

    fn indent(&mut self, depth: usize) {
        for _ in 0..depth {
            self.out.push_str(INDENT);
        }
    }

    fn has_comment_in(&self, start: usize, end: usize) -> bool {
        self.trivia
            .iter()
            .any(|t| matches!(t.kind, Trivia::Comment(_)) && t.pos >= start && t.pos < end)
    }

    fn emit_trivia_before(&mut self, until: usize, depth: usize) {
        let mut last_was_blank = false;
        for t in self.trivia {
            if t.pos < self.cursor {
                continue;
            }
            if t.pos >= until {
                break;
            }
            match &t.kind {
                Trivia::Comment(text) => {
                    self.indent(depth);
                    self.out.push_str(text);
                    self.out.push('\n');
                    last_was_blank = false;
                }
                Trivia::BlankLine => {
                    if !last_was_blank && !self.out.is_empty() && !self.out.ends_with("\n\n") {
                        self.out.push('\n');
                        last_was_blank = true;
                    }
                }
            }
        }
        self.cursor = until;
    }
}

// ─────────────────────────── Spans & token helpers ───────────────────────────

fn style_item_span(item: &StyleItem) -> Span {
    match item {
        StyleItem::RootDecl(d) | StyleItem::Var(d) => d.span,
        StyleItem::Rule(r) => r.span,
        StyleItem::Define(d) => d.span,
    }
}

fn wire_op_str(op: WireOp) -> String {
    format!(
        "{}{}{}",
        op.start.start_str(),
        op.line.as_str(),
        op.end.end_str()
    )
}

fn side_str(s: Side) -> &'static str {
    match s {
        Side::Top => "top",
        Side::Bottom => "bottom",
        Side::Left => "left",
        Side::Right => "right",
    }
}

fn pad(out: &mut String, n: usize) {
    for _ in 0..n {
        out.push(' ');
    }
}

fn child_span(c: &Child) -> Span {
    match c {
        Child::Box(n) => n.span,
        Child::Text(t) => t.span,
    }
}

/// A string as a Lini double-quoted literal, with the four escapes.
fn quoted(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

/// The grid column count from a `columns:` declaration — a track list where
/// `repeat(N)` counts as N and every other entry as one. `None` if absent.
fn count_columns(decls: &[Decl]) -> Option<usize> {
    let d = decls.iter().find(|d| d.name == "columns")?;
    let n: usize = d
        .groups
        .iter()
        .flatten()
        .map(|v| match v {
            Value::Call(c) if c.name == "repeat" => c
                .args
                .first()
                .and_then(|a| match a {
                    Value::Number(x) if *x >= 1.0 => Some(*x as usize),
                    _ => None,
                })
                .unwrap_or(1),
            _ => 1,
        })
        .sum();
    (n > 0).then_some(n)
}

/// The bare-text labels among a body's children, in order — used to test whether
/// the body fits inline (boxes are checked separately by the caller).
fn text_strs(children: &[Child]) -> Vec<&str> {
    children
        .iter()
        .filter_map(|c| match c {
            Child::Text(t) => Some(t.text.as_str()),
            Child::Box(_) => None,
        })
        .collect()
}

fn format_number(n: f64) -> String {
    if n.fract() == 0.0 && n.is_finite() && n.abs() < 1e15 {
        format!("{}", n as i64)
    } else {
        format!("{}", n)
    }
}

mod align;

#[cfg(test)]
mod tests;