1 //! This pretty-printer is a direct reimplementation of Philip Karlton's
2 //! Mesa pretty-printer, as described in the appendix to
3 //! Derek C. Oppen, "Pretty Printing" (1979),
4 //! Stanford Computer Science Department STAN-CS-79-770,
5 //! <http://i.stanford.edu/pub/cstr/reports/cs/tr/79/770/CS-TR-79-770.pdf>.
7 //! The algorithm's aim is to break a stream into as few lines as possible
8 //! while respecting the indentation-consistency requirements of the enclosing
9 //! block, and avoiding breaking at silly places on block boundaries, for
10 //! example, between "x" and ")" in "x)".
12 //! I am implementing this algorithm because it comes with 20 pages of
13 //! documentation explaining its theory, and because it addresses the set of
14 //! concerns I've seen other pretty-printers fall down on. Weirdly. Even though
15 //! it's 32 years old. What can I say?
17 //! Despite some redundancies and quirks in the way it's implemented in that
18 //! paper, I've opted to keep the implementation here as similar as I can,
19 //! changing only what was blatantly wrong, a typo, or sufficiently
20 //! non-idiomatic rust that it really stuck out.
22 //! In particular you'll see a certain amount of churn related to INTEGER vs.
23 //! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two
24 //! somewhat readily? In any case, I've used usize for indices-in-buffers and
25 //! ints for character-sizes-and-indentation-offsets. This respects the need
26 //! for ints to "go negative" while carrying a pending-calculation balance, and
27 //! helps differentiate all the numbers flying around internally (slightly).
29 //! I also inverted the indentation arithmetic used in the print stack, since
30 //! the Mesa implementation (somewhat randomly) stores the offset on the print
31 //! stack in terms of margin-col rather than col itself. I store col.
33 //! I also implemented a small change in the String token, in that I store an
34 //! explicit length for the string. For most tokens this is just the length of
35 //! the accompanying string. But it's necessary to permit it to differ, for
36 //! encoding things that are supposed to "go on their own line" -- certain
37 //! classes of comment and blank-line -- where relying on adjacent
38 //! hardbreak-like Break tokens with long blankness indication doesn't actually
39 //! work. To see why, consider when there is a "thing that should be on its own
40 //! line" between two long blocks, say functions. If you put a hardbreak after
41 //! each function (or before each) and the breaking algorithm decides to break
42 //! there anyways (because the functions themselves are long) you wind up with
43 //! extra blank lines. If you don't put hardbreaks you can wind up with the
44 //! "thing which should be on its own line" not getting its own line in the
45 //! rare case of "really small functions" or such. This re-occurs with comments
46 //! and explicit blank lines. So in those cases we use a string with a payload
47 //! we want isolated to a line and an explicit length that's huge, surrounded
48 //! by two zero-length breaks. The algorithm will try its best to fit it on a
49 //! line (which it can't) and so naturally place the content on its own line to
50 //! avoid combining it with other lines and making matters even worse.
54 //! In case you do not have the paper, here is an explanation of what's going
57 //! There is a stream of input tokens flowing through this printer.
59 //! The printer buffers up to 3N tokens inside itself, where N is linewidth.
60 //! Yes, linewidth is chars and tokens are multi-char, but in the worst
61 //! case every token worth buffering is 1 char long, so it's ok.
63 //! Tokens are String, Break, and Begin/End to delimit blocks.
65 //! Begin tokens can carry an offset, saying "how far to indent when you break
66 //! inside here", as well as a flag indicating "consistent" or "inconsistent"
67 //! breaking. Consistent breaking means that after the first break, no attempt
68 //! will be made to flow subsequent breaks together onto lines. Inconsistent
69 //! is the opposite. Inconsistent breaking example would be, say:
72 //! foo(hello, there, good, friends)
75 //! breaking inconsistently to become
82 //! whereas a consistent breaking would yield:
91 //! That is, in the consistent-break blocks we value vertical alignment
92 //! more than the ability to cram stuff onto a line. But in all cases if it
93 //! can make a block a one-liner, it'll do so.
95 //! Carrying on with high-level logic:
97 //! The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and
98 //! 'right' indices denote the active portion of the ring buffer as well as
99 //! describing hypothetical points-in-the-infinite-stream at most 3N tokens
100 //! apart (i.e., "not wrapped to ring-buffer boundaries"). The paper will switch
101 //! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer
102 //! and point-in-infinite-stream senses freely.
104 //! There is a parallel ring buffer, `size`, that holds the calculated size of
105 //! each token. Why calculated? Because for Begin/End pairs, the "size"
106 //! includes everything between the pair. That is, the "size" of Begin is
107 //! actually the sum of the sizes of everything between Begin and the paired
108 //! End that follows. Since that is arbitrarily far in the future, `size` is
109 //! being rewritten regularly while the printer runs; in fact most of the
110 //! machinery is here to work out `size` entries on the fly (and give up when
111 //! they're so obviously over-long that "infinity" is a good enough
112 //! approximation for purposes of line breaking).
114 //! The "input side" of the printer is managed as an abstract process called
115 //! SCAN, which uses `scan_stack`, to manage calculating `size`. SCAN is, in
116 //! other words, the process of calculating 'size' entries.
118 //! The "output side" of the printer is managed by an abstract process called
119 //! PRINT, which uses `print_stack`, `margin` and `space` to figure out what to
120 //! do with each token/size pair it consumes as it goes. It's trying to consume
121 //! the entire buffered window, but can't output anything until the size is >=
122 //! 0 (sizes are set to negative while they're pending calculation).
124 //! So SCAN takes input and buffers tokens and pending calculations, while
125 //! PRINT gobbles up completed calculations and tokens from the buffer. The
126 //! theory is that the two can never get more than 3N tokens apart, because
127 //! once there's "obviously" too much data to fit on a line, in a size
128 //! calculation, SCAN will write "infinity" to the size and let PRINT consume
131 //! In this implementation (following the paper, again) the SCAN process is the
132 //! methods called `Printer::scan_*`, and the 'PRINT' process is the
133 //! method called `Printer::print`.
135 use std::borrow::Cow;
136 use std::collections::VecDeque;
140 /// How to break. Described in more detail in the module docs.
141 #[derive(Clone, Copy, PartialEq)]
147 #[derive(Clone, Copy)]
148 pub struct BreakToken {
153 #[derive(Clone, Copy)]
154 pub struct BeginToken {
161 // In practice a string token contains either a `&'static str` or a
162 // `String`. `Cow` is overkill for this because we never modify the data,
163 // but it's more convenient than rolling our own more specialized type.
164 String(Cow<'static, str>),
172 crate fn is_eof(&self) -> bool {
173 matches!(self, Token::Eof)
176 pub fn is_hardbreak_tok(&self) -> bool {
177 matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY }))
181 impl fmt::Display for Token {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 Token::String(ref s) => write!(f, "STR({},{})", s, s.len()),
185 Token::Break(_) => f.write_str("BREAK"),
186 Token::Begin(_) => f.write_str("BEGIN"),
187 Token::End => f.write_str("END"),
188 Token::Eof => f.write_str("EOF"),
193 fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String {
197 let mut s = String::from("[");
198 while i != right && l != 0 {
203 s.push_str(&format!("{}={}", buf[i].size, &buf[i].token));
211 #[derive(Copy, Clone)]
212 enum PrintStackBreak {
217 #[derive(Copy, Clone)]
218 struct PrintStackElem {
220 pbreak: PrintStackBreak,
223 const SIZE_INFINITY: isize = 0xffff;
225 pub fn mk_printer() -> Printer {
227 // Yes 55, it makes the ring buffers big enough to never fall behind.
228 let n: usize = 55 * linewidth;
229 debug!("mk_printer {}", linewidth);
233 margin: linewidth as isize,
234 space: linewidth as isize,
237 // Initialize a single entry; advance_right() will extend it on demand
238 // up to `buf_max_len` elements.
239 buf: vec![BufEntry::default()],
242 scan_stack: VecDeque::new(),
243 print_stack: Vec::new(),
244 pending_indentation: 0,
251 /// Width of lines we're constrained to
253 /// Number of spaces left on line
255 /// Index of left side of input stream
257 /// Index of right side of input stream
259 /// Ring-buffer of tokens and calculated sizes
261 /// Running size of stream "...left"
263 /// Running size of stream "...right"
265 /// Pseudo-stack, really a ring too. Holds the
266 /// primary-ring-buffers index of the Begin that started the
267 /// current block, possibly with the most recent Break after that
268 /// Begin (if there is any) on top of it. Stuff is flushed off the
269 /// bottom as it becomes irrelevant due to the primary ring-buffer
271 scan_stack: VecDeque<usize>,
272 /// Stack of blocks-in-progress being flushed by print
273 print_stack: Vec<PrintStackElem>,
274 /// Buffered indentation to avoid writing trailing whitespace
275 pending_indentation: isize,
284 impl Default for BufEntry {
285 fn default() -> Self {
286 BufEntry { token: Token::Eof, size: 0 }
291 pub fn last_token(&self) -> Token {
292 self.buf[self.right].token.clone()
295 /// Be very careful with this!
296 pub fn replace_last_token(&mut self, t: Token) {
297 self.buf[self.right].token = t;
300 fn scan_eof(&mut self) {
301 if !self.scan_stack.is_empty() {
307 fn scan_begin(&mut self, b: BeginToken) {
308 if self.scan_stack.is_empty() {
310 self.right_total = 1;
314 self.advance_right();
316 debug!("pp Begin({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
317 self.scan_push(BufEntry { token: Token::Begin(b), size: -self.right_total });
320 fn scan_end(&mut self) {
321 if self.scan_stack.is_empty() {
322 debug!("pp End/print Vec<{},{}>", self.left, self.right);
325 debug!("pp End/buffer Vec<{},{}>", self.left, self.right);
326 self.advance_right();
327 self.scan_push(BufEntry { token: Token::End, size: -1 });
331 fn scan_break(&mut self, b: BreakToken) {
332 if self.scan_stack.is_empty() {
334 self.right_total = 1;
338 self.advance_right();
340 debug!("pp Break({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
342 self.scan_push(BufEntry { token: Token::Break(b), size: -self.right_total });
343 self.right_total += b.blank_space;
346 fn scan_string(&mut self, s: Cow<'static, str>) {
347 if self.scan_stack.is_empty() {
348 debug!("pp String('{}')/print Vec<{},{}>", s, self.left, self.right);
349 self.print_string(s);
351 debug!("pp String('{}')/buffer Vec<{},{}>", s, self.left, self.right);
352 self.advance_right();
353 let len = s.len() as isize;
354 self.buf[self.right] = BufEntry { token: Token::String(s), size: len };
355 self.right_total += len;
360 fn check_stream(&mut self) {
362 "check_stream Vec<{}, {}> with left_total={}, right_total={}",
363 self.left, self.right, self.left_total, self.right_total
365 if self.right_total - self.left_total > self.space {
367 "scan window is {}, longer than space on line ({})",
368 self.right_total - self.left_total,
371 if Some(&self.left) == self.scan_stack.back() {
372 debug!("setting {} to infinity and popping", self.left);
373 let scanned = self.scan_pop_bottom();
374 self.buf[scanned].size = SIZE_INFINITY;
377 if self.left != self.right {
383 fn scan_push(&mut self, entry: BufEntry) {
384 debug!("scan_push {}", self.right);
385 self.buf[self.right] = entry;
386 self.scan_stack.push_front(self.right);
389 fn scan_pop(&mut self) -> usize {
390 self.scan_stack.pop_front().unwrap()
393 fn scan_top(&self) -> usize {
394 *self.scan_stack.front().unwrap()
397 fn scan_pop_bottom(&mut self) -> usize {
398 self.scan_stack.pop_back().unwrap()
401 fn advance_right(&mut self) {
403 self.right %= self.buf_max_len;
404 // Extend the buf if necessary.
405 if self.right == self.buf.len() {
406 self.buf.push(BufEntry::default());
408 assert_ne!(self.right, self.left);
411 fn advance_left(&mut self) {
413 "advance_left Vec<{},{}>, sizeof({})={}",
414 self.left, self.right, self.left, self.buf[self.left].size
417 let mut left_size = self.buf[self.left].size;
419 while left_size >= 0 {
420 let left = self.buf[self.left].token.clone();
422 let len = match left {
423 Token::Break(b) => b.blank_space,
424 Token::String(ref s) => {
425 let len = s.len() as isize;
426 assert_eq!(len, left_size);
432 self.print(left, left_size);
434 self.left_total += len;
436 if self.left == self.right {
441 self.left %= self.buf_max_len;
443 left_size = self.buf[self.left].size;
447 fn check_stack(&mut self, k: usize) {
448 if !self.scan_stack.is_empty() {
449 let x = self.scan_top();
450 match self.buf[x].token {
454 self.buf[x].size += self.right_total;
455 self.check_stack(k - 1);
459 // paper says + not =, but that makes no sense.
461 self.buf[x].size = 1;
462 self.check_stack(k + 1);
466 self.buf[x].size += self.right_total;
475 fn print_newline(&mut self, amount: isize) {
476 debug!("NEWLINE {}", amount);
478 self.pending_indentation = 0;
482 fn indent(&mut self, amount: isize) {
483 debug!("INDENT {}", amount);
484 self.pending_indentation += amount;
487 fn get_top(&self) -> PrintStackElem {
488 *self.print_stack.last().unwrap_or({
489 &PrintStackElem { offset: 0, pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) }
493 fn print_begin(&mut self, b: BeginToken, l: isize) {
495 let col = self.margin - self.space + b.offset;
496 debug!("print Begin -> push broken block at col {}", col);
498 .push(PrintStackElem { offset: col, pbreak: PrintStackBreak::Broken(b.breaks) });
500 debug!("print Begin -> push fitting block");
501 self.print_stack.push(PrintStackElem { offset: 0, pbreak: PrintStackBreak::Fits });
505 fn print_end(&mut self) {
506 debug!("print End -> pop End");
507 self.print_stack.pop().unwrap();
510 fn print_break(&mut self, b: BreakToken, l: isize) {
511 let top = self.get_top();
513 PrintStackBreak::Fits => {
514 debug!("print Break({}) in fitting block", b.blank_space);
515 self.space -= b.blank_space;
516 self.indent(b.blank_space);
518 PrintStackBreak::Broken(Breaks::Consistent) => {
519 debug!("print Break({}+{}) in consistent block", top.offset, b.offset);
520 self.print_newline(top.offset + b.offset);
521 self.space = self.margin - (top.offset + b.offset);
523 PrintStackBreak::Broken(Breaks::Inconsistent) => {
525 debug!("print Break({}+{}) w/ newline in inconsistent", top.offset, b.offset);
526 self.print_newline(top.offset + b.offset);
527 self.space = self.margin - (top.offset + b.offset);
529 debug!("print Break({}) w/o newline in inconsistent", b.blank_space);
530 self.indent(b.blank_space);
531 self.space -= b.blank_space;
537 fn print_string(&mut self, s: Cow<'static, str>) {
538 let len = s.len() as isize;
539 debug!("print String({})", s);
540 // assert!(len <= space);
543 // Write the pending indent. A more concise way of doing this would be:
545 // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
547 // But that is significantly slower. This code is sufficiently hot, and indents can get
548 // sufficiently large, that the difference is significant on some workloads.
549 self.out.reserve(self.pending_indentation as usize);
550 self.out.extend(std::iter::repeat(' ').take(self.pending_indentation as usize));
551 self.pending_indentation = 0;
552 self.out.push_str(&s);
555 fn print(&mut self, token: Token, l: isize) {
556 debug!("print {} {} (remaining line space={})", token, l, self.space);
557 debug!("{}", buf_str(&self.buf, self.left, self.right, 6));
559 Token::Begin(b) => self.print_begin(b, l),
560 Token::End => self.print_end(),
561 Token::Break(b) => self.print_break(b, l),
562 Token::String(s) => {
563 let len = s.len() as isize;
565 self.print_string(s);
567 Token::Eof => panic!(), // Eof should never get here.
571 // Convenience functions to talk to the printer.
574 pub fn rbox(&mut self, indent: usize, b: Breaks) {
575 self.scan_begin(BeginToken { offset: indent as isize, breaks: b })
578 /// Inconsistent breaking box
579 pub fn ibox(&mut self, indent: usize) {
580 self.rbox(indent, Breaks::Inconsistent)
583 /// Consistent breaking box
584 pub fn cbox(&mut self, indent: usize) {
585 self.rbox(indent, Breaks::Consistent)
588 pub fn break_offset(&mut self, n: usize, off: isize) {
589 self.scan_break(BreakToken { offset: off, blank_space: n as isize })
592 pub fn end(&mut self) {
596 pub fn eof(mut self) -> String {
601 pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
606 fn spaces(&mut self, n: usize) {
607 self.break_offset(n, 0)
610 crate fn zerobreak(&mut self) {
614 pub fn space(&mut self) {
618 pub fn hardbreak(&mut self) {
619 self.spaces(SIZE_INFINITY as usize)
622 pub fn is_beginning_of_line(&self) -> bool {
623 self.last_token().is_eof() || self.last_token().is_hardbreak_tok()
626 pub fn hardbreak_tok_offset(off: isize) -> Token {
627 Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY })