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`.
136 use std::borrow::Cow;
137 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 {
179 pub fn is_hardbreak_tok(&self) -> bool {
181 Token::Break(BreakToken { offset: 0, blank_space: bs }) if bs == SIZE_INFINITY => true,
187 impl fmt::Display for Token {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 Token::String(ref s) => write!(f, "STR({},{})", s, s.len()),
191 Token::Break(_) => f.write_str("BREAK"),
192 Token::Begin(_) => f.write_str("BEGIN"),
193 Token::End => f.write_str("END"),
194 Token::Eof => f.write_str("EOF"),
199 fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String {
203 let mut s = String::from("[");
204 while i != right && l != 0 {
209 s.push_str(&format!("{}={}", buf[i].size, &buf[i].token));
217 #[derive(Copy, Clone)]
218 enum PrintStackBreak {
223 #[derive(Copy, Clone)]
224 struct PrintStackElem {
226 pbreak: PrintStackBreak,
229 const SIZE_INFINITY: isize = 0xffff;
231 pub fn mk_printer() -> Printer {
233 // Yes 55, it makes the ring buffers big enough to never fall behind.
234 let n: usize = 55 * linewidth;
235 debug!("mk_printer {}", linewidth);
239 margin: linewidth as isize,
240 space: linewidth as isize,
243 // Initialize a single entry; advance_right() will extend it on demand
244 // up to `buf_max_len` elements.
245 buf: vec![BufEntry::default()],
248 scan_stack: VecDeque::new(),
249 print_stack: Vec::new(),
250 pending_indentation: 0,
257 /// Width of lines we're constrained to
259 /// Number of spaces left on line
261 /// Index of left side of input stream
263 /// Index of right side of input stream
265 /// Ring-buffer of tokens and calculated sizes
267 /// Running size of stream "...left"
269 /// Running size of stream "...right"
271 /// Pseudo-stack, really a ring too. Holds the
272 /// primary-ring-buffers index of the Begin that started the
273 /// current block, possibly with the most recent Break after that
274 /// Begin (if there is any) on top of it. Stuff is flushed off the
275 /// bottom as it becomes irrelevant due to the primary ring-buffer
277 scan_stack: VecDeque<usize>,
278 /// Stack of blocks-in-progress being flushed by print
279 print_stack: Vec<PrintStackElem>,
280 /// Buffered indentation to avoid writing trailing whitespace
281 pending_indentation: isize,
290 impl Default for BufEntry {
291 fn default() -> Self {
292 BufEntry { token: Token::Eof, size: 0 }
297 pub fn last_token(&self) -> Token {
298 self.buf[self.right].token.clone()
301 /// Be very careful with this!
302 pub fn replace_last_token(&mut self, t: Token) {
303 self.buf[self.right].token = t;
306 fn scan_eof(&mut self) {
307 if !self.scan_stack.is_empty() {
313 fn scan_begin(&mut self, b: BeginToken) {
314 if self.scan_stack.is_empty() {
316 self.right_total = 1;
320 self.advance_right();
322 debug!("pp Begin({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
323 self.scan_push(BufEntry { token: Token::Begin(b), size: -self.right_total });
326 fn scan_end(&mut self) {
327 if self.scan_stack.is_empty() {
328 debug!("pp End/print Vec<{},{}>", self.left, self.right);
331 debug!("pp End/buffer Vec<{},{}>", self.left, self.right);
332 self.advance_right();
333 self.scan_push(BufEntry { token: Token::End, size: -1 });
337 fn scan_break(&mut self, b: BreakToken) {
338 if self.scan_stack.is_empty() {
340 self.right_total = 1;
344 self.advance_right();
346 debug!("pp Break({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
348 self.scan_push(BufEntry { token: Token::Break(b), size: -self.right_total });
349 self.right_total += b.blank_space;
352 fn scan_string(&mut self, s: Cow<'static, str>) {
353 if self.scan_stack.is_empty() {
354 debug!("pp String('{}')/print Vec<{},{}>", s, self.left, self.right);
355 self.print_string(s);
357 debug!("pp String('{}')/buffer Vec<{},{}>", s, self.left, self.right);
358 self.advance_right();
359 let len = s.len() as isize;
360 self.buf[self.right] = BufEntry { token: Token::String(s), size: len };
361 self.right_total += len;
366 fn check_stream(&mut self) {
368 "check_stream Vec<{}, {}> with left_total={}, right_total={}",
369 self.left, self.right, self.left_total, self.right_total
371 if self.right_total - self.left_total > self.space {
373 "scan window is {}, longer than space on line ({})",
374 self.right_total - self.left_total,
377 if Some(&self.left) == self.scan_stack.back() {
378 debug!("setting {} to infinity and popping", self.left);
379 let scanned = self.scan_pop_bottom();
380 self.buf[scanned].size = SIZE_INFINITY;
383 if self.left != self.right {
389 fn scan_push(&mut self, entry: BufEntry) {
390 debug!("scan_push {}", self.right);
391 self.buf[self.right] = entry;
392 self.scan_stack.push_front(self.right);
395 fn scan_pop(&mut self) -> usize {
396 self.scan_stack.pop_front().unwrap()
399 fn scan_top(&mut self) -> usize {
400 *self.scan_stack.front().unwrap()
403 fn scan_pop_bottom(&mut self) -> usize {
404 self.scan_stack.pop_back().unwrap()
407 fn advance_right(&mut self) {
409 self.right %= self.buf_max_len;
410 // Extend the buf if necessary.
411 if self.right == self.buf.len() {
412 self.buf.push(BufEntry::default());
414 assert_ne!(self.right, self.left);
417 fn advance_left(&mut self) {
419 "advance_left Vec<{},{}>, sizeof({})={}",
420 self.left, self.right, self.left, self.buf[self.left].size
423 let mut left_size = self.buf[self.left].size;
425 while left_size >= 0 {
426 let left = self.buf[self.left].token.clone();
428 let len = match left {
429 Token::Break(b) => b.blank_space,
430 Token::String(ref s) => {
431 let len = s.len() as isize;
432 assert_eq!(len, left_size);
438 self.print(left, left_size);
440 self.left_total += len;
442 if self.left == self.right {
447 self.left %= self.buf_max_len;
449 left_size = self.buf[self.left].size;
453 fn check_stack(&mut self, k: usize) {
454 if !self.scan_stack.is_empty() {
455 let x = self.scan_top();
456 match self.buf[x].token {
460 self.buf[x].size += self.right_total;
461 self.check_stack(k - 1);
465 // paper says + not =, but that makes no sense.
467 self.buf[x].size = 1;
468 self.check_stack(k + 1);
472 self.buf[x].size += self.right_total;
481 fn print_newline(&mut self, amount: isize) {
482 debug!("NEWLINE {}", amount);
484 self.pending_indentation = 0;
488 fn indent(&mut self, amount: isize) {
489 debug!("INDENT {}", amount);
490 self.pending_indentation += amount;
493 fn get_top(&mut self) -> PrintStackElem {
494 match self.print_stack.last() {
497 PrintStackElem { offset: 0, pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) }
502 fn print_begin(&mut self, b: BeginToken, l: isize) {
504 let col = self.margin - self.space + b.offset;
505 debug!("print Begin -> push broken block at col {}", col);
507 .push(PrintStackElem { offset: col, pbreak: PrintStackBreak::Broken(b.breaks) });
509 debug!("print Begin -> push fitting block");
510 self.print_stack.push(PrintStackElem { offset: 0, pbreak: PrintStackBreak::Fits });
514 fn print_end(&mut self) {
515 debug!("print End -> pop End");
516 self.print_stack.pop().unwrap();
519 fn print_break(&mut self, b: BreakToken, l: isize) {
520 let top = self.get_top();
522 PrintStackBreak::Fits => {
523 debug!("print Break({}) in fitting block", b.blank_space);
524 self.space -= b.blank_space;
525 self.indent(b.blank_space);
527 PrintStackBreak::Broken(Breaks::Consistent) => {
528 debug!("print Break({}+{}) in consistent block", top.offset, b.offset);
529 self.print_newline(top.offset + b.offset);
530 self.space = self.margin - (top.offset + b.offset);
532 PrintStackBreak::Broken(Breaks::Inconsistent) => {
534 debug!("print Break({}+{}) w/ newline in inconsistent", top.offset, b.offset);
535 self.print_newline(top.offset + b.offset);
536 self.space = self.margin - (top.offset + b.offset);
538 debug!("print Break({}) w/o newline in inconsistent", b.blank_space);
539 self.indent(b.blank_space);
540 self.space -= b.blank_space;
546 fn print_string(&mut self, s: Cow<'static, str>) {
547 let len = s.len() as isize;
548 debug!("print String({})", s);
549 // assert!(len <= space);
552 // Write the pending indent. A more concise way of doing this would be:
554 // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
556 // But that is significantly slower. This code is sufficiently hot, and indents can get
557 // sufficiently large, that the difference is significant on some workloads.
558 self.out.reserve(self.pending_indentation as usize);
559 self.out.extend(std::iter::repeat(' ').take(self.pending_indentation as usize));
560 self.pending_indentation = 0;
561 self.out.push_str(&s);
564 fn print(&mut self, token: Token, l: isize) {
565 debug!("print {} {} (remaining line space={})", token, l, self.space);
566 debug!("{}", buf_str(&self.buf, self.left, self.right, 6));
568 Token::Begin(b) => self.print_begin(b, l),
569 Token::End => self.print_end(),
570 Token::Break(b) => self.print_break(b, l),
571 Token::String(s) => {
572 let len = s.len() as isize;
574 self.print_string(s);
576 Token::Eof => panic!(), // Eof should never get here.
580 // Convenience functions to talk to the printer.
583 pub fn rbox(&mut self, indent: usize, b: Breaks) {
584 self.scan_begin(BeginToken { offset: indent as isize, breaks: b })
587 /// Inconsistent breaking box
588 pub fn ibox(&mut self, indent: usize) {
589 self.rbox(indent, Breaks::Inconsistent)
592 /// Consistent breaking box
593 pub fn cbox(&mut self, indent: usize) {
594 self.rbox(indent, Breaks::Consistent)
597 pub fn break_offset(&mut self, n: usize, off: isize) {
598 self.scan_break(BreakToken { offset: off, blank_space: n as isize })
601 pub fn end(&mut self) {
605 pub fn eof(mut self) -> String {
610 pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
615 fn spaces(&mut self, n: usize) {
616 self.break_offset(n, 0)
619 crate fn zerobreak(&mut self) {
623 pub fn space(&mut self) {
627 pub fn hardbreak(&mut self) {
628 self.spaces(SIZE_INFINITY as usize)
631 pub fn is_beginning_of_line(&self) -> bool {
632 self.last_token().is_eof() || self.last_token().is_hardbreak_tok()
635 pub fn hardbreak_tok_offset(off: isize) -> Token {
636 Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY })