]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_pretty/src/pp.rs
Merge commit '97a5daa65908e59744e2bc625b14849352231c75' into clippyup
[rust.git] / compiler / rustc_ast_pretty / src / pp.rs
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>.
6 //!
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)".
11 //!
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?
16 //!
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.
21 //!
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).
28 //!
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.
32 //!
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.
51 //!
52 //! # Explanation
53 //!
54 //! In case you do not have the paper, here is an explanation of what's going
55 //! on.
56 //!
57 //! There is a stream of input tokens flowing through this printer.
58 //!
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.
62 //!
63 //! Tokens are String, Break, and Begin/End to delimit blocks.
64 //!
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:
70 //!
71 //! ```
72 //! foo(hello, there, good, friends)
73 //! ```
74 //!
75 //! breaking inconsistently to become
76 //!
77 //! ```
78 //! foo(hello, there,
79 //!     good, friends);
80 //! ```
81 //!
82 //! whereas a consistent breaking would yield:
83 //!
84 //! ```
85 //! foo(hello,
86 //!     there,
87 //!     good,
88 //!     friends);
89 //! ```
90 //!
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.
94 //!
95 //! Carrying on with high-level logic:
96 //!
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.
103 //!
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).
113 //!
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.
117 //!
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).
123 //!
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
129 //! it.
130 //!
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`.
134
135 use std::borrow::Cow;
136 use std::collections::VecDeque;
137 use std::fmt;
138 use tracing::debug;
139
140 /// How to break. Described in more detail in the module docs.
141 #[derive(Clone, Copy, PartialEq)]
142 pub enum Breaks {
143     Consistent,
144     Inconsistent,
145 }
146
147 #[derive(Clone, Copy)]
148 pub struct BreakToken {
149     offset: isize,
150     blank_space: isize,
151 }
152
153 #[derive(Clone, Copy)]
154 pub struct BeginToken {
155     offset: isize,
156     breaks: Breaks,
157 }
158
159 #[derive(Clone)]
160 pub enum Token {
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>),
165     Break(BreakToken),
166     Begin(BeginToken),
167     End,
168     Eof,
169 }
170
171 impl Token {
172     crate fn is_eof(&self) -> bool {
173         matches!(self, Token::Eof)
174     }
175
176     pub fn is_hardbreak_tok(&self) -> bool {
177         matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY }))
178     }
179 }
180
181 impl fmt::Display for Token {
182     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183         match *self {
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"),
189         }
190     }
191 }
192
193 fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String {
194     let n = buf.len();
195     let mut i = left;
196     let mut l = lim;
197     let mut s = String::from("[");
198     while i != right && l != 0 {
199         l -= 1;
200         if i != left {
201             s.push_str(", ");
202         }
203         s.push_str(&format!("{}={}", buf[i].size, &buf[i].token));
204         i += 1;
205         i %= n;
206     }
207     s.push(']');
208     s
209 }
210
211 #[derive(Copy, Clone)]
212 enum PrintStackBreak {
213     Fits,
214     Broken(Breaks),
215 }
216
217 #[derive(Copy, Clone)]
218 struct PrintStackElem {
219     offset: isize,
220     pbreak: PrintStackBreak,
221 }
222
223 const SIZE_INFINITY: isize = 0xffff;
224
225 pub fn mk_printer() -> Printer {
226     let linewidth = 78;
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);
230     Printer {
231         out: String::new(),
232         buf_max_len: n,
233         margin: linewidth as isize,
234         space: linewidth as isize,
235         left: 0,
236         right: 0,
237         // Initialize a single entry; advance_right() will extend it on demand
238         // up to `buf_max_len` elements.
239         buf: vec![BufEntry::default()],
240         left_total: 0,
241         right_total: 0,
242         scan_stack: VecDeque::new(),
243         print_stack: Vec::new(),
244         pending_indentation: 0,
245     }
246 }
247
248 pub struct Printer {
249     out: String,
250     buf_max_len: usize,
251     /// Width of lines we're constrained to
252     margin: isize,
253     /// Number of spaces left on line
254     space: isize,
255     /// Index of left side of input stream
256     left: usize,
257     /// Index of right side of input stream
258     right: usize,
259     /// Ring-buffer of tokens and calculated sizes
260     buf: Vec<BufEntry>,
261     /// Running size of stream "...left"
262     left_total: isize,
263     /// Running size of stream "...right"
264     right_total: isize,
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
270     /// advancing.
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,
276 }
277
278 #[derive(Clone)]
279 struct BufEntry {
280     token: Token,
281     size: isize,
282 }
283
284 impl Default for BufEntry {
285     fn default() -> Self {
286         BufEntry { token: Token::Eof, size: 0 }
287     }
288 }
289
290 impl Printer {
291     pub fn last_token(&self) -> Token {
292         self.buf[self.right].token.clone()
293     }
294
295     /// Be very careful with this!
296     pub fn replace_last_token(&mut self, t: Token) {
297         self.buf[self.right].token = t;
298     }
299
300     fn scan_eof(&mut self) {
301         if !self.scan_stack.is_empty() {
302             self.check_stack(0);
303             self.advance_left();
304         }
305     }
306
307     fn scan_begin(&mut self, b: BeginToken) {
308         if self.scan_stack.is_empty() {
309             self.left_total = 1;
310             self.right_total = 1;
311             self.left = 0;
312             self.right = 0;
313         } else {
314             self.advance_right();
315         }
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 });
318     }
319
320     fn scan_end(&mut self) {
321         if self.scan_stack.is_empty() {
322             debug!("pp End/print Vec<{},{}>", self.left, self.right);
323             self.print_end();
324         } else {
325             debug!("pp End/buffer Vec<{},{}>", self.left, self.right);
326             self.advance_right();
327             self.scan_push(BufEntry { token: Token::End, size: -1 });
328         }
329     }
330
331     fn scan_break(&mut self, b: BreakToken) {
332         if self.scan_stack.is_empty() {
333             self.left_total = 1;
334             self.right_total = 1;
335             self.left = 0;
336             self.right = 0;
337         } else {
338             self.advance_right();
339         }
340         debug!("pp Break({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
341         self.check_stack(0);
342         self.scan_push(BufEntry { token: Token::Break(b), size: -self.right_total });
343         self.right_total += b.blank_space;
344     }
345
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);
350         } else {
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;
356             self.check_stream();
357         }
358     }
359
360     fn check_stream(&mut self) {
361         debug!(
362             "check_stream Vec<{}, {}> with left_total={}, right_total={}",
363             self.left, self.right, self.left_total, self.right_total
364         );
365         if self.right_total - self.left_total > self.space {
366             debug!(
367                 "scan window is {}, longer than space on line ({})",
368                 self.right_total - self.left_total,
369                 self.space
370             );
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;
375             }
376             self.advance_left();
377             if self.left != self.right {
378                 self.check_stream();
379             }
380         }
381     }
382
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);
387     }
388
389     fn scan_pop(&mut self) -> usize {
390         self.scan_stack.pop_front().unwrap()
391     }
392
393     fn scan_top(&self) -> usize {
394         *self.scan_stack.front().unwrap()
395     }
396
397     fn scan_pop_bottom(&mut self) -> usize {
398         self.scan_stack.pop_back().unwrap()
399     }
400
401     fn advance_right(&mut self) {
402         self.right += 1;
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());
407         }
408         assert_ne!(self.right, self.left);
409     }
410
411     fn advance_left(&mut self) {
412         debug!(
413             "advance_left Vec<{},{}>, sizeof({})={}",
414             self.left, self.right, self.left, self.buf[self.left].size
415         );
416
417         let mut left_size = self.buf[self.left].size;
418
419         while left_size >= 0 {
420             let left = self.buf[self.left].token.clone();
421
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);
427                     len
428                 }
429                 _ => 0,
430             };
431
432             self.print(left, left_size);
433
434             self.left_total += len;
435
436             if self.left == self.right {
437                 break;
438             }
439
440             self.left += 1;
441             self.left %= self.buf_max_len;
442
443             left_size = self.buf[self.left].size;
444         }
445     }
446
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 {
451                 Token::Begin(_) => {
452                     if k > 0 {
453                         self.scan_pop();
454                         self.buf[x].size += self.right_total;
455                         self.check_stack(k - 1);
456                     }
457                 }
458                 Token::End => {
459                     // paper says + not =, but that makes no sense.
460                     self.scan_pop();
461                     self.buf[x].size = 1;
462                     self.check_stack(k + 1);
463                 }
464                 _ => {
465                     self.scan_pop();
466                     self.buf[x].size += self.right_total;
467                     if k > 0 {
468                         self.check_stack(k);
469                     }
470                 }
471             }
472         }
473     }
474
475     fn print_newline(&mut self, amount: isize) {
476         debug!("NEWLINE {}", amount);
477         self.out.push('\n');
478         self.pending_indentation = 0;
479         self.indent(amount);
480     }
481
482     fn indent(&mut self, amount: isize) {
483         debug!("INDENT {}", amount);
484         self.pending_indentation += amount;
485     }
486
487     fn get_top(&self) -> PrintStackElem {
488         *self.print_stack.last().unwrap_or({
489             &PrintStackElem { offset: 0, pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) }
490         })
491     }
492
493     fn print_begin(&mut self, b: BeginToken, l: isize) {
494         if l > self.space {
495             let col = self.margin - self.space + b.offset;
496             debug!("print Begin -> push broken block at col {}", col);
497             self.print_stack
498                 .push(PrintStackElem { offset: col, pbreak: PrintStackBreak::Broken(b.breaks) });
499         } else {
500             debug!("print Begin -> push fitting block");
501             self.print_stack.push(PrintStackElem { offset: 0, pbreak: PrintStackBreak::Fits });
502         }
503     }
504
505     fn print_end(&mut self) {
506         debug!("print End -> pop End");
507         self.print_stack.pop().unwrap();
508     }
509
510     fn print_break(&mut self, b: BreakToken, l: isize) {
511         let top = self.get_top();
512         match top.pbreak {
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);
517             }
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);
522             }
523             PrintStackBreak::Broken(Breaks::Inconsistent) => {
524                 if l > self.space {
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);
528                 } else {
529                     debug!("print Break({}) w/o newline in inconsistent", b.blank_space);
530                     self.indent(b.blank_space);
531                     self.space -= b.blank_space;
532                 }
533             }
534         }
535     }
536
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);
541         self.space -= len;
542
543         // Write the pending indent. A more concise way of doing this would be:
544         //
545         //   write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
546         //
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);
553     }
554
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));
558         match token {
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;
564                 assert_eq!(len, l);
565                 self.print_string(s);
566             }
567             Token::Eof => panic!(), // Eof should never get here.
568         }
569     }
570
571     // Convenience functions to talk to the printer.
572
573     /// "raw box"
574     pub fn rbox(&mut self, indent: usize, b: Breaks) {
575         self.scan_begin(BeginToken { offset: indent as isize, breaks: b })
576     }
577
578     /// Inconsistent breaking box
579     pub fn ibox(&mut self, indent: usize) {
580         self.rbox(indent, Breaks::Inconsistent)
581     }
582
583     /// Consistent breaking box
584     pub fn cbox(&mut self, indent: usize) {
585         self.rbox(indent, Breaks::Consistent)
586     }
587
588     pub fn break_offset(&mut self, n: usize, off: isize) {
589         self.scan_break(BreakToken { offset: off, blank_space: n as isize })
590     }
591
592     pub fn end(&mut self) {
593         self.scan_end()
594     }
595
596     pub fn eof(mut self) -> String {
597         self.scan_eof();
598         self.out
599     }
600
601     pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
602         let s = wrd.into();
603         self.scan_string(s)
604     }
605
606     fn spaces(&mut self, n: usize) {
607         self.break_offset(n, 0)
608     }
609
610     crate fn zerobreak(&mut self) {
611         self.spaces(0)
612     }
613
614     pub fn space(&mut self) {
615         self.spaces(1)
616     }
617
618     pub fn hardbreak(&mut self) {
619         self.spaces(SIZE_INFINITY as usize)
620     }
621
622     pub fn is_beginning_of_line(&self) -> bool {
623         self.last_token().is_eof() || self.last_token().is_hardbreak_tok()
624     }
625
626     pub fn hardbreak_tok_offset(off: isize) -> Token {
627         Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY })
628     }
629 }