arity-formatter 0.7.1

Deterministic, rule-based formatter for the R language
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! The layout engine: walks an [`Ir`] tree and renders it to a string, deciding
//! for each [`Ir::Group`] whether it fits flat on the current line or must break.

use super::ir::{Ir, LineSuffixKind};
use super::style::FormatStyle;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    Flat,
    Break,
}

pub(crate) struct Printer {
    line_width: usize,
    indent_unit: usize,
}

/// Accumulates output while deferring indentation until visible content is
/// written, so blank lines never carry trailing whitespace.
struct Writer {
    out: String,
    col: usize,
    pending_indent: usize,
    needs_indent: bool,
    line: usize,
    line_indent: usize,
    suffixes: Vec<LineSuffixMark>,
}

/// The rendered position of a structured trailing comment. Keeping this
/// metadata beside the output lets alignment operate on comments identified by
/// the CST rather than rediscovering `#` characters in rendered strings.
struct LineSuffixMark {
    line: usize,
    indent: usize,
    separator_start: usize,
    separator_end: usize,
    code_col: usize,
    comment_width: usize,
    kind: LineSuffixKind,
}

impl Writer {
    fn new() -> Self {
        Self {
            out: String::new(),
            col: 0,
            pending_indent: 0,
            needs_indent: false,
            line: 0,
            line_indent: 0,
            suffixes: Vec::new(),
        }
    }

    fn flush_indent(&mut self) {
        if self.needs_indent {
            for _ in 0..self.pending_indent {
                self.out.push(' ');
            }
            self.col += self.pending_indent;
            self.needs_indent = false;
        }
    }

    /// The column the next visible character will land on. Indentation is
    /// deferred until something is actually written (so blank lines carry no
    /// trailing whitespace), which leaves `col` at 0 between a `newline` and
    /// the next `write_text`. Every break decision must measure against the
    /// column the content will *really* start at, not that transient 0 —
    /// otherwise a group or conditional-group that begins a line is measured
    /// as if it sat at the left margin and is wrongly kept flat.
    fn fit_col(&self) -> usize {
        if self.needs_indent {
            self.col + self.pending_indent
        } else {
            self.col
        }
    }

    /// Write text that contains no newline.
    fn write_text(&mut self, s: &str) {
        if s.is_empty() {
            return;
        }
        self.flush_indent();
        self.out.push_str(s);
        self.col += s.chars().count();
    }

    fn write_line_suffix(&mut self, s: &str, kind: LineSuffixKind) {
        if s.is_empty() {
            return;
        }
        self.flush_indent();
        let separator_len = s.bytes().take_while(|byte| *byte == b' ').count();
        debug_assert!(separator_len > 0, "line suffix must include a separator");
        let separator_start = self.out.len();
        let code_col = self.col;
        self.out.push_str(s);
        self.col += s.chars().count();
        self.suffixes.push(LineSuffixMark {
            line: self.line,
            indent: self.line_indent,
            separator_start,
            separator_end: separator_start + separator_len,
            code_col,
            comment_width: s[separator_len..].chars().count(),
            kind,
        });
    }

    /// Move to a fresh line indented to `indent`.
    fn newline(&mut self, indent: usize) {
        self.out.push('\n');
        self.line += 1;
        self.col = 0;
        self.pending_indent = indent;
        self.line_indent = indent;
        self.needs_indent = true;
    }

    /// Emit a blank line, then position on a fresh line indented to `indent`.
    fn empty_line(&mut self, indent: usize) {
        self.out.push('\n');
        self.out.push('\n');
        self.line += 2;
        self.col = 0;
        self.pending_indent = indent;
        self.line_indent = indent;
        self.needs_indent = true;
    }

    /// Splice source the formatter was told not to touch, byte for byte.
    ///
    /// Unlike [`Writer::write_verbatim`], the pending indent is *dropped* rather
    /// than honored: the text was sliced from the start of its own line, so its
    /// original indentation is already there, and emitting the structural indent
    /// too would shift it. This is the one place where the formatter deliberately
    /// declines to choose a column.
    fn write_skipped(&mut self, s: &str) {
        self.needs_indent = false;
        self.pending_indent = 0;
        self.write_verbatim(s);
    }

    /// Splice a possibly multi-line string verbatim. The string is assumed to
    /// already carry its own indentation, so only a pending indent on the very
    /// first line is honored.
    fn write_verbatim(&mut self, s: &str) {
        let mut first = true;
        for segment in s.split('\n') {
            if first {
                self.flush_indent();
                first = false;
            } else {
                self.out.push('\n');
                self.line += 1;
                self.col = 0;
                self.needs_indent = false;
            }
            self.out.push_str(segment);
            self.col += segment.chars().count();
        }
    }

    fn finish(mut self, line_width: usize) -> String {
        let mut replacements: Vec<(usize, usize, usize)> = Vec::new();
        let mut start = 0usize;
        while start < self.suffixes.len() {
            let mut same_line_end = start + 1;
            while same_line_end < self.suffixes.len()
                && self.suffixes[same_line_end].line == self.suffixes[start].line
            {
                same_line_end += 1;
            }
            if same_line_end > start + 1 {
                // Multiple suffix nodes on one physical line are not separate
                // code/comment pairs and form a hard alignment boundary.
                start = same_line_end;
                continue;
            }

            let mut end = start + 1;
            while end < self.suffixes.len()
                && self.suffixes[end].line == self.suffixes[end - 1].line + 1
                && self.suffixes[end].kind == self.suffixes[start].kind
                && (self.suffixes[start].kind == LineSuffixKind::QuartoAnnotation
                    || self.suffixes[end].indent == self.suffixes[start].indent)
                && (end + 1 == self.suffixes.len()
                    || self.suffixes[end + 1].line != self.suffixes[end].line)
            {
                end += 1;
            }

            let run = &self.suffixes[start..end];
            if run.len() >= 2 {
                let target = run
                    .iter()
                    .map(|suffix| suffix.code_col)
                    .max()
                    .expect("non-empty suffix run")
                    + 1;
                if run
                    .iter()
                    .all(|suffix| target + suffix.comment_width <= line_width)
                {
                    for suffix in run {
                        replacements.push((
                            suffix.separator_start,
                            suffix.separator_end,
                            target - suffix.code_col,
                        ));
                    }
                }
            }
            start = end;
        }

        // Earlier byte offsets remain valid when edits are applied from right
        // to left, even when a shorter line gains several spaces.
        for (start, end, width) in replacements.into_iter().rev() {
            self.out.replace_range(start..end, &" ".repeat(width));
        }
        self.out
    }
}

impl Printer {
    pub(crate) fn new(style: FormatStyle) -> Self {
        Self {
            line_width: style.line_width,
            indent_unit: style.indent_width,
        }
    }

    /// Print a complete document starting at column 0.
    pub(crate) fn print(&self, ir: &Ir) -> String {
        self.run(ir, 0, 0)
    }

    /// Print an expression that will be placed at indent level `indent_level`,
    /// without emitting the leading indent on the first line (the caller does
    /// that). The starting column accounts for the indent so width decisions
    /// match where the expression actually sits.
    pub(crate) fn print_at(&self, ir: &Ir, indent_level: usize) -> String {
        let base = indent_level * self.indent_unit;
        self.run(ir, base, base)
    }

    /// Render `ir` on a single line, ignoring the configured line width so no
    /// nested group breaks of its own accord. `None` when the result still spans
    /// several lines, i.e. the document carries a forced break and so has no
    /// flat form at all.
    ///
    /// Table layout uses this both to measure a cell and to emit it: a cell that
    /// cannot lie flat has no place in an aligned row, and one that can has no
    /// layout freedom left to hand back to the printer.
    pub(crate) fn render_flat(&self, ir: &Ir) -> Option<String> {
        let unbounded = Printer {
            line_width: usize::MAX,
            indent_unit: self.indent_unit,
        };
        let text = unbounded.run(ir, 0, 0);
        (!text.contains('\n')).then_some(text)
    }

    fn run(&self, ir: &Ir, base_indent: usize, init_col: usize) -> String {
        self.run_with_mode(ir, base_indent, init_col, Mode::Break)
    }

    fn run_with_mode(&self, ir: &Ir, base_indent: usize, init_col: usize, mode: Mode) -> String {
        let mut w = Writer::new();
        w.col = init_col;
        w.line_indent = base_indent;
        let mut stack: Vec<(usize, Mode, &Ir)> = vec![(base_indent, mode, ir)];
        while let Some((indent, mode, node)) = stack.pop() {
            match node {
                Ir::Nil => {}
                Ir::Text(s) => w.write_text(s),
                Ir::Verbatim { text, .. } => w.write_verbatim(text),
                Ir::Skipped(text) => w.write_skipped(text),
                // A trailing comment renders inline; Writer retains its
                // structured position so adjacent suffixes can align after the
                // layout is fixed. Fit measurement still treats it as zero width.
                Ir::LineSuffix { text, kind } => w.write_line_suffix(text, *kind),
                Ir::Concat(items) => {
                    for item in items.iter().rev() {
                        stack.push((indent, mode, item));
                    }
                }
                Ir::Indent(inner) => {
                    stack.push((indent + self.indent_unit, mode, inner));
                }
                Ir::BreakBody(inner) => {
                    stack.push((indent, Mode::Break, inner));
                }
                Ir::Line => match mode {
                    Mode::Flat => w.write_text(" "),
                    Mode::Break => w.newline(indent),
                },
                Ir::SoftLine => {
                    if mode == Mode::Break {
                        w.newline(indent);
                    }
                }
                Ir::HardLine => w.newline(indent),
                Ir::EmptyLine => w.empty_line(indent),
                Ir::IfBreak { flat, broken } => {
                    let chosen = if mode == Mode::Break { broken } else { flat };
                    stack.push((indent, mode, chosen));
                }
                Ir::Group {
                    inner,
                    expand,
                    hug,
                    hug_excuse_overflow,
                } => {
                    let m = if *expand {
                        Mode::Break
                    } else if *hug {
                        // A trailing-block hug measures only its own prefix up to
                        // the block's opening brace; what follows sits on the
                        // block's closing line, not this one.
                        if self.fits(w.fit_col(), inner, true, *hug_excuse_overflow) {
                            Mode::Flat
                        } else {
                            Mode::Break
                        }
                    } else if self.group_fits(w.fit_col(), inner, &stack) {
                        Mode::Flat
                    } else {
                        Mode::Break
                    };
                    stack.push((indent, m, inner));
                }
                Ir::ConditionalGroup(cands) => {
                    let (m, chosen) = self.pick_candidate(w.fit_col(), cands);
                    stack.push((indent, m, chosen));
                }
                Ir::ConditionalGroupAllLines(cands) => {
                    let (m, chosen) = self.pick_candidate_all_lines(w.fit_col(), indent, cands);
                    stack.push((indent, m, chosen));
                }
            }
        }
        w.finish(self.line_width)
    }

    /// Pick the layout for an [`Ir::ConditionalGroup`] at the current column:
    /// the first candidate whose first line fits is rendered flat; if none, the
    /// last candidate is rendered broken. With a single candidate this is a
    /// "break-aware group" — flat if its first line fits, broken otherwise.
    fn pick_candidate<'a>(&self, col: usize, cands: &'a [Ir]) -> (Mode, &'a Ir) {
        let n = cands.len();
        for (i, c) in cands.iter().enumerate() {
            if self.first_line_fits(col, c) {
                return (Mode::Flat, c);
            }
            if i + 1 == n {
                return (Mode::Break, c);
            }
        }
        unreachable!("Ir::ConditionalGroup builder rejects empty candidate lists")
    }

    /// Pick the layout for an [`Ir::ConditionalGroupAllLines`]: the first
    /// candidate every one of whose rendered lines fits within `line_width`
    /// is rendered flat; if none qualifies the last candidate is rendered
    /// broken. The IR-native equivalent of the legacy `fits_with_newlines`
    /// check.
    fn pick_candidate_all_lines<'a>(
        &self,
        col: usize,
        indent: usize,
        cands: &'a [Ir],
    ) -> (Mode, &'a Ir) {
        let n = cands.len();
        for (i, c) in cands.iter().enumerate() {
            if self.all_lines_fit(col, indent, c) {
                return (Mode::Flat, c);
            }
            if i + 1 == n {
                return (Mode::Break, c);
            }
        }
        unreachable!("Ir::ConditionalGroupAllLines builder rejects empty candidate lists")
    }

    /// Whether every line `node` would render to fits within `line_width`,
    /// when placed at column `start_col` under the active `indent` in Flat
    /// mode (the mode the chosen candidate would be rendered in). Used by
    /// [`Self::pick_candidate_all_lines`]. Renders the candidate via the
    /// same printer machinery (so nested group decisions match the real
    /// render), then walks the output lines.
    fn all_lines_fit(&self, start_col: usize, indent: usize, node: &Ir) -> bool {
        let rendered = self.run_with_mode(node, indent, start_col, Mode::Flat);
        let mut lines = rendered.split('\n');
        if let Some(first) = lines.next()
            && start_col + first.chars().count() > self.line_width
        {
            return false;
        }
        for line in lines {
            if line.chars().count() > self.line_width {
                return false;
            }
        }
        true
    }

    /// Simulate `node` flat, starting at column `start_col`. Returns false on the
    /// first forced break or as soon as the running width exceeds the line.
    ///
    /// When `hug` is set, a forced line break (`HardLine`/`EmptyLine`) instead
    /// stops the measurement *successfully*: only the prefix up to a trailing
    /// block's opening brace needs to fit. A forced-break `Verbatim` (a comment)
    /// still fails, so a comment in the prefix prevents hugging.
    /// Whether an overflowing atom of width `w` should be *excused* during a
    /// hug-prefix fit: it can never fit on any line (`w >= line_width`), so
    /// breaking the argument list would not rescue it — only cost lines. Gated
    /// on `excuse_overflow`, which the rule sets solely when every leading
    /// argument is a bare atom (nothing breaking could rescue). See the
    /// `hug_excuse_overflow` field on [`Ir::Group`].
    fn atom_is_unfittable(&self, hug: bool, excuse_overflow: bool, w: usize) -> bool {
        hug && excuse_overflow && w >= self.line_width
    }

    fn fits(&self, start_col: usize, node: &Ir, hug: bool, excuse_overflow: bool) -> bool {
        let mut remaining = self.line_width.saturating_sub(start_col);
        let mut stack: Vec<&Ir> = vec![node];
        while let Some(node) = stack.pop() {
            match node {
                // A line suffix (trailing comment) is zero width for fit.
                Ir::Nil | Ir::SoftLine | Ir::LineSuffix { .. } => {}
                Ir::Text(s) => {
                    let w = s.chars().count();
                    if w > remaining {
                        if self.atom_is_unfittable(hug, excuse_overflow, w) {
                            return true;
                        }
                        return false;
                    }
                    remaining -= w;
                }
                Ir::HardLine | Ir::EmptyLine => return hug,
                // Skipped source owns its lines, so it can never be laid flat.
                Ir::Skipped(_) => return false,
                Ir::Verbatim { text, force_break } => {
                    if *force_break {
                        // A multi-line force-break verbatim (e.g. a brace-token
                        // param default) carries its own embedded line breaks
                        // and behaves like a HardLine for hugging: the prefix
                        // up to its own first newline is what needs to fit.
                        // A single-line force-break (a standalone comment) still
                        // fails — a comment in the prefix forbids the hug.
                        if hug && text.contains('\n') {
                            return true;
                        }
                        return false;
                    }
                    let w = text.chars().count();
                    if w > remaining {
                        if self.atom_is_unfittable(hug, excuse_overflow, w) {
                            return true;
                        }
                        return false;
                    }
                    remaining -= w;
                }
                Ir::Concat(items) => {
                    for item in items.iter().rev() {
                        stack.push(item);
                    }
                }
                // Transparent to the flat simulation: a forced break inside still
                // ends measurement via `HardLine`/`EmptyLine` (success under `hug`,
                // failure otherwise), exactly as if the body were not wrapped.
                Ir::Indent(inner) | Ir::BreakBody(inner) => stack.push(inner),
                Ir::Line => {
                    if remaining == 0 {
                        return false;
                    }
                    remaining -= 1;
                }
                Ir::IfBreak { flat, .. } => stack.push(flat),
                Ir::Group { inner, expand, .. } => {
                    if *expand {
                        return false;
                    }
                    stack.push(inner);
                }
                // Conservative: measure as the flat-most candidate. A nested
                // conditional group inside a flat measurement is rare today
                // (the only producer is the trailing-function call hug); if
                // and when one nests, this matches the most permissive layout.
                Ir::ConditionalGroup(cands) | Ir::ConditionalGroupAllLines(cands) => {
                    if let Some(first) = cands.first() {
                        stack.push(first);
                    }
                }
            }
        }
        true
    }

    /// Rest-aware fit check for a non-hugging [`Ir::Group`]: whether `inner`
    /// laid flat, *followed by* the already-queued `rest` commands up to the
    /// next line break, fits within the line width from `start_col`. Trailing
    /// same-line content (e.g. the closing `)` of a call hugging this group as
    /// its sole argument) counts toward the decision, so a group breaks when the
    /// inner plus what follows would overflow — not just the inner in isolation.
    /// This is the Wadler/Prettier "fits the rest of the line" rule and the cure
    /// for break decisions that were previously purely local.
    fn group_fits(&self, start_col: usize, inner: &Ir, rest: &[(usize, Mode, &Ir)]) -> bool {
        let mut col = start_col;
        let mut stack: Vec<&Ir> = vec![inner];
        while let Some(node) = stack.pop() {
            match node {
                // A line suffix (trailing comment) is zero width for fit.
                Ir::Nil | Ir::SoftLine | Ir::LineSuffix { .. } => {}
                Ir::Text(s) => {
                    col += s.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::HardLine | Ir::EmptyLine | Ir::Skipped(_) => return false,
                Ir::Verbatim { text, force_break } => {
                    if *force_break {
                        return false;
                    }
                    col += text.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::Concat(items) => {
                    for item in items.iter().rev() {
                        stack.push(item);
                    }
                }
                Ir::Indent(i) | Ir::BreakBody(i) => stack.push(i),
                Ir::Line => {
                    col += 1;
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::IfBreak { flat, .. } => stack.push(flat),
                Ir::Group {
                    inner: gi, expand, ..
                } => {
                    if *expand {
                        return false;
                    }
                    stack.push(gi);
                }
                Ir::ConditionalGroup(cands) | Ir::ConditionalGroupAllLines(cands) => {
                    if let Some(first) = cands.first() {
                        stack.push(first);
                    }
                }
            }
        }
        self.rest_fits(col, rest)
    }

    /// Measure the queued commands `rest` (the printer stack after the group
    /// being decided) from `start_col`, stopping at the first line break. Each
    /// command keeps its already-decided mode; an undecided nested group is
    /// measured flat (optimistic), an expanded one in break mode so its first
    /// soft break ends the line. Returns whether everything up to that break
    /// fits within the line width.
    fn rest_fits(&self, start_col: usize, rest: &[(usize, Mode, &Ir)]) -> bool {
        let mut col = start_col;
        let mut work: Vec<(Mode, &Ir)> = rest.iter().map(|(_, m, n)| (*m, *n)).collect();
        while let Some((mode, node)) = work.pop() {
            match node {
                Ir::Nil | Ir::SoftLine if mode == Mode::Flat => {}
                Ir::Nil => {}
                // A line suffix (trailing comment) is zero width for fit; the
                // break that follows it is measured on its own.
                Ir::LineSuffix { .. } => {}
                Ir::SoftLine => return true,
                Ir::Text(s) => {
                    col += s.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::Verbatim { text, .. } => {
                    if let Some((first, _)) = text.split_once('\n') {
                        col += first.chars().count();
                        return col <= self.line_width;
                    }
                    col += text.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                // Like a hard break: the current line ends at it.
                Ir::HardLine | Ir::EmptyLine | Ir::Skipped(_) => return true,
                Ir::Line => match mode {
                    Mode::Flat => {
                        col += 1;
                        if col > self.line_width {
                            return false;
                        }
                    }
                    Mode::Break => return true,
                },
                Ir::Concat(items) => {
                    for item in items.iter().rev() {
                        work.push((mode, item));
                    }
                }
                Ir::Indent(i) => work.push((mode, i)),
                // The body genuinely renders broken, whatever the surrounding
                // (possibly hug-flat) mode: measure it that way so a breakable
                // group inside is not mistaken for flat. This is the fix for a
                // leftmost group breaking when a hug-flat block body sits to the
                // right of the group being decided.
                Ir::BreakBody(inner) => work.push((Mode::Break, inner)),
                Ir::IfBreak { flat, broken } => {
                    work.push((mode, if mode == Mode::Break { broken } else { flat }));
                }
                Ir::Group { inner, expand, .. } => {
                    // An undecided group inherits the surrounding mode: when the
                    // rest of the line is being laid out in `Break` mode, the
                    // group *can* break, so its first soft break ends the line —
                    // a later sibling group breaking is what accommodates the
                    // overflow, rather than forcing *this* group to break. Only a
                    // group whose parent is flat (or one already expanded) is
                    // measured flat. This is Prettier's `groupMode = doc.break ?
                    // BREAK : mode` rule, and the cure for breaking the leftmost
                    // group when a rightmost one should break instead.
                    work.push((if *expand { Mode::Break } else { mode }, inner));
                }
                Ir::ConditionalGroup(cands) | Ir::ConditionalGroupAllLines(cands) => {
                    let candidate = if mode == Mode::Break {
                        cands.last()
                    } else {
                        cands.first()
                    };
                    if let Some(candidate) = candidate {
                        work.push((mode, candidate));
                    }
                }
            }
        }
        col <= self.line_width
    }

    /// Does the *first line* of `node` fit starting at `start_col`? Unlike
    /// [`Self::fits`] (a flat simulation), this lets nested [`Ir::Group`]s
    /// decide their own break naturally — they re-use the existing flat
    /// `fits` exactly as the real printer does — and treats the first
    /// newline that would actually be emitted (a `HardLine`/`EmptyLine`, a
    /// `Line`/`SoftLine` in `Break` mode, or anything in a nested group
    /// decided `Break`) as success. A *single-line* forced-break `Verbatim`
    /// (e.g. a standalone comment) fails, since it can't be rendered flat;
    /// a *multi-line* `Verbatim` (e.g. a function arg fallback-rendered as
    /// a multi-line legacy chunk) measures only its first line — its own
    /// embedded newline counts as the success signal.
    fn first_line_fits(&self, start_col: usize, node: &Ir) -> bool {
        let mut col = start_col;
        let mut stack: Vec<(Mode, &Ir)> = vec![(Mode::Flat, node)];
        while let Some((mode, node)) = stack.pop() {
            match node {
                // A line suffix (trailing comment) is zero width for fit.
                Ir::Nil | Ir::LineSuffix { .. } => {}
                Ir::Text(s) => {
                    col += s.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::Skipped(_) => return false,
                Ir::Verbatim { text, force_break } => {
                    if let Some(first_line) = text.split_once('\n').map(|(l, _)| l) {
                        col += first_line.chars().count();
                        if col > self.line_width {
                            return false;
                        }
                        return true;
                    }
                    if *force_break {
                        return false;
                    }
                    col += text.chars().count();
                    if col > self.line_width {
                        return false;
                    }
                }
                Ir::Concat(items) => {
                    for item in items.iter().rev() {
                        stack.push((mode, item));
                    }
                }
                Ir::Indent(inner) => stack.push((mode, inner)),
                Ir::BreakBody(inner) => stack.push((Mode::Break, inner)),
                Ir::Line => match mode {
                    Mode::Flat => {
                        col += 1;
                        if col > self.line_width {
                            return false;
                        }
                    }
                    Mode::Break => return true,
                },
                Ir::SoftLine => {
                    if mode == Mode::Break {
                        return true;
                    }
                }
                Ir::HardLine | Ir::EmptyLine => return true,
                Ir::IfBreak { flat, broken } => {
                    let chosen = if mode == Mode::Break { broken } else { flat };
                    stack.push((mode, chosen));
                }
                Ir::Group {
                    inner,
                    expand,
                    hug,
                    hug_excuse_overflow,
                } => {
                    let m = if *expand || !self.fits(col, inner, *hug, *hug_excuse_overflow) {
                        Mode::Break
                    } else {
                        Mode::Flat
                    };
                    stack.push((m, inner));
                }
                Ir::ConditionalGroup(cands) | Ir::ConditionalGroupAllLines(cands) => {
                    let (m, chosen) = self.pick_candidate(col, cands);
                    stack.push((m, chosen));
                }
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::super::style::LineEnding;
    use super::*;

    /// A block that always breaks: `{`, an indented body, then `}`.
    fn block() -> Ir {
        Ir::concat([
            Ir::text("{"),
            Ir::indent(Ir::concat([Ir::hard_line(), Ir::text("body")])),
            Ir::hard_line(),
            Ir::text("}"),
        ])
    }

    /// `f(a, {block})` as a hug group: prefix `f(a, ` then a trailing block.
    fn hug_call() -> Ir {
        Ir::group_hug(Ir::concat([
            Ir::text("f("),
            Ir::indent(Ir::concat([
                Ir::soft_line(),
                Ir::text("a"),
                Ir::if_break(Ir::text(", "), Ir::text(",")),
            ])),
            Ir::if_break(block(), Ir::indent(Ir::concat([Ir::soft_line(), block()]))),
            Ir::soft_line(),
            Ir::text(")"),
        ]))
    }

    #[test]
    fn hug_group_keeps_prefix_flat_when_it_fits() {
        let printer = Printer::new(FormatStyle::default());
        assert_eq!(printer.print(&hug_call()), "f(a, {\n  body\n})");
    }

    #[test]
    fn line_suffix_is_zero_width_and_keeps_a_group_flat() {
        // A group whose flat form fits at 80 only because the trailing comment is
        // not counted: `aaaa || bbbb` (12 cols) fits, the comment does not.
        let style = FormatStyle {
            line_width: 14,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        let group = Ir::group(Ir::concat([
            Ir::text("aaaa"),
            Ir::if_break(
                Ir::text(" || "),
                Ir::concat([Ir::text(" ||"), Ir::hard_line()]),
            ),
            Ir::text("bbbb"),
        ]));
        // With the comment counted (18 cols) the group would break; as a zero-width
        // line suffix it stays flat and the comment rides the end of the line.
        let ir = Ir::concat([group, Ir::line_suffix(" # note")]);
        assert_eq!(printer.print(&ir), "aaaa || bbbb # note");
    }

    #[test]
    fn adjacent_line_suffixes_align_to_the_longest_prefix() {
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::concat([
            Ir::text("a"),
            Ir::line_suffix(" # first"),
            Ir::hard_line(),
            Ir::text("long"),
            Ir::line_suffix(" # second"),
        ]);
        assert_eq!(printer.print(&ir), "a    # first\nlong # second");
    }

    #[test]
    fn suffix_alignment_counts_unicode_columns_not_bytes() {
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::concat([
            Ir::text("é"),
            Ir::line_suffix(" # first"),
            Ir::hard_line(),
            Ir::text("long"),
            Ir::line_suffix(" # second"),
        ]);
        assert_eq!(printer.print(&ir), "é    # first\nlong # second");
    }

    #[test]
    fn suffix_alignment_stops_at_a_different_indentation() {
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::concat([
            Ir::text("a"),
            Ir::line_suffix(" # first"),
            Ir::indent(Ir::concat([
                Ir::hard_line(),
                Ir::text("long"),
                Ir::line_suffix(" # second"),
            ])),
        ]);
        assert_eq!(printer.print(&ir), "a # first\n  long # second");
    }

    #[test]
    fn quarto_annotations_align_across_indentation() {
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::concat([
            Ir::text("a"),
            Ir::quarto_annotation_suffix(" # <1>"),
            Ir::indent(Ir::concat([
                Ir::hard_line(),
                Ir::text("long"),
                Ir::quarto_annotation_suffix(" # <2>"),
            ])),
        ]);
        assert_eq!(printer.print(&ir), "a      # <1>\n  long # <2>");
    }

    #[test]
    fn multiple_suffixes_on_one_line_break_alignment() {
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::concat([
            Ir::text("a"),
            Ir::line_suffix(" # first"),
            Ir::line_suffix(" # second"),
            Ir::hard_line(),
            Ir::text("long"),
            Ir::line_suffix(" # third"),
        ]);
        assert_eq!(printer.print(&ir), "a # first # second\nlong # third");
    }

    #[test]
    fn suffix_run_stays_unaligned_if_padding_would_overflow() {
        let style = FormatStyle {
            line_width: 14,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        let ir = Ir::concat([
            Ir::text("a"),
            Ir::line_suffix(" # 1234567890"),
            Ir::hard_line(),
            Ir::text("long"),
            Ir::line_suffix(" # short"),
        ]);
        assert_eq!(printer.print(&ir), "a # 1234567890\nlong # short");
    }

    #[test]
    fn hug_group_expands_when_prefix_does_not_fit() {
        // A narrow line forces even the short prefix `f(a, {` to break.
        let style = FormatStyle {
            line_width: 5,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        assert_eq!(
            printer.print(&hug_call()),
            "f(\n  a,\n  {\n    body\n  }\n)"
        );
    }

    #[test]
    fn hug_group_expands_when_prefix_has_a_comment() {
        // A forced-break verbatim (a comment) in the prefix prevents hugging
        // even though the prefix is short.
        let printer = Printer::new(FormatStyle::default());
        let ir = Ir::group_hug(Ir::concat([
            Ir::text("f("),
            Ir::indent(Ir::concat([
                Ir::soft_line(),
                Ir::verbatim_forced("# c"),
                Ir::hard_line(),
                Ir::text("a"),
                Ir::if_break(Ir::text(", "), Ir::text(",")),
            ])),
            Ir::if_break(block(), Ir::indent(Ir::concat([Ir::soft_line(), block()]))),
            Ir::soft_line(),
            Ir::text(")"),
        ]));
        // Expanded: the comment lands on its own line and the block is indented.
        assert_eq!(printer.print(&ir), "f(\n  # c\n  a,\n  {\n    body\n  }\n)");
    }

    /// A nested group whose flat form overflows the line but whose own break
    /// emits a newline before the overflow point. The conditional group's
    /// first-line measurement lets the nested group break, so the outer line
    /// fits even though the inner cannot stay flat.
    fn nested_breakable_group(width: usize) -> Ir {
        let long = "x".repeat(width);
        // Inner group: flat = `(<long>)` (overflows at width ≥ ~outer.width);
        // broken = `(\n  <long>\n)`.
        let inner = Ir::group(Ir::concat([
            Ir::text("("),
            Ir::indent(Ir::concat([Ir::soft_line(), Ir::text(long)])),
            Ir::soft_line(),
            Ir::text(")"),
        ]));
        // Outer candidate: `f` then the inner group. Its first line is `f(`.
        Ir::concat([Ir::text("f"), inner])
    }

    #[test]
    fn conditional_group_single_candidate_flat_when_first_line_fits() {
        // The inner group cannot fit flat (long >> width), but the conditional
        // group's first-line measurement lets it break naturally: `f(` fits
        // and the inner emits its own newline.
        let style = FormatStyle {
            line_width: 10,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        let ir = Ir::conditional_group([nested_breakable_group(20)]);
        assert_eq!(printer.print(&ir), "f(\n  xxxxxxxxxxxxxxxxxxxx\n)");
    }

    #[test]
    fn conditional_group_single_candidate_breaks_when_first_line_does_not_fit() {
        // A long literal in the candidate's first line itself blows the budget
        // before any nested group can break: fall to Break mode for the same
        // (single) candidate.
        let style = FormatStyle {
            line_width: 5,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        // Candidate: `verylong` then a Line. In Flat: `verylong ` overflows;
        // in Break: the Line becomes a newline.
        let ir = Ir::conditional_group([Ir::concat([
            Ir::text("verylong"),
            Ir::line(),
            Ir::text("x"),
        ])]);
        assert_eq!(printer.print(&ir), "verylong\nx");
    }

    #[test]
    fn conditional_group_picks_first_fitting_candidate() {
        let style = FormatStyle {
            line_width: 6,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        // c0 doesn't fit; c1 fits; c2 (fallback) never reached.
        let c0 = Ir::text("toolongtofit");
        let c1 = Ir::text("ok");
        let c2 = Ir::concat([Ir::text("fallback"), Ir::hard_line(), Ir::text("more")]);
        let ir = Ir::conditional_group([c0, c1, c2]);
        assert_eq!(printer.print(&ir), "ok");
    }

    #[test]
    fn conditional_group_falls_back_to_last_in_break_mode() {
        let style = FormatStyle {
            line_width: 4,
            indent_width: 2,
            line_ending: LineEnding::Lf,
        };
        let printer = Printer::new(style);
        // Neither earlier candidate fits; the last is rendered broken (its
        // `Line` becomes a newline).
        let c0 = Ir::text("toolongtofit");
        let c1 = Ir::text("alsotoolong");
        let c2 = Ir::concat([Ir::text("ab"), Ir::line(), Ir::text("cd")]);
        let ir = Ir::conditional_group([c0, c1, c2]);
        assert_eq!(printer.print(&ir), "ab\ncd");
    }
}