]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pp.rs
d8a8cbb655b4b548720afa23594b5cef95783bc4
[rust.git] / src / libsyntax / print / pp.rs
1 //! This pretty-printer is a direct reimplementation of Philip Karlton's
2 //! Mesa pretty-printer, as described in appendix A of
3 //!
4 //! ```text
5 //! STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen.
6 //! Stanford Department of Computer Science, 1979.
7 //! ```
8 //!
9 //! The algorithm's aim is to break a stream into as few lines as possible
10 //! while respecting the indentation-consistency requirements of the enclosing
11 //! block, and avoiding breaking at silly places on block boundaries, for
12 //! example, between "x" and ")" in "x)".
13 //!
14 //! I am implementing this algorithm because it comes with 20 pages of
15 //! documentation explaining its theory, and because it addresses the set of
16 //! concerns I've seen other pretty-printers fall down on. Weirdly. Even though
17 //! it's 32 years old. What can I say?
18 //!
19 //! Despite some redundancies and quirks in the way it's implemented in that
20 //! paper, I've opted to keep the implementation here as similar as I can,
21 //! changing only what was blatantly wrong, a typo, or sufficiently
22 //! non-idiomatic rust that it really stuck out.
23 //!
24 //! In particular you'll see a certain amount of churn related to INTEGER vs.
25 //! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two
26 //! somewhat readily? In any case, I've used usize for indices-in-buffers and
27 //! ints for character-sizes-and-indentation-offsets. This respects the need
28 //! for ints to "go negative" while carrying a pending-calculation balance, and
29 //! helps differentiate all the numbers flying around internally (slightly).
30 //!
31 //! I also inverted the indentation arithmetic used in the print stack, since
32 //! the Mesa implementation (somewhat randomly) stores the offset on the print
33 //! stack in terms of margin-col rather than col itself. I store col.
34 //!
35 //! I also implemented a small change in the String token, in that I store an
36 //! explicit length for the string. For most tokens this is just the length of
37 //! the accompanying string. But it's necessary to permit it to differ, for
38 //! encoding things that are supposed to "go on their own line" -- certain
39 //! classes of comment and blank-line -- where relying on adjacent
40 //! hardbreak-like Break tokens with long blankness indication doesn't actually
41 //! work. To see why, consider when there is a "thing that should be on its own
42 //! line" between two long blocks, say functions. If you put a hardbreak after
43 //! each function (or before each) and the breaking algorithm decides to break
44 //! there anyways (because the functions themselves are long) you wind up with
45 //! extra blank lines. If you don't put hardbreaks you can wind up with the
46 //! "thing which should be on its own line" not getting its own line in the
47 //! rare case of "really small functions" or such. This re-occurs with comments
48 //! and explicit blank lines. So in those cases we use a string with a payload
49 //! we want isolated to a line and an explicit length that's huge, surrounded
50 //! by two zero-length breaks. The algorithm will try its best to fit it on a
51 //! line (which it can't) and so naturally place the content on its own line to
52 //! avoid combining it with other lines and making matters even worse.
53 //!
54 //! # Explanation
55 //!
56 //! In case you do not have the paper, here is an explanation of what's going
57 //! on.
58 //!
59 //! There is a stream of input tokens flowing through this printer.
60 //!
61 //! The printer buffers up to 3N tokens inside itself, where N is linewidth.
62 //! Yes, linewidth is chars and tokens are multi-char, but in the worst
63 //! case every token worth buffering is 1 char long, so it's ok.
64 //!
65 //! Tokens are String, Break, and Begin/End to delimit blocks.
66 //!
67 //! Begin tokens can carry an offset, saying "how far to indent when you break
68 //! inside here", as well as a flag indicating "consistent" or "inconsistent"
69 //! breaking. Consistent breaking means that after the first break, no attempt
70 //! will be made to flow subsequent breaks together onto lines. Inconsistent
71 //! is the opposite. Inconsistent breaking example would be, say:
72 //!
73 //! ```
74 //! foo(hello, there, good, friends)
75 //! ```
76 //!
77 //! breaking inconsistently to become
78 //!
79 //! ```
80 //! foo(hello, there
81 //!     good, friends);
82 //! ```
83 //!
84 //! whereas a consistent breaking would yield:
85 //!
86 //! ```
87 //! foo(hello,
88 //!     there
89 //!     good,
90 //!     friends);
91 //! ```
92 //!
93 //! That is, in the consistent-break blocks we value vertical alignment
94 //! more than the ability to cram stuff onto a line. But in all cases if it
95 //! can make a block a one-liner, it'll do so.
96 //!
97 //! Carrying on with high-level logic:
98 //!
99 //! The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and
100 //! 'right' indices denote the active portion of the ring buffer as well as
101 //! describing hypothetical points-in-the-infinite-stream at most 3N tokens
102 //! apart (i.e., "not wrapped to ring-buffer boundaries"). The paper will switch
103 //! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer
104 //! and point-in-infinite-stream senses freely.
105 //!
106 //! There is a parallel ring buffer, `size`, that holds the calculated size of
107 //! each token. Why calculated? Because for Begin/End pairs, the "size"
108 //! includes everything between the pair. That is, the "size" of Begin is
109 //! actually the sum of the sizes of everything between Begin and the paired
110 //! End that follows. Since that is arbitrarily far in the future, `size` is
111 //! being rewritten regularly while the printer runs; in fact most of the
112 //! machinery is here to work out `size` entries on the fly (and give up when
113 //! they're so obviously over-long that "infinity" is a good enough
114 //! approximation for purposes of line breaking).
115 //!
116 //! The "input side" of the printer is managed as an abstract process called
117 //! SCAN, which uses `scan_stack`, to manage calculating `size`. SCAN is, in
118 //! other words, the process of calculating 'size' entries.
119 //!
120 //! The "output side" of the printer is managed by an abstract process called
121 //! PRINT, which uses `print_stack`, `margin` and `space` to figure out what to
122 //! do with each token/size pair it consumes as it goes. It's trying to consume
123 //! the entire buffered window, but can't output anything until the size is >=
124 //! 0 (sizes are set to negative while they're pending calculation).
125 //!
126 //! So SCAN takes input and buffers tokens and pending calculations, while
127 //! PRINT gobbles up completed calculations and tokens from the buffer. The
128 //! theory is that the two can never get more than 3N tokens apart, because
129 //! once there's "obviously" too much data to fit on a line, in a size
130 //! calculation, SCAN will write "infinity" to the size and let PRINT consume
131 //! it.
132 //!
133 //! In this implementation (following the paper, again) the SCAN process is the
134 //! methods called `Printer::pretty_print_*`, and the 'PRINT' process is the
135 //! method called `Printer::print`.
136
137 use std::collections::VecDeque;
138 use std::fmt;
139 use std::io;
140 use std::borrow::Cow;
141 use log::debug;
142
143 /// How to break. Described in more detail in the module docs.
144 #[derive(Clone, Copy, PartialEq)]
145 pub enum Breaks {
146     Consistent,
147     Inconsistent,
148 }
149
150 #[derive(Clone, Copy)]
151 pub struct BreakToken {
152     offset: isize,
153     blank_space: isize
154 }
155
156 #[derive(Clone, Copy)]
157 pub struct BeginToken {
158     offset: isize,
159     breaks: Breaks
160 }
161
162 #[derive(Clone)]
163 pub enum Token {
164     // In practice a string token contains either a `&'static str` or a
165     // `String`. `Cow` is overkill for this because we never modify the data,
166     // but it's more convenient than rolling our own more specialized type.
167     String(Cow<'static, str>, isize),
168     Break(BreakToken),
169     Begin(BeginToken),
170     End,
171     Eof,
172 }
173
174 impl Token {
175     pub fn is_eof(&self) -> bool {
176         match *self {
177             Token::Eof => true,
178             _ => false,
179         }
180     }
181
182     pub fn is_hardbreak_tok(&self) -> bool {
183         match *self {
184             Token::Break(BreakToken {
185                 offset: 0,
186                 blank_space: bs
187             }) if bs == SIZE_INFINITY =>
188                 true,
189             _ =>
190                 false
191         }
192     }
193 }
194
195 impl fmt::Display for Token {
196     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197         match *self {
198             Token::String(ref s, len) => write!(f, "STR({},{})", s, len),
199             Token::Break(_) => f.write_str("BREAK"),
200             Token::Begin(_) => f.write_str("BEGIN"),
201             Token::End => f.write_str("END"),
202             Token::Eof => f.write_str("EOF"),
203         }
204     }
205 }
206
207 fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String {
208     let n = buf.len();
209     let mut i = left;
210     let mut l = lim;
211     let mut s = String::from("[");
212     while i != right && l != 0 {
213         l -= 1;
214         if i != left {
215             s.push_str(", ");
216         }
217         s.push_str(&format!("{}={}", buf[i].size, &buf[i].token));
218         i += 1;
219         i %= n;
220     }
221     s.push(']');
222     s
223 }
224
225 #[derive(Copy, Clone)]
226 pub enum PrintStackBreak {
227     Fits,
228     Broken(Breaks),
229 }
230
231 #[derive(Copy, Clone)]
232 pub struct PrintStackElem {
233     offset: isize,
234     pbreak: PrintStackBreak
235 }
236
237 const SIZE_INFINITY: isize = 0xffff;
238
239 pub fn mk_printer<'a>(out: Box<dyn io::Write+'a>, linewidth: usize) -> Printer<'a> {
240     // Yes 55, it makes the ring buffers big enough to never fall behind.
241     let n: usize = 55 * linewidth;
242     debug!("mk_printer {}", linewidth);
243     Printer {
244         out,
245         buf_max_len: n,
246         margin: linewidth as isize,
247         space: linewidth as isize,
248         left: 0,
249         right: 0,
250         // Initialize a single entry; advance_right() will extend it on demand
251         // up to `buf_max_len` elements.
252         buf: vec![BufEntry::default()],
253         left_total: 0,
254         right_total: 0,
255         scan_stack: VecDeque::new(),
256         print_stack: Vec::new(),
257         pending_indentation: 0
258     }
259 }
260
261 pub struct Printer<'a> {
262     out: Box<dyn io::Write+'a>,
263     buf_max_len: usize,
264     /// Width of lines we're constrained to
265     margin: isize,
266     /// Number of spaces left on line
267     space: isize,
268     /// Index of left side of input stream
269     left: usize,
270     /// Index of right side of input stream
271     right: usize,
272     /// Ring-buffer of tokens and calculated sizes
273     buf: Vec<BufEntry>,
274     /// Running size of stream "...left"
275     left_total: isize,
276     /// Running size of stream "...right"
277     right_total: isize,
278     /// Pseudo-stack, really a ring too. Holds the
279     /// primary-ring-buffers index of the Begin that started the
280     /// current block, possibly with the most recent Break after that
281     /// Begin (if there is any) on top of it. Stuff is flushed off the
282     /// bottom as it becomes irrelevant due to the primary ring-buffer
283     /// advancing.
284     scan_stack: VecDeque<usize>,
285     /// Stack of blocks-in-progress being flushed by print
286     print_stack: Vec<PrintStackElem> ,
287     /// Buffered indentation to avoid writing trailing whitespace
288     pending_indentation: isize,
289 }
290
291 #[derive(Clone)]
292 struct BufEntry {
293     token: Token,
294     size: isize,
295 }
296
297 impl Default for BufEntry {
298     fn default() -> Self {
299         BufEntry { token: Token::Eof, size: 0 }
300     }
301 }
302
303 impl<'a> Printer<'a> {
304     pub fn last_token(&mut self) -> Token {
305         self.buf[self.right].token.clone()
306     }
307
308     /// Be very careful with this!
309     pub fn replace_last_token(&mut self, t: Token) {
310         self.buf[self.right].token = t;
311     }
312
313     fn pretty_print_eof(&mut self) -> io::Result<()> {
314         if !self.scan_stack.is_empty() {
315             self.check_stack(0);
316             self.advance_left()?;
317         }
318         self.indent(0);
319         Ok(())
320     }
321
322     fn pretty_print_begin(&mut self, b: BeginToken) -> io::Result<()> {
323         if self.scan_stack.is_empty() {
324             self.left_total = 1;
325             self.right_total = 1;
326             self.left = 0;
327             self.right = 0;
328         } else {
329             self.advance_right();
330         }
331         debug!("pp Begin({})/buffer Vec<{},{}>",
332                b.offset, self.left, self.right);
333         self.buf[self.right] = BufEntry { token: Token::Begin(b), size: -self.right_total };
334         let right = self.right;
335         self.scan_push(right);
336         Ok(())
337     }
338
339     fn pretty_print_end(&mut self) -> io::Result<()> {
340         if self.scan_stack.is_empty() {
341             debug!("pp End/print Vec<{},{}>", self.left, self.right);
342             self.print_end()
343         } else {
344             debug!("pp End/buffer Vec<{},{}>", self.left, self.right);
345             self.advance_right();
346             self.buf[self.right] = BufEntry { token: Token::End, size: -1 };
347             let right = self.right;
348             self.scan_push(right);
349             Ok(())
350         }
351     }
352
353     fn pretty_print_break(&mut self, b: BreakToken) -> io::Result<()> {
354         if self.scan_stack.is_empty() {
355             self.left_total = 1;
356             self.right_total = 1;
357             self.left = 0;
358             self.right = 0;
359         } else {
360             self.advance_right();
361         }
362         debug!("pp Break({})/buffer Vec<{},{}>",
363                b.offset, self.left, self.right);
364         self.check_stack(0);
365         let right = self.right;
366         self.scan_push(right);
367         self.buf[self.right] = BufEntry { token: Token::Break(b), size: -self.right_total };
368         self.right_total += b.blank_space;
369         Ok(())
370     }
371
372     fn pretty_print_string(&mut self, s: Cow<'static, str>, len: isize) -> io::Result<()> {
373         if self.scan_stack.is_empty() {
374             debug!("pp String('{}')/print Vec<{},{}>",
375                    s, self.left, self.right);
376             self.print_string(s, len)
377         } else {
378             debug!("pp String('{}')/buffer Vec<{},{}>",
379                    s, self.left, self.right);
380             self.advance_right();
381             self.buf[self.right] = BufEntry { token: Token::String(s, len), size: len };
382             self.right_total += len;
383             self.check_stream()
384         }
385     }
386
387     pub fn check_stream(&mut self) -> io::Result<()> {
388         debug!("check_stream Vec<{}, {}> with left_total={}, right_total={}",
389                self.left, self.right, self.left_total, self.right_total);
390         if self.right_total - self.left_total > self.space {
391             debug!("scan window is {}, longer than space on line ({})",
392                    self.right_total - self.left_total, self.space);
393             if Some(&self.left) == self.scan_stack.back() {
394                 debug!("setting {} to infinity and popping", self.left);
395                 let scanned = self.scan_pop_bottom();
396                 self.buf[scanned].size = SIZE_INFINITY;
397             }
398             self.advance_left()?;
399             if self.left != self.right {
400                 self.check_stream()?;
401             }
402         }
403         Ok(())
404     }
405
406     pub fn scan_push(&mut self, x: usize) {
407         debug!("scan_push {}", x);
408         self.scan_stack.push_front(x);
409     }
410
411     pub fn scan_pop(&mut self) -> usize {
412         self.scan_stack.pop_front().unwrap()
413     }
414
415     pub fn scan_top(&mut self) -> usize {
416         *self.scan_stack.front().unwrap()
417     }
418
419     pub fn scan_pop_bottom(&mut self) -> usize {
420         self.scan_stack.pop_back().unwrap()
421     }
422
423     pub fn advance_right(&mut self) {
424         self.right += 1;
425         self.right %= self.buf_max_len;
426         // Extend the buf if necessary.
427         if self.right == self.buf.len() {
428             self.buf.push(BufEntry::default());
429         }
430         assert_ne!(self.right, self.left);
431     }
432
433     pub fn advance_left(&mut self) -> io::Result<()> {
434         debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right,
435                self.left, self.buf[self.left].size);
436
437         let mut left_size = self.buf[self.left].size;
438
439         while left_size >= 0 {
440             let left = self.buf[self.left].token.clone();
441
442             let len = match left {
443                 Token::Break(b) => b.blank_space,
444                 Token::String(_, len) => {
445                     assert_eq!(len, left_size);
446                     len
447                 }
448                 _ => 0
449             };
450
451             self.print(left, left_size)?;
452
453             self.left_total += len;
454
455             if self.left == self.right {
456                 break;
457             }
458
459             self.left += 1;
460             self.left %= self.buf_max_len;
461
462             left_size = self.buf[self.left].size;
463         }
464
465         Ok(())
466     }
467
468     pub fn check_stack(&mut self, k: isize) {
469         if !self.scan_stack.is_empty() {
470             let x = self.scan_top();
471             match self.buf[x].token {
472                 Token::Begin(_) => {
473                     if k > 0 {
474                         let popped = self.scan_pop();
475                         self.buf[popped].size = self.buf[x].size + self.right_total;
476                         self.check_stack(k - 1);
477                     }
478                 }
479                 Token::End => {
480                     // paper says + not =, but that makes no sense.
481                     let popped = self.scan_pop();
482                     self.buf[popped].size = 1;
483                     self.check_stack(k + 1);
484                 }
485                 _ => {
486                     let popped = self.scan_pop();
487                     self.buf[popped].size = self.buf[x].size + self.right_total;
488                     if k > 0 {
489                         self.check_stack(k);
490                     }
491                 }
492             }
493         }
494     }
495
496     pub fn print_newline(&mut self, amount: isize) -> io::Result<()> {
497         debug!("NEWLINE {}", amount);
498         let ret = write!(self.out, "\n");
499         self.pending_indentation = 0;
500         self.indent(amount);
501         ret
502     }
503
504     pub fn indent(&mut self, amount: isize) {
505         debug!("INDENT {}", amount);
506         self.pending_indentation += amount;
507     }
508
509     pub fn get_top(&mut self) -> PrintStackElem {
510         match self.print_stack.last() {
511             Some(el) => *el,
512             None => PrintStackElem {
513                 offset: 0,
514                 pbreak: PrintStackBreak::Broken(Breaks::Inconsistent)
515             }
516         }
517     }
518
519     pub fn print_begin(&mut self, b: BeginToken, l: isize) -> io::Result<()> {
520         if l > self.space {
521             let col = self.margin - self.space + b.offset;
522             debug!("print Begin -> push broken block at col {}", col);
523             self.print_stack.push(PrintStackElem {
524                 offset: col,
525                 pbreak: PrintStackBreak::Broken(b.breaks)
526             });
527         } else {
528             debug!("print Begin -> push fitting block");
529             self.print_stack.push(PrintStackElem {
530                 offset: 0,
531                 pbreak: PrintStackBreak::Fits
532             });
533         }
534         Ok(())
535     }
536
537     pub fn print_end(&mut self) -> io::Result<()> {
538         debug!("print End -> pop End");
539         let print_stack = &mut self.print_stack;
540         assert!(!print_stack.is_empty());
541         print_stack.pop().unwrap();
542         Ok(())
543     }
544
545     pub fn print_break(&mut self, b: BreakToken, l: isize) -> io::Result<()> {
546         let top = self.get_top();
547         match top.pbreak {
548             PrintStackBreak::Fits => {
549                 debug!("print Break({}) in fitting block", b.blank_space);
550                 self.space -= b.blank_space;
551                 self.indent(b.blank_space);
552                 Ok(())
553             }
554             PrintStackBreak::Broken(Breaks::Consistent) => {
555                 debug!("print Break({}+{}) in consistent block",
556                        top.offset, b.offset);
557                 let ret = self.print_newline(top.offset + b.offset);
558                 self.space = self.margin - (top.offset + b.offset);
559                 ret
560             }
561             PrintStackBreak::Broken(Breaks::Inconsistent) => {
562                 if l > self.space {
563                     debug!("print Break({}+{}) w/ newline in inconsistent",
564                            top.offset, b.offset);
565                     let ret = self.print_newline(top.offset + b.offset);
566                     self.space = self.margin - (top.offset + b.offset);
567                     ret
568                 } else {
569                     debug!("print Break({}) w/o newline in inconsistent",
570                            b.blank_space);
571                     self.indent(b.blank_space);
572                     self.space -= b.blank_space;
573                     Ok(())
574                 }
575             }
576         }
577     }
578
579     pub fn print_string(&mut self, s: Cow<'static, str>, len: isize) -> io::Result<()> {
580         debug!("print String({})", s);
581         // assert!(len <= space);
582         self.space -= len;
583         while self.pending_indentation > 0 {
584             write!(self.out, " ")?;
585             self.pending_indentation -= 1;
586         }
587         write!(self.out, "{}", s)
588     }
589
590     pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> {
591         debug!("print {} {} (remaining line space={})", token, l,
592                self.space);
593         debug!("{}", buf_str(&self.buf,
594                              self.left,
595                              self.right,
596                              6));
597         match token {
598             Token::Begin(b) => self.print_begin(b, l),
599             Token::End => self.print_end(),
600             Token::Break(b) => self.print_break(b, l),
601             Token::String(s, len) => {
602                 assert_eq!(len, l);
603                 self.print_string(s, len)
604             }
605             Token::Eof => panic!(), // Eof should never get here.
606         }
607     }
608
609     // Convenience functions to talk to the printer.
610
611     /// "raw box"
612     pub fn rbox(&mut self, indent: usize, b: Breaks) -> io::Result<()> {
613         self.pretty_print_begin(BeginToken {
614             offset: indent as isize,
615             breaks: b
616         })
617     }
618
619     /// Inconsistent breaking box
620     pub fn ibox(&mut self, indent: usize) -> io::Result<()> {
621         self.rbox(indent, Breaks::Inconsistent)
622     }
623
624     /// Consistent breaking box
625     pub fn cbox(&mut self, indent: usize) -> io::Result<()> {
626         self.rbox(indent, Breaks::Consistent)
627     }
628
629     pub fn break_offset(&mut self, n: usize, off: isize) -> io::Result<()> {
630         self.pretty_print_break(BreakToken {
631             offset: off,
632             blank_space: n as isize
633         })
634     }
635
636     pub fn end(&mut self) -> io::Result<()> {
637         self.pretty_print_end()
638     }
639
640     pub fn eof(&mut self) -> io::Result<()> {
641         self.pretty_print_eof()
642     }
643
644     pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) -> io::Result<()> {
645         let s = wrd.into();
646         let len = s.len() as isize;
647         self.pretty_print_string(s, len)
648     }
649
650     fn spaces(&mut self, n: usize) -> io::Result<()> {
651         self.break_offset(n, 0)
652     }
653
654     pub fn zerobreak(&mut self) -> io::Result<()> {
655         self.spaces(0)
656     }
657
658     pub fn space(&mut self) -> io::Result<()> {
659         self.spaces(1)
660     }
661
662     pub fn hardbreak(&mut self) -> io::Result<()> {
663         self.spaces(SIZE_INFINITY as usize)
664     }
665
666     pub fn hardbreak_tok_offset(off: isize) -> Token {
667         Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY})
668     }
669
670     pub fn hardbreak_tok() -> Token {
671         Self::hardbreak_tok_offset(0)
672     }
673 }