profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
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
//! Wadler-style document algebra and its printer.
//!
//! The document is stored in flat arenas: container nodes refer to ranges of
//! [`Document::children`], so building and dropping a document never
//! allocates per group. Unchanged source is referenced by byte span rather
//! than copied.

#[derive(Clone, Debug)]
pub enum Doc {
    /// Synthesised text held in [`Document::text`].
    Text(Span),
    /// A byte range of the source, printed verbatim.
    Source(Span),
    Group(Group),
    Indent(Fragment),
    Line(Line),
    /// Deferred to the end of the current line, before its line break.
    LineSuffix(Fragment),
    BreakParent,
}

#[derive(Clone, Copy, Debug)]
pub struct Group {
    pub broken: bool,
    pub contents: Fragment,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
    start: u32,
    end: u32,
}

impl Span {
    fn new(start: usize, end: usize) -> Self {
        Self {
            start: u32::try_from(start).expect("a document contains fewer than 2^32 bytes"),
            end: u32::try_from(end).expect("a document contains fewer than 2^32 bytes"),
        }
    }

    pub fn range(self) -> std::ops::Range<usize> {
        self.start as usize..self.end as usize
    }
}

/// A sequence of document node IDs in [`Document::children`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fragment {
    start: u32,
    end: u32,
}

impl Fragment {
    fn new(start: usize, end: usize) -> Self {
        Self {
            start: u32::try_from(start).expect("a document contains fewer than 2^32 edges"),
            end: u32::try_from(end).expect("a document contains fewer than 2^32 edges"),
        }
    }

    fn range(self) -> std::ops::Range<usize> {
        self.start as usize..self.end as usize
    }
}

#[derive(Debug)]
pub struct Document {
    docs: Vec<Doc>,
    children: Vec<u32>,
    text: String,
    root: Fragment,
}

impl Document {
    fn doc(&self, id: u32) -> &Doc {
        &self.docs[id as usize]
    }

    fn ids(&self, fragment: Fragment) -> &[u32] {
        &self.children[fragment.range()]
    }

    fn text(&self, span: Span) -> &str {
        &self.text[span.range()]
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Separator {
    Empty,
    Space,
}

impl Separator {
    fn as_str(self) -> &'static str {
        match self {
            Self::Empty => "",
            Self::Space => " ",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Line {
    /// Emitted instead of a newline when flat.
    separator: Separator,
    /// A forced line always breaks and breaks every enclosing group.
    pub force: bool,
}

pub const SOFT: Line = Line {
    separator: Separator::Empty,
    force: false,
};
pub const SPACE: Line = Line {
    separator: Separator::Space,
    force: false,
};
pub const HARD: Line = Line {
    separator: Separator::Space,
    force: true,
};

/// Builds a document tree in flat arenas. Groups are marked broken eagerly
/// (`BreakParent` propagation) so layouts can be decided while building.
pub struct Builder {
    docs: Vec<Doc>,
    children: Vec<u32>,
    text: String,
    /// IDs in every open target. `target_starts` delimits the active suffix.
    working: Vec<u32>,
    /// Stack of open groups. Index 0 is the root.
    groups: Vec<OpenGroup>,
    /// Start in `working` of each open target. Index 0 is the root.
    target_starts: Vec<usize>,
}

struct OpenGroup {
    broken: bool,
    /// Depth of `target_starts` when this group was opened; used to check
    /// that every container opened inside it is closed inside it.
    target_depth: usize,
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

impl Builder {
    pub fn new() -> Self {
        Self::with_capacity(0)
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            docs: Vec::with_capacity(capacity),
            children: Vec::with_capacity(capacity),
            text: String::new(),
            working: Vec::new(),
            groups: vec![OpenGroup {
                broken: false,
                target_depth: 0,
            }],
            target_starts: vec![0],
        }
    }

    fn push_doc(&mut self, doc: Doc) {
        let id = u32::try_from(self.docs.len()).expect("a document contains fewer than 2^32 nodes");
        self.docs.push(doc);
        self.working.push(id);
    }

    fn target_last(&self) -> Option<u32> {
        let start = *self.target_starts.last().expect("builder always has a target");
        (self.working.len() > start).then(|| *self.working.last().expect("non-empty target"))
    }

    fn seal_target(&mut self) -> Fragment {
        let start = self.target_starts.pop().expect("builder always has a target");
        let fragment_start = self.children.len();
        self.children.extend_from_slice(&self.working[start..]);
        self.working.truncate(start);
        Fragment::new(fragment_start, self.children.len())
    }

    /// Appends text. A lone space after text that already ends with a space
    /// is dropped, so comments can be padded on both sides without doubling
    /// the separator a caller adds.
    pub fn text(&mut self, s: &str) {
        if s.is_empty() {
            return;
        }
        if s == " "
            && let Some(id) = self.target_last()
            && let Doc::Text(previous) = &self.docs[id as usize]
            && self.text[previous.range()].ends_with(' ')
        {
            return;
        }
        let start = self.text.len();
        self.text.push_str(s);
        let span = Span::new(start, self.text.len());
        if let Some(id) = self.target_last()
            && let Doc::Text(previous) = &mut self.docs[id as usize]
            && previous.end == span.start
        {
            previous.end = span.end;
        } else {
            self.push_doc(Doc::Text(span));
        }
    }

    pub fn source(&mut self, start: usize, end: usize) {
        if start == end {
            return;
        }
        let span = Span::new(start, end);
        if let Some(id) = self.target_last()
            && let Doc::Source(previous) = &mut self.docs[id as usize]
            && previous.end == span.start
        {
            previous.end = span.end;
        } else {
            self.push_doc(Doc::Source(span));
        }
    }

    pub fn line(&mut self, line: Line) {
        self.push_doc(Doc::Line(line));
        if line.force {
            self.break_parent();
        }
    }

    #[cfg(test)]
    pub fn space(&mut self) {
        self.line(SPACE);
    }

    #[cfg(test)]
    pub fn soft(&mut self) {
        self.line(SOFT);
    }

    #[cfg(test)]
    pub fn hard(&mut self) {
        self.line(HARD);
    }

    pub fn break_parent(&mut self) {
        self.push_doc(Doc::BreakParent);
        for group in self.groups.iter_mut().rev() {
            if group.broken {
                break;
            }
            group.broken = true;
        }
    }

    fn push_target(&mut self) {
        self.target_starts.push(self.working.len());
    }

    fn pop_target(&mut self) -> Fragment {
        assert!(self.target_starts.len() > 1, "popped the root target");
        self.seal_target()
    }

    pub fn open_group(&mut self) {
        self.groups.push(OpenGroup {
            broken: false,
            target_depth: self.target_starts.len(),
        });
        self.push_target();
    }

    pub fn close_group(&mut self) {
        let contents = self.pop_target();
        let group = self.groups.pop().expect("open group");
        assert_eq!(
            self.target_starts.len(),
            group.target_depth,
            "group closed with containers still open"
        );
        self.push_doc(Doc::Group(Group {
            broken: group.broken,
            contents,
        }));
    }

    #[cfg(test)]
    pub fn group(&mut self, f: impl FnOnce(&mut Self)) {
        self.open_group();
        f(self);
        self.close_group();
    }

    pub fn open_indent(&mut self) {
        self.push_target();
    }

    pub fn close_indent(&mut self) {
        let contents = self.pop_target();
        self.push_doc(Doc::Indent(contents));
    }

    #[cfg(test)]
    pub fn indent(&mut self, f: impl FnOnce(&mut Self)) {
        self.open_indent();
        f(self);
        self.close_indent();
    }

    pub fn line_suffix(&mut self, f: impl FnOnce(&mut Self)) {
        self.push_target();
        f(self);
        let contents = self.pop_target();
        self.push_doc(Doc::LineSuffix(contents));
    }

    pub fn finish(mut self) -> Document {
        assert_eq!(self.groups.len(), 1, "unclosed group");
        assert_eq!(self.target_starts.len(), 1, "unclosed container");
        let root = self.seal_target();
        Document {
            docs: self.docs,
            children: self.children,
            text: self.text,
            root,
        }
    }
}

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

#[derive(Clone, Copy)]
struct Command {
    indent: usize,
    mode: Mode,
    id: u32,
}

struct Suffix {
    indent: usize,
    mode: Mode,
    contents: Fragment,
}

#[derive(Clone, Copy, Debug)]
pub struct PrintOptions {
    pub line_width: usize,
    pub indent_width: usize,
    pub output_capacity: usize,
}

pub fn print(document: &Document, source: &str, options: PrintOptions) -> String {
    render(
        document,
        source,
        options,
        String::with_capacity(options.output_capacity),
    )
}

/// Whether printing `document` would reproduce `source` exactly, decided
/// without materialising the output.
pub fn matches_source(document: &Document, source: &str, options: PrintOptions) -> bool {
    render(document, source, options, MatchOutput::new(source.as_bytes())).matches()
}

trait Output {
    fn write_str(&mut self, text: &str);
    fn write_spaces(&mut self, count: usize);
    fn trim_trailing(&mut self);
}

impl Output for String {
    fn write_str(&mut self, text: &str) {
        self.push_str(text);
    }

    fn write_spaces(&mut self, count: usize) {
        self.extend(std::iter::repeat_n(' ', count));
    }

    fn trim_trailing(&mut self) {
        let trimmed = self.trim_end_matches([' ', '\t']).len();
        self.truncate(trimmed);
    }
}

/// Compares written bytes against the expected source, tracking the start of
/// the current run of trailing whitespace so it can be un-written.
struct MatchOutput<'a> {
    expected: &'a [u8],
    cursor: usize,
    matches: bool,
    trailing_cursor: usize,
    trailing_matches: bool,
    trailing_len: usize,
}

impl<'a> MatchOutput<'a> {
    fn new(expected: &'a [u8]) -> Self {
        Self {
            expected,
            cursor: 0,
            matches: true,
            trailing_cursor: 0,
            trailing_matches: true,
            trailing_len: 0,
        }
    }

    fn compare(&mut self, bytes: &[u8]) {
        let available = self.expected.len().saturating_sub(self.cursor).min(bytes.len());
        self.matches &= available == bytes.len()
            && self.expected.get(self.cursor..self.cursor + available) == Some(&bytes[..available]);
        self.cursor = self.cursor.saturating_add(bytes.len());
    }

    fn begin_trailing(&mut self) {
        if self.trailing_len == 0 {
            self.trailing_cursor = self.cursor;
            self.trailing_matches = self.matches;
        }
    }

    fn matches(self) -> bool {
        self.matches && self.cursor == self.expected.len()
    }
}

impl Output for MatchOutput<'_> {
    fn write_str(&mut self, text: &str) {
        let bytes = text.as_bytes();
        let prefix_len = bytes
            .iter()
            .rposition(|byte| !matches!(byte, b' ' | b'\t'))
            .map_or(0, |index| index + 1);
        if prefix_len > 0 {
            self.compare(&bytes[..prefix_len]);
            self.trailing_len = 0;
        }
        if prefix_len < bytes.len() {
            self.begin_trailing();
            self.compare(&bytes[prefix_len..]);
            self.trailing_len += bytes.len() - prefix_len;
        }
    }

    fn write_spaces(&mut self, count: usize) {
        if count == 0 {
            return;
        }
        self.begin_trailing();
        let available = self.expected.len().saturating_sub(self.cursor).min(count);
        self.matches &= available == count
            && self
                .expected
                .get(self.cursor..self.cursor.saturating_add(available))
                .is_some_and(|bytes| bytes.iter().all(|&byte| byte == b' '));
        self.cursor = self.cursor.saturating_add(count);
        self.trailing_len += count;
    }

    fn trim_trailing(&mut self) {
        if self.trailing_len > 0 {
            self.cursor = self.trailing_cursor;
            self.matches = self.trailing_matches;
            self.trailing_len = 0;
        }
    }
}

fn render<T: Output>(document: &Document, source: &str, options: PrintOptions, mut out: T) -> T {
    debug_assert!(options.line_width > 0);
    debug_assert!(options.indent_width > 0);

    let mut position = 0usize;
    let mut commands = Vec::new();
    push_all(&mut commands, document, document.root, 0, Mode::Break);
    let mut remeasure = false;
    let mut suffixes: Vec<Suffix> = Vec::new();
    let mut fit_commands = Vec::new();

    while let Some(Command { indent, mode, id }) = commands.pop() {
        match document.doc(id) {
            Doc::Text(span) => {
                let text = document.text(*span);
                out.write_str(text);
                position += text_width(text);
            }
            Doc::Source(span) => {
                let text = &source[span.range()];
                out.write_str(text);
                position += text_width(text);
            }
            Doc::Group(group) => {
                if mode == Mode::Flat && !remeasure {
                    let next = if group.broken { Mode::Break } else { Mode::Flat };
                    push_all(&mut commands, document, group.contents, indent, next);
                } else {
                    remeasure = false;
                    if group.broken {
                        push_all(&mut commands, document, group.contents, indent, Mode::Break);
                    } else {
                        let mode = if fits(
                            document,
                            group.contents,
                            &commands,
                            source,
                            &mut fit_commands,
                            FitOptions {
                                indent,
                                remaining: options.line_width.saturating_sub(position),
                                within_width: position <= options.line_width,
                                indent_width: options.indent_width,
                            },
                        ) {
                            Mode::Flat
                        } else {
                            Mode::Break
                        };
                        push_all(&mut commands, document, group.contents, indent, mode);
                    }
                }
            }
            Doc::Line(line) => {
                if mode == Mode::Flat {
                    if line.force {
                        remeasure = true;
                    } else {
                        let separator = line.separator.as_str();
                        out.write_str(separator);
                        position += separator.len();
                        continue;
                    }
                }
                if !suffixes.is_empty() {
                    commands.push(Command { indent, mode, id });
                    flush_suffixes(&mut commands, document, &mut suffixes);
                    continue;
                }
                out.trim_trailing();
                out.write_str("\n");
                out.write_spaces(indent);
                position = indent;
            }
            Doc::Indent(contents) => push_all(
                &mut commands,
                document,
                *contents,
                indent.saturating_add(options.indent_width),
                mode,
            ),
            Doc::LineSuffix(contents) => suffixes.push(Suffix {
                indent,
                mode,
                contents: *contents,
            }),
            Doc::BreakParent => {}
        }
        if commands.is_empty() && !suffixes.is_empty() {
            flush_suffixes(&mut commands, document, &mut suffixes);
        }
    }
    out
}

fn push_all(commands: &mut Vec<Command>, document: &Document, docs: Fragment, indent: usize, mode: Mode) {
    commands.extend(document.ids(docs).iter().rev().map(|&id| Command { indent, mode, id }));
}

/// Suffixes print in the order they were queued.
fn flush_suffixes(commands: &mut Vec<Command>, document: &Document, suffixes: &mut Vec<Suffix>) {
    for suffix in suffixes.drain(..).rev() {
        push_all(commands, document, suffix.contents, suffix.indent, suffix.mode);
    }
}

struct FitOptions {
    indent: usize,
    remaining: usize,
    within_width: bool,
    indent_width: usize,
}

/// Whether `contents` printed flat, followed by whatever of `rest` is needed
/// to reach the next line break, fits in the remaining columns.
fn fits(
    document: &Document,
    contents: Fragment,
    rest: &[Command],
    source: &str,
    commands: &mut Vec<Command>,
    options: FitOptions,
) -> bool {
    if !options.within_width {
        return false;
    }
    let mut remaining = options.remaining as isize;
    let mut rest_index = rest.len();
    commands.clear();
    push_all(commands, document, contents, options.indent, Mode::Flat);
    while remaining >= 0 {
        let Command { indent, mode, id } = match commands.pop() {
            Some(command) => command,
            None => {
                if rest_index == 0 {
                    return true;
                }
                rest_index -= 1;
                commands.push(rest[rest_index]);
                continue;
            }
        };
        match document.doc(id) {
            Doc::Text(span) => remaining -= text_width(document.text(*span)) as isize,
            Doc::Source(span) => remaining -= text_width(&source[span.range()]) as isize,
            Doc::Group(group) => {
                let next = if group.broken { Mode::Break } else { mode };
                push_all(commands, document, group.contents, indent, next);
            }
            Doc::Line(line) => {
                if mode == Mode::Flat && !line.force {
                    remaining -= line.separator.as_str().len() as isize;
                    continue;
                }
                return true;
            }
            Doc::Indent(contents) => push_all(
                commands,
                document,
                *contents,
                indent.saturating_add(options.indent_width),
                mode,
            ),
            Doc::LineSuffix(_) | Doc::BreakParent => {}
        }
    }
    false
}

fn text_width(text: &str) -> usize {
    if text.is_ascii() {
        text.len()
    } else {
        text.chars().count()
    }
}

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

    fn render(f: impl FnOnce(&mut Builder), width: usize) -> String {
        let mut b = Builder::new();
        f(&mut b);
        print(
            &b.finish(),
            "",
            PrintOptions {
                line_width: width,
                indent_width: 4,
                output_capacity: 0,
            },
        )
    }

    fn list(b: &mut Builder) {
        b.group(|b| {
            b.text("[");
            b.indent(|b| {
                b.soft();
                b.text("aaaa,");
                b.space();
                b.text("bbbb");
            });
            b.soft();
            b.text("]");
        });
    }

    #[test]
    fn flat_when_it_fits() {
        assert_eq!(render(list, 80), "[aaaa, bbbb]");
    }

    #[test]
    fn breaks_and_indents_when_it_does_not_fit() {
        assert_eq!(render(list, 8), "[\n    aaaa,\n    bbbb\n]");
    }

    #[test]
    fn forced_break_propagates_to_enclosing_groups() {
        let s = render(
            |b| {
                b.group(|b| {
                    b.text("a");
                    b.space();
                    b.group(|b| {
                        b.text("b");
                        b.hard();
                        b.text("c");
                    });
                })
            },
            80,
        );
        assert_eq!(s, "a\nb\nc");
    }

    #[test]
    fn line_suffix_defers_to_end_of_line() {
        let s = render(
            |b| {
                b.text("x = 1;");
                b.line_suffix(|b| b.text(" // hi"));
                b.text(";");
                b.hard();
                b.text("y");
            },
            80,
        );
        assert_eq!(s, "x = 1;; // hi\ny");
    }

    #[test]
    fn trailing_whitespace_is_trimmed_before_a_line_break() {
        let s = render(
            |b| {
                b.text("a  ");
                b.hard();
                b.text("b");
            },
            80,
        );
        assert_eq!(s, "a\nb");
    }

    #[test]
    fn compares_rendered_output_without_materialising_it() {
        let mut b = Builder::new();
        b.text("a  ");
        b.indent(|b| {
            b.hard();
            b.text("b");
        });
        let docs = b.finish();
        let options = PrintOptions {
            line_width: 80,
            indent_width: 4,
            output_capacity: 0,
        };

        assert_eq!(print(&docs, "", options), "a\n    b");
        assert!(matches_source(&docs, "a\n    b", options));
        assert!(!matches_source(&docs, "a  \n    b", options));
        assert!(!matches_source(&docs, "a\n  b", options));
        assert!(!matches_source(&docs, "a\n    b\n", options));
    }

    #[test]
    fn adjacent_source_spans_merge() {
        let mut b = Builder::new();
        b.source(0, 1);
        b.source(1, 3);
        let docs = b.finish();

        assert_eq!(docs.ids(docs.root).len(), 1);
        assert_eq!(
            print(
                &docs,
                "abc",
                PrintOptions {
                    line_width: 80,
                    indent_width: 2,
                    output_capacity: 3,
                },
            ),
            "abc"
        );
    }
}