pprint 0.3.6

Flexible and lightweight pretty printing library for Rust
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
use rustc_hash::FxHashMap;

use crate::DigitCount;
use crate::doc::Doc;
use crate::utils::text_justify;

struct PrintItem<'a> {
    doc: &'a Doc<'a>,
    indent_delta: usize,

    left: Option<&'a Doc<'a>>,
    break_left: usize,

    /// Whether the enclosing Group decided to break.
    /// Set by Group when it decides `needs_breaking`, read by IfBreak.
    break_mode: bool,
}

impl<'a> PrintItem<'a> {
    #[inline(always)]
    fn new(doc: &'a Doc<'a>, indent_delta: usize) -> Self {
        Self {
            doc,
            indent_delta,
            left: None,
            break_left: 0,
            break_mode: false,
        }
    }
}

struct PrintState<'a> {
    stack: Vec<PrintItem<'a>>,
    output: Vec<u8>,

    current_line_len: usize,
    indent_delta: usize,

    space_cache: Vec<u8>,
    join_breaks: Vec<usize>,
    doc_lengths: Vec<usize>,
    text_length_cache: FxHashMap<*const Doc<'a>, usize>,
}

#[inline(always)]
fn is_literal_doc(doc: &Doc) -> bool {
    match doc {
        Doc::Null => false,
        Doc::Char(_)
        | Doc::DoubleChar(_)
        | Doc::TripleChar(_)
        | Doc::QuadChar(_)
        | Doc::SmallBytes(_, _)
        | Doc::Bytes(_, _)
        | Doc::String(_)
        | Doc::i8(_)
        | Doc::i16(_)
        | Doc::i32(_)
        | Doc::i64(_)
        | Doc::i128(_)
        | Doc::isize(_)
        | Doc::u8(_)
        | Doc::u16(_)
        | Doc::u32(_)
        | Doc::u64(_)
        | Doc::u128(_)
        | Doc::usize(_)
        | Doc::f32(_)
        | Doc::f64(_)
        | Doc::Line
        | Doc::Softline
        | Doc::Mediumline
        | Doc::Hardline => true,
        Doc::DoubleDoc(doc1, doc2) => is_literal_doc(doc1) && is_literal_doc(doc2),
        Doc::TripleDoc(doc1, doc2, doc3) => {
            is_literal_doc(doc1) && is_literal_doc(doc2) && is_literal_doc(doc3)
        }
        Doc::Concat(_) => false,
        Doc::Group(_) => false,
        Doc::Indent(_) => false,
        Doc::Dedent(_) => false,
        Doc::Join(_) => false,
        Doc::SmartJoin(_) => false,
        Doc::LinearJoin(_) => false,
        Doc::IfBreak(_, _) => false,
    }
}

#[inline(always)]
fn count_join_length<'a>(
    sep: &'a Doc<'a>,
    docs: &'a [Doc<'a>],
    printer: &Printer,
    cache: &mut FxHashMap<*const Doc<'a>, usize>,
) -> usize {
    if docs.is_empty() {
        return 0;
    }

    let doc_len: usize = docs
        .iter()
        .map(|d| count_text_length(d, printer, cache))
        .sum();
    let sep_len = count_text_length(sep, printer, cache);

    doc_len + sep_len * (docs.len() - 1)
}

#[inline(always)]
fn literal_text_length(doc: &Doc, printer: &Printer) -> Option<usize> {
    match doc {
        Doc::Null => Some(0),
        Doc::Char(_) => Some(1),
        Doc::DoubleChar(_) => Some(2),
        Doc::TripleChar(_) => Some(3),
        Doc::QuadChar(_) => Some(4),
        Doc::SmallBytes(_, len) => Some(*len),
        Doc::Bytes(_, len) => Some(*len),
        Doc::String(s) => Some(s.len()),
        Doc::i8(value) => Some(value.len()),
        Doc::i16(value) => Some(value.len()),
        Doc::i32(value) => Some(value.len()),
        Doc::i64(value) => Some(value.len()),
        Doc::i128(value) => Some(value.len()),
        Doc::isize(value) => Some(value.len()),
        Doc::u8(value) => Some(value.len()),
        Doc::u16(value) => Some(value.len()),
        Doc::u32(value) => Some(value.len()),
        Doc::u64(value) => Some(value.len()),
        Doc::u128(value) => Some(value.len()),
        Doc::usize(value) => Some(value.len()),
        Doc::f32(value) => {
            assert!(
                value.is_finite(),
                "pprint: non-finite float is unsupported (value: {value})"
            );
            Some(10)
        }
        Doc::f64(value) => {
            assert!(
                value.is_finite(),
                "pprint: non-finite float is unsupported (value: {value})"
            );
            Some(20)
        }
        Doc::Softline => Some(1),
        Doc::Mediumline => Some(0),
        Doc::Hardline | Doc::Line => Some(printer.max_width),
        Doc::DoubleDoc(doc1, doc2) => {
            Some(literal_text_length(doc1, printer)? + literal_text_length(doc2, printer)?)
        }
        Doc::TripleDoc(doc1, doc2, doc3) => Some(
            literal_text_length(doc1, printer)?
                + literal_text_length(doc2, printer)?
                + literal_text_length(doc3, printer)?,
        ),
        Doc::Concat(_)
        | Doc::Group(_)
        | Doc::Indent(_)
        | Doc::Dedent(_)
        | Doc::Join(_)
        | Doc::SmartJoin(_)
        | Doc::LinearJoin(_)
        | Doc::IfBreak(_, _) => None,
    }
}

#[inline]
fn count_text_length<'a>(
    doc: &'a Doc<'a>,
    printer: &Printer,
    cache: &mut FxHashMap<*const Doc<'a>, usize>,
) -> usize {
    if let Some(len) = literal_text_length(doc, printer) {
        return len;
    }

    let key = doc as *const _;
    if let Some(&len) = cache.get(&key) {
        return len;
    }
    let len = match doc {
        Doc::Concat(docs) => docs
            .iter()
            .map(|d| count_text_length(d, printer, cache))
            .sum(),

        Doc::DoubleDoc(doc1, doc2) => {
            count_text_length(doc1, printer, cache) + count_text_length(doc2, printer, cache)
        }
        Doc::TripleDoc(doc1, doc2, doc3) => {
            count_text_length(doc1, printer, cache)
                + count_text_length(doc2, printer, cache)
                + count_text_length(doc3, printer, cache)
        }

        Doc::Group(d) => count_text_length(d, printer, cache),

        // Indent/Dedent only affect post-break indentation, not flat-mode width.
        Doc::Indent(d) => count_text_length(d, printer, cache),
        Doc::Dedent(d) => count_text_length(d, printer, cache),

        Doc::Join(inner) => count_join_length(&inner.0, &inner.1, printer, cache),

        Doc::SmartJoin(inner) => count_join_length(&inner.0, &inner.1, printer, cache),

        Doc::LinearJoin(inner) => count_join_length(&inner.0, &inner.1, printer, cache),

        // Use the "fits" branch for width calculation — we're measuring
        // whether the enclosing Group fits inline (break_mode=false).
        Doc::IfBreak(_t, f) => count_text_length(f, printer, cache),

        Doc::Null
        | Doc::Char(_)
        | Doc::DoubleChar(_)
        | Doc::TripleChar(_)
        | Doc::QuadChar(_)
        | Doc::SmallBytes(_, _)
        | Doc::Bytes(_, _)
        | Doc::String(_)
        | Doc::i8(_)
        | Doc::i16(_)
        | Doc::i32(_)
        | Doc::i64(_)
        | Doc::i128(_)
        | Doc::isize(_)
        | Doc::u8(_)
        | Doc::u16(_)
        | Doc::u32(_)
        | Doc::u64(_)
        | Doc::u128(_)
        | Doc::usize(_)
        | Doc::f32(_)
        | Doc::f64(_)
        | Doc::Softline
        | Doc::Mediumline
        | Doc::Hardline
        | Doc::Line => unreachable!("literal docs are handled in literal_text_length"),
    };
    cache.insert(key, len);
    len
}

#[inline(always)]
fn smart_join_breaks<'a>(
    sep: &'a Doc<'a>,
    docs: &'a [Doc<'a>],

    state: &mut PrintState<'a>,
    printer: &mut Printer,
) {
    let max_width = printer.max_width.saturating_sub(state.indent_delta);

    let sep_length = count_text_length(sep, printer, &mut state.text_length_cache);
    state.doc_lengths.clear();
    state.doc_lengths.extend(
        docs.iter()
            .map(|d| count_text_length(d, printer, &mut state.text_length_cache)),
    );

    // sep_length stays as-is — text_justify already accounts for separators.

    state.join_breaks.clear();

    text_justify(
        sep_length,
        &state.doc_lengths,
        max_width,
        state.current_line_len,
        &mut state.join_breaks,
    )
}

#[inline(always)]
fn format_int<T>(value: T, state: &mut PrintState) -> usize
where
    T: itoap::Integer + std::fmt::Display,
{
    let prev_len = state.output.len();
    itoap::write_to_vec(&mut state.output, value);
    state.output.len() - prev_len
}

#[inline(always)]
fn format_f64(value: f64, state: &mut PrintState) -> usize {
    assert!(
        value.is_finite(),
        "pprint: non-finite float is unsupported (value: {value})"
    );
    let mut buf = dragonbox::Buffer::new();
    let s = buf.format_finite(value).as_bytes();
    state.output.extend_from_slice(s);
    s.len()
}

#[inline(always)]
fn format_f32(value: f32, state: &mut PrintState) -> usize {
    format_f64(value as f64, state)
}

#[inline(always)]
fn append_line(state: &mut PrintState, printer: &mut Printer) -> usize {
    let space_cache = &mut state.space_cache;

    let indent_delta = state.indent_delta;

    if space_cache.is_empty() {
        space_cache.push(b'\n');
    }

    if indent_delta >= space_cache.len() {
        let space = if printer.use_tabs { b'\t' } else { b' ' };
        for _ in space_cache.len()..=indent_delta {
            space_cache.push(space);
        }
    }

    // space_cache layout: ['\n', ' ', ' ', ' ', ...] — index 0 is the newline,
    // indices 1..=indent_delta are indent spaces.  Output indent_delta + 1 bytes
    // to get newline + indent_delta spaces.
    let output_len = indent_delta + 1;
    state.output.extend_from_slice(&space_cache[..output_len]);

    indent_delta
}

#[inline(always)]
fn handle_line<'a>(doc: &'a Doc<'a>, state: &mut PrintState<'a>, printer: &mut Printer) -> usize {
    match doc {
        Doc::Line => {
            state.output.push(b'\n');
            0
        }

        Doc::Hardline => append_line(state, printer),

        Doc::Mediumline if state.current_line_len > printer.max_width / 2 => {
            append_line(state, printer)
        }
        Doc::Mediumline => state.current_line_len,

        Doc::Softline if state.current_line_len > printer.max_width => append_line(state, printer),
        Doc::Softline => state.current_line_len,

        _ => panic!("handle_line called with non-line Doc variant"),
    }
}

#[inline(always)]
fn handle_literal<'a>(doc: &'a Doc<'a>, state: &mut PrintState<'a>, printer: &mut Printer) {
    let offset = match doc {
        Doc::Null => 0,

        Doc::Char(c) => {
            state.output.push(*c);
            1
        }
        Doc::DoubleChar(cs) => {
            state.output.extend_from_slice(cs);
            2
        }
        Doc::TripleChar(cs) => {
            state.output.extend_from_slice(cs);
            3
        }
        Doc::QuadChar(cs) => {
            state.output.extend_from_slice(cs);
            4
        }

        Doc::SmallBytes(b, len) => {
            state.output.extend_from_slice(&b[..*len]);
            *len
        }

        Doc::Bytes(b, len) => {
            state.output.extend_from_slice(b);
            *len
        }

        Doc::String(s) => {
            state.output.extend_from_slice(s.as_bytes());
            s.len()
        }

        Doc::i8(v) => format_int(*v, state),
        Doc::i16(v) => format_int(*v, state),
        Doc::i32(v) => format_int(*v, state),
        Doc::i64(v) => format_int(*v, state),
        Doc::i128(v) => format_int(*v, state),
        Doc::isize(v) => format_int(*v, state),

        Doc::u8(v) => format_int(*v, state),
        Doc::u16(v) => format_int(*v, state),
        Doc::u32(v) => format_int(*v, state),
        Doc::u64(v) => format_int(*v, state),
        Doc::u128(v) => format_int(*v, state),
        Doc::usize(v) => format_int(*v, state),

        Doc::f32(v) => format_f32(*v, state),
        Doc::f64(v) => format_f64(*v, state),

        Doc::Line | Doc::Softline | Doc::Mediumline | Doc::Hardline => 0,

        Doc::DoubleDoc(_, _) | Doc::TripleDoc(_, _, _) => 0,

        Doc::Concat(_)
        | Doc::Group(_)
        | Doc::Indent(_)
        | Doc::Dedent(_)
        | Doc::Join(_)
        | Doc::SmartJoin(_)
        | Doc::LinearJoin(_)
        | Doc::IfBreak(_, _) => {
            panic!("handle_literal called with non-literal Doc variant")
        }
    };

    state.current_line_len = match doc {
        Doc::Line | Doc::Hardline | Doc::Mediumline | Doc::Softline => {
            handle_line(doc, state, printer)
        }
        _ => state.current_line_len + offset,
    };

    match doc {
        Doc::DoubleDoc(doc1, doc2) => {
            handle_literal(doc1, state, printer);
            handle_literal(doc2, state, printer);
        }
        Doc::TripleDoc(doc1, doc2, doc3) => {
            handle_literal(doc1, state, printer);
            handle_literal(doc2, state, printer);
            handle_literal(doc3, state, printer);
        }
        Doc::Null
        | Doc::Char(_)
        | Doc::DoubleChar(_)
        | Doc::TripleChar(_)
        | Doc::QuadChar(_)
        | Doc::SmallBytes(_, _)
        | Doc::Bytes(_, _)
        | Doc::String(_)
        | Doc::i8(_)
        | Doc::i16(_)
        | Doc::i32(_)
        | Doc::i64(_)
        | Doc::i128(_)
        | Doc::isize(_)
        | Doc::u8(_)
        | Doc::u16(_)
        | Doc::u32(_)
        | Doc::u64(_)
        | Doc::u128(_)
        | Doc::usize(_)
        | Doc::f32(_)
        | Doc::f64(_)
        | Doc::Line
        | Doc::Softline
        | Doc::Mediumline
        | Doc::Hardline => {}
        Doc::Concat(_)
        | Doc::Group(_)
        | Doc::Indent(_)
        | Doc::Dedent(_)
        | Doc::Join(_)
        | Doc::SmartJoin(_)
        | Doc::LinearJoin(_)
        | Doc::IfBreak(_, _) => {
            panic!("handle_literal reached non-literal composite variant")
        }
    }
}

fn handle_join<'a>(
    doc: &'a Doc<'a>,
    sep: &'a Doc<'a>,
    docs: &'a [Doc<'a>],
    state: &mut PrintState<'a>,
    printer: &mut Printer,
    parent_break_mode: bool,
) {
    let is_smart_join = matches!(doc, Doc::SmartJoin(_));

    if is_smart_join {
        smart_join_breaks(sep, docs, state, printer);
    } else {
        state.join_breaks.clear();
    }

    let sep_is_lit = is_literal_doc(sep);

    // Step 2: reverse-iterating cursor instead of binary_search per item.
    // join_breaks is sorted ascending, items processed in reverse (high→low),
    // so we walk the cursor backwards.
    let mut break_cursor = state.join_breaks.len();

    for (i, d) in docs.iter().rev().enumerate() {
        let i = docs.len() - i - 1;

        let left = if i > 0 && sep_is_lit { Some(sep) } else { None };

        let (break_left, item_break_mode) = if is_smart_join && break_cursor > 0 && state.join_breaks[break_cursor - 1] == i {
            break_cursor -= 1;
            // SmartJoin decided to break before this item — override parent's break_mode
            // so IfBreak separators use the break branch only at SmartJoin-chosen positions.
            // Use max(indent_delta, 1) to ensure break_left > 0 triggers the newline.
            (state.indent_delta.max(1), true)
        } else {
            // No break at this position — use flat mode for IfBreak separators,
            // even if the parent Group is broken.
            (0, if is_smart_join { false } else { parent_break_mode })
        };

        state.stack.push(PrintItem {
            doc: d,
            indent_delta: state.indent_delta,
            left,
            break_left,
            break_mode: item_break_mode,
        });

        if !sep_is_lit && i > 0 {
            state.stack.push(PrintItem {
                doc: sep,
                indent_delta: state.indent_delta,
                left: None,
                // Separator gets break_mode from SmartJoin's decision but NO break_left —
                // the line break is emitted by the following item's break_left, not here.
                break_left: 0,
                break_mode: item_break_mode,
            });
        }
    }
}

fn handle_linear_join<'a>(
    sep: &'a Doc<'a>,
    docs: &'a [Doc<'a>],
    state: &mut PrintState<'a>,
    printer: &mut Printer,
) {
    if docs.is_empty() {
        return;
    }

    let max_width = printer.max_width.saturating_sub(state.indent_delta);
    let sep_len = count_text_length(sep, printer, &mut state.text_length_cache);
    let sep_is_lit = is_literal_doc(sep);

    // Forward scan: compute break positions inline, then push in reverse.
    // We reuse state.join_breaks to store break indices.
    state.join_breaks.clear();

    let mut line_len = state.current_line_len;

    for (i, d) in docs.iter().enumerate() {
        let item_width = count_text_length(d, printer, &mut state.text_length_cache);
        if i > 0 {
            let next_len = line_len + sep_len + item_width;
            if next_len > max_width {
                state.join_breaks.push(i);
                line_len = state.indent_delta + item_width;
            } else {
                line_len = next_len;
            }
        } else {
            line_len += item_width;
        }
    }

    // Now push items onto the stack in reverse, using the computed break positions.
    let mut break_cursor = state.join_breaks.len();

    for (i, d) in docs.iter().rev().enumerate() {
        let i = docs.len() - i - 1;

        let left = if i > 0 && sep_is_lit { Some(sep) } else { None };

        let break_left = if break_cursor > 0 && state.join_breaks[break_cursor - 1] == i {
            break_cursor -= 1;
            state.indent_delta
        } else {
            0
        };

        state.stack.push(PrintItem {
            doc: d,
            indent_delta: state.indent_delta,
            left,
            break_left,
            break_mode: false,
        });

        if !sep_is_lit && i > 0 {
            state.stack.push(PrintItem {
                doc: sep,
                indent_delta: state.indent_delta,
                left: None,
                // Separator gets no break_left — the line break is emitted by the
                // following item's break_left, not the separator (matching handle_join).
                break_left: 0,
                break_mode: false,
            });
        }
    }
}

fn handle_n_docs_unrolled<'a>(doc: &'a Doc<'a>, state: &mut PrintState<'a>, printer: &mut Printer) {
    match doc {
        Doc::DoubleDoc(doc1, doc2) => {
            let doc1_is_lit = is_literal_doc(doc1);
            let doc2_is_lit = is_literal_doc(doc2);

            if doc1_is_lit && doc2_is_lit {
                handle_literal(doc1, state, printer);
                handle_literal(doc2, state, printer);
            } else if doc1_is_lit && !doc2_is_lit {
                handle_literal(doc1, state, printer);

                state.stack.push(PrintItem::new(doc2, state.indent_delta));
            } else {
                state.stack.push(PrintItem::new(doc2, state.indent_delta));
                state.stack.push(PrintItem::new(doc1, state.indent_delta));
            }
        }

        Doc::TripleDoc(doc1, doc2, doc3) => {
            let doc3_is_lit = is_literal_doc(doc3);
            let doc2_is_lit = is_literal_doc(doc2);
            let doc1_is_lit = is_literal_doc(doc1);

            if doc1_is_lit && doc2_is_lit && doc3_is_lit {
                handle_literal(doc1, state, printer);
                handle_literal(doc2, state, printer);
                handle_literal(doc3, state, printer);
            } else if doc1_is_lit && doc2_is_lit && !doc3_is_lit {
                handle_literal(doc1, state, printer);
                handle_literal(doc2, state, printer);

                state.stack.push(PrintItem::new(doc3, state.indent_delta));
            } else if doc1_is_lit && !doc2_is_lit && !doc3_is_lit {
                handle_literal(doc1, state, printer);

                state.stack.push(PrintItem::new(doc3, state.indent_delta));
                state.stack.push(PrintItem::new(doc2, state.indent_delta));
            } else {
                state.stack.push(PrintItem::new(doc3, state.indent_delta));
                state.stack.push(PrintItem::new(doc2, state.indent_delta));
                state.stack.push(PrintItem::new(doc1, state.indent_delta));
            }
        }
        _ => {
            unreachable!()
        }
    }
}

/// Shared render loop used by both `pprint` and `pprint_ref`.
///
/// Drains the `state.stack`, dispatching each `PrintItem` to the appropriate
/// handler. Factored into a macro to avoid duplicating the ~100-line loop
/// across the owning (`pprint`) and borrowing (`pprint_ref`) entry points.
macro_rules! render_loop {
    ($state:expr, $printer:expr) => {
        while let Some(PrintItem {
            doc,
            indent_delta,
            left,
            break_left,
            break_mode,
        }) = $state.stack.pop()
        {
            if let Some(left) = left {
                handle_literal(left, &mut $state, &mut $printer);
            }
            if break_left > 0 {
                // Strip trailing whitespace before the line break.
                while $state.output.last() == Some(&b' ')
                    || $state.output.last() == Some(&b'\t')
                {
                    $state.output.pop();
                }
                $state.current_line_len = append_line(&mut $state, &mut $printer);
            }

            let (doc, indent_delta) = match doc {
                Doc::Indent(d) => (d.as_ref(), indent_delta.saturating_add($printer.indent)),
                Doc::Dedent(d) => (d.as_ref(), indent_delta.saturating_sub($printer.indent)),
                _ => (doc, indent_delta),
            };

            $state.indent_delta = indent_delta;

            match doc {
                Doc::Concat(docs) => {
                    for d in docs.iter().rev() {
                        $state.stack.push(PrintItem {
                            doc: d,
                            indent_delta,
                            left: None,
                            break_left: 0,
                            break_mode,
                        });
                    }
                }
                Doc::Group(d) => {
                    let group_width =
                        count_text_length(d, &$printer, &mut $state.text_length_cache);
                    let needs_breaking =
                        $state.current_line_len.saturating_add(group_width) > $printer.max_width;
                    // Standard Wadler-Lindig: Group only sets break_mode for children.
                    // IfBreak docs inside the Group handle actual line breaking.
                    // No automatic leading break or trailing Hardline.
                    $state.stack.push(PrintItem {
                        doc: d,
                        indent_delta,
                        left: None,
                        break_left: 0,
                        break_mode: needs_breaking,
                    });
                }
                Doc::IfBreak(doc, other) => {
                    let doc = if break_mode { doc } else { other };
                    $state.stack.push(PrintItem {
                        doc,
                        indent_delta,
                        left: None,
                        break_left: 0,
                        break_mode,
                    });
                }
                Doc::Join(inner) | Doc::SmartJoin(inner) => {
                    handle_join(
                        doc,
                        &inner.0,
                        &inner.1,
                        &mut $state,
                        &mut $printer,
                        break_mode,
                    );
                }
                Doc::LinearJoin(inner) => {
                    handle_linear_join(&inner.0, &inner.1, &mut $state, &mut $printer);
                }

                Doc::DoubleDoc(_, _) | Doc::TripleDoc(_, _, _) => {
                    handle_n_docs_unrolled(doc, &mut $state, &mut $printer);
                }
                Doc::Indent(_) | Doc::Dedent(_) => {
                    unreachable!("Indent/Dedent should be normalized before dispatch");
                }
                Doc::Null
                | Doc::Char(_)
                | Doc::DoubleChar(_)
                | Doc::TripleChar(_)
                | Doc::QuadChar(_)
                | Doc::SmallBytes(_, _)
                | Doc::Bytes(_, _)
                | Doc::String(_)
                | Doc::i8(_)
                | Doc::i16(_)
                | Doc::i32(_)
                | Doc::i64(_)
                | Doc::i128(_)
                | Doc::isize(_)
                | Doc::u8(_)
                | Doc::u16(_)
                | Doc::u32(_)
                | Doc::u64(_)
                | Doc::u128(_)
                | Doc::usize(_)
                | Doc::f32(_)
                | Doc::f64(_)
                | Doc::Line
                | Doc::Softline
                | Doc::Mediumline
                | Doc::Hardline => {
                    handle_literal(doc, &mut $state, &mut $printer);
                }
            }
        }
    };
}

/// Finalize the output buffer into a String.
///
/// In debug builds, validates UTF-8. In release builds, uses unchecked
/// conversion since all Doc sources produce valid UTF-8 (string literals,
/// newlines, spaces, digits).
#[inline]
fn finalize_output(output: Vec<u8>) -> String {
    if cfg!(debug_assertions) {
        String::from_utf8(output).expect(
            "pprint: output buffer contained invalid UTF-8 — all Doc sources must produce valid UTF-8",
        )
    } else {
        unsafe { String::from_utf8_unchecked(output) }
    }
}

/// Create a fresh `PrintState` with default capacities.
fn new_print_state<'a>() -> PrintState<'a> {
    PrintState {
        stack: Vec::with_capacity(64),
        output: Vec::with_capacity(1024),

        current_line_len: 0,
        indent_delta: 0,

        space_cache: Vec::with_capacity(128),
        join_breaks: Vec::new(),
        doc_lengths: Vec::new(),
        text_length_cache: FxHashMap::with_capacity_and_hasher(256, Default::default()),
    }
}

/// Core pretty printing function.
///
/// Takes a document and a printer configuration and returns a String.
/// Uses a stack to avoid recursion, keeping track of the current line length,
/// and indent level.
pub fn pprint<'a>(doc: impl Into<Doc<'a>>, mut printer: Printer) -> String {
    let doc = doc.into();
    let mut state = new_print_state();

    state.stack.push(PrintItem {
        doc: &doc,
        indent_delta: 0,
        left: None,
        break_left: 0,
        break_mode: false,
    });

    render_loop!(state, printer);
    finalize_output(state.output)
}

/// Pretty-print a document by reference, avoiding cloning.
///
/// Same as `pprint()` but borrows the Doc tree instead of consuming it.
/// Useful for benchmarks and when the same Doc tree needs to be rendered
/// multiple times (e.g., LSP formatting).
pub fn pprint_ref<'a>(doc: &'a Doc<'a>, mut printer: Printer) -> String {
    let mut state = new_print_state();

    state.stack.push(PrintItem {
        doc,
        indent_delta: 0,
        left: None,
        break_left: 0,
        break_mode: false,
    });

    render_loop!(state, printer);
    finalize_output(state.output)
}

#[derive(Debug, Clone, Copy)]
pub struct Printer {
    pub max_width: usize,
    pub indent: usize,
    pub use_tabs: bool,
}

/// Default printer configuration.
pub const PRINTER: Printer = Printer {
    max_width: 80,
    indent: 4,
    use_tabs: false,
};

impl Default for Printer {
    fn default() -> Self {
        PRINTER
    }
}

/// A builder for a printer configuration.
/// Allows for setting the max width, indent, and whether to use tabs.
impl Printer {
    pub const fn new(max_width: usize, indent: usize, use_tabs: bool) -> Self {
        Printer {
            max_width,
            indent,
            use_tabs,
        }
    }
}