]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_pretty/pp.rs
Auto merge of #69257 - RalfJung:layout-visitor, r=eddyb
[rust.git] / src / librustc_ast_pretty / 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::scan_*`, and the 'PRINT' process is the
135 //! method called `Printer::print`.
136
137 use log::debug;
138 use std::borrow::Cow;
139 use std::collections::VecDeque;
140 use std::fmt;
141
142 /// How to break. Described in more detail in the module docs.
143 #[derive(Clone, Copy, PartialEq)]
144 pub enum Breaks {
145     Consistent,
146     Inconsistent,
147 }
148
149 #[derive(Clone, Copy)]
150 pub struct BreakToken {
151     offset: isize,
152     blank_space: isize,
153 }
154
155 #[derive(Clone, Copy)]
156 pub struct BeginToken {
157     offset: isize,
158     breaks: Breaks,
159 }
160
161 #[derive(Clone)]
162 pub enum Token {
163     // In practice a string token contains either a `&'static str` or a
164     // `String`. `Cow` is overkill for this because we never modify the data,
165     // but it's more convenient than rolling our own more specialized type.
166     String(Cow<'static, str>),
167     Break(BreakToken),
168     Begin(BeginToken),
169     End,
170     Eof,
171 }
172
173 impl Token {
174     crate fn is_eof(&self) -> bool {
175         match *self {
176             Token::Eof => true,
177             _ => false,
178         }
179     }
180
181     pub fn is_hardbreak_tok(&self) -> bool {
182         match *self {
183             Token::Break(BreakToken { offset: 0, blank_space: bs }) if bs == SIZE_INFINITY => true,
184             _ => false,
185         }
186     }
187 }
188
189 impl fmt::Display for Token {
190     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191         match *self {
192             Token::String(ref s) => write!(f, "STR({},{})", s, s.len()),
193             Token::Break(_) => f.write_str("BREAK"),
194             Token::Begin(_) => f.write_str("BEGIN"),
195             Token::End => f.write_str("END"),
196             Token::Eof => f.write_str("EOF"),
197         }
198     }
199 }
200
201 fn buf_str(buf: &[BufEntry], left: usize, right: usize, lim: usize) -> String {
202     let n = buf.len();
203     let mut i = left;
204     let mut l = lim;
205     let mut s = String::from("[");
206     while i != right && l != 0 {
207         l -= 1;
208         if i != left {
209             s.push_str(", ");
210         }
211         s.push_str(&format!("{}={}", buf[i].size, &buf[i].token));
212         i += 1;
213         i %= n;
214     }
215     s.push(']');
216     s
217 }
218
219 #[derive(Copy, Clone)]
220 enum PrintStackBreak {
221     Fits,
222     Broken(Breaks),
223 }
224
225 #[derive(Copy, Clone)]
226 struct PrintStackElem {
227     offset: isize,
228     pbreak: PrintStackBreak,
229 }
230
231 const SIZE_INFINITY: isize = 0xffff;
232
233 pub fn mk_printer() -> Printer {
234     let linewidth = 78;
235     // Yes 55, it makes the ring buffers big enough to never fall behind.
236     let n: usize = 55 * linewidth;
237     debug!("mk_printer {}", linewidth);
238     Printer {
239         out: String::new(),
240         buf_max_len: n,
241         margin: linewidth as isize,
242         space: linewidth as isize,
243         left: 0,
244         right: 0,
245         // Initialize a single entry; advance_right() will extend it on demand
246         // up to `buf_max_len` elements.
247         buf: vec![BufEntry::default()],
248         left_total: 0,
249         right_total: 0,
250         scan_stack: VecDeque::new(),
251         print_stack: Vec::new(),
252         pending_indentation: 0,
253     }
254 }
255
256 pub struct Printer {
257     out: String,
258     buf_max_len: usize,
259     /// Width of lines we're constrained to
260     margin: isize,
261     /// Number of spaces left on line
262     space: isize,
263     /// Index of left side of input stream
264     left: usize,
265     /// Index of right side of input stream
266     right: usize,
267     /// Ring-buffer of tokens and calculated sizes
268     buf: Vec<BufEntry>,
269     /// Running size of stream "...left"
270     left_total: isize,
271     /// Running size of stream "...right"
272     right_total: isize,
273     /// Pseudo-stack, really a ring too. Holds the
274     /// primary-ring-buffers index of the Begin that started the
275     /// current block, possibly with the most recent Break after that
276     /// Begin (if there is any) on top of it. Stuff is flushed off the
277     /// bottom as it becomes irrelevant due to the primary ring-buffer
278     /// advancing.
279     scan_stack: VecDeque<usize>,
280     /// Stack of blocks-in-progress being flushed by print
281     print_stack: Vec<PrintStackElem>,
282     /// Buffered indentation to avoid writing trailing whitespace
283     pending_indentation: isize,
284 }
285
286 #[derive(Clone)]
287 struct BufEntry {
288     token: Token,
289     size: isize,
290 }
291
292 impl Default for BufEntry {
293     fn default() -> Self {
294         BufEntry { token: Token::Eof, size: 0 }
295     }
296 }
297
298 impl Printer {
299     pub fn last_token(&self) -> Token {
300         self.buf[self.right].token.clone()
301     }
302
303     /// Be very careful with this!
304     pub fn replace_last_token(&mut self, t: Token) {
305         self.buf[self.right].token = t;
306     }
307
308     fn scan_eof(&mut self) {
309         if !self.scan_stack.is_empty() {
310             self.check_stack(0);
311             self.advance_left();
312         }
313     }
314
315     fn scan_begin(&mut self, b: BeginToken) {
316         if self.scan_stack.is_empty() {
317             self.left_total = 1;
318             self.right_total = 1;
319             self.left = 0;
320             self.right = 0;
321         } else {
322             self.advance_right();
323         }
324         debug!("pp Begin({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
325         self.scan_push(BufEntry { token: Token::Begin(b), size: -self.right_total });
326     }
327
328     fn scan_end(&mut self) {
329         if self.scan_stack.is_empty() {
330             debug!("pp End/print Vec<{},{}>", self.left, self.right);
331             self.print_end();
332         } else {
333             debug!("pp End/buffer Vec<{},{}>", self.left, self.right);
334             self.advance_right();
335             self.scan_push(BufEntry { token: Token::End, size: -1 });
336         }
337     }
338
339     fn scan_break(&mut self, b: BreakToken) {
340         if self.scan_stack.is_empty() {
341             self.left_total = 1;
342             self.right_total = 1;
343             self.left = 0;
344             self.right = 0;
345         } else {
346             self.advance_right();
347         }
348         debug!("pp Break({})/buffer Vec<{},{}>", b.offset, self.left, self.right);
349         self.check_stack(0);
350         self.scan_push(BufEntry { token: Token::Break(b), size: -self.right_total });
351         self.right_total += b.blank_space;
352     }
353
354     fn scan_string(&mut self, s: Cow<'static, str>) {
355         if self.scan_stack.is_empty() {
356             debug!("pp String('{}')/print Vec<{},{}>", s, self.left, self.right);
357             self.print_string(s);
358         } else {
359             debug!("pp String('{}')/buffer Vec<{},{}>", s, self.left, self.right);
360             self.advance_right();
361             let len = s.len() as isize;
362             self.buf[self.right] = BufEntry { token: Token::String(s), size: len };
363             self.right_total += len;
364             self.check_stream();
365         }
366     }
367
368     fn check_stream(&mut self) {
369         debug!(
370             "check_stream Vec<{}, {}> with left_total={}, right_total={}",
371             self.left, self.right, self.left_total, self.right_total
372         );
373         if self.right_total - self.left_total > self.space {
374             debug!(
375                 "scan window is {}, longer than space on line ({})",
376                 self.right_total - self.left_total,
377                 self.space
378             );
379             if Some(&self.left) == self.scan_stack.back() {
380                 debug!("setting {} to infinity and popping", self.left);
381                 let scanned = self.scan_pop_bottom();
382                 self.buf[scanned].size = SIZE_INFINITY;
383             }
384             self.advance_left();
385             if self.left != self.right {
386                 self.check_stream();
387             }
388         }
389     }
390
391     fn scan_push(&mut self, entry: BufEntry) {
392         debug!("scan_push {}", self.right);
393         self.buf[self.right] = entry;
394         self.scan_stack.push_front(self.right);
395     }
396
397     fn scan_pop(&mut self) -> usize {
398         self.scan_stack.pop_front().unwrap()
399     }
400
401     fn scan_top(&mut self) -> usize {
402         *self.scan_stack.front().unwrap()
403     }
404
405     fn scan_pop_bottom(&mut self) -> usize {
406         self.scan_stack.pop_back().unwrap()
407     }
408
409     fn advance_right(&mut self) {
410         self.right += 1;
411         self.right %= self.buf_max_len;
412         // Extend the buf if necessary.
413         if self.right == self.buf.len() {
414             self.buf.push(BufEntry::default());
415         }
416         assert_ne!(self.right, self.left);
417     }
418
419     fn advance_left(&mut self) {
420         debug!(
421             "advance_left Vec<{},{}>, sizeof({})={}",
422             self.left, self.right, self.left, self.buf[self.left].size
423         );
424
425         let mut left_size = self.buf[self.left].size;
426
427         while left_size >= 0 {
428             let left = self.buf[self.left].token.clone();
429
430             let len = match left {
431                 Token::Break(b) => b.blank_space,
432                 Token::String(ref s) => {
433                     let len = s.len() as isize;
434                     assert_eq!(len, left_size);
435                     len
436                 }
437                 _ => 0,
438             };
439
440             self.print(left, left_size);
441
442             self.left_total += len;
443
444             if self.left == self.right {
445                 break;
446             }
447
448             self.left += 1;
449             self.left %= self.buf_max_len;
450
451             left_size = self.buf[self.left].size;
452         }
453     }
454
455     fn check_stack(&mut self, k: usize) {
456         if !self.scan_stack.is_empty() {
457             let x = self.scan_top();
458             match self.buf[x].token {
459                 Token::Begin(_) => {
460                     if k > 0 {
461                         self.scan_pop();
462                         self.buf[x].size += self.right_total;
463                         self.check_stack(k - 1);
464                     }
465                 }
466                 Token::End => {
467                     // paper says + not =, but that makes no sense.
468                     self.scan_pop();
469                     self.buf[x].size = 1;
470                     self.check_stack(k + 1);
471                 }
472                 _ => {
473                     self.scan_pop();
474                     self.buf[x].size += self.right_total;
475                     if k > 0 {
476                         self.check_stack(k);
477                     }
478                 }
479             }
480         }
481     }
482
483     fn print_newline(&mut self, amount: isize) {
484         debug!("NEWLINE {}", amount);
485         self.out.push('\n');
486         self.pending_indentation = 0;
487         self.indent(amount);
488     }
489
490     fn indent(&mut self, amount: isize) {
491         debug!("INDENT {}", amount);
492         self.pending_indentation += amount;
493     }
494
495     fn get_top(&mut self) -> PrintStackElem {
496         match self.print_stack.last() {
497             Some(el) => *el,
498             None => {
499                 PrintStackElem { offset: 0, pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) }
500             }
501         }
502     }
503
504     fn print_begin(&mut self, b: BeginToken, l: isize) {
505         if l > self.space {
506             let col = self.margin - self.space + b.offset;
507             debug!("print Begin -> push broken block at col {}", col);
508             self.print_stack
509                 .push(PrintStackElem { offset: col, pbreak: PrintStackBreak::Broken(b.breaks) });
510         } else {
511             debug!("print Begin -> push fitting block");
512             self.print_stack.push(PrintStackElem { offset: 0, pbreak: PrintStackBreak::Fits });
513         }
514     }
515
516     fn print_end(&mut self) {
517         debug!("print End -> pop End");
518         self.print_stack.pop().unwrap();
519     }
520
521     fn print_break(&mut self, b: BreakToken, l: isize) {
522         let top = self.get_top();
523         match top.pbreak {
524             PrintStackBreak::Fits => {
525                 debug!("print Break({}) in fitting block", b.blank_space);
526                 self.space -= b.blank_space;
527                 self.indent(b.blank_space);
528             }
529             PrintStackBreak::Broken(Breaks::Consistent) => {
530                 debug!("print Break({}+{}) in consistent block", top.offset, b.offset);
531                 self.print_newline(top.offset + b.offset);
532                 self.space = self.margin - (top.offset + b.offset);
533             }
534             PrintStackBreak::Broken(Breaks::Inconsistent) => {
535                 if l > self.space {
536                     debug!("print Break({}+{}) w/ newline in inconsistent", top.offset, b.offset);
537                     self.print_newline(top.offset + b.offset);
538                     self.space = self.margin - (top.offset + b.offset);
539                 } else {
540                     debug!("print Break({}) w/o newline in inconsistent", b.blank_space);
541                     self.indent(b.blank_space);
542                     self.space -= b.blank_space;
543                 }
544             }
545         }
546     }
547
548     fn print_string(&mut self, s: Cow<'static, str>) {
549         let len = s.len() as isize;
550         debug!("print String({})", s);
551         // assert!(len <= space);
552         self.space -= len;
553
554         // Write the pending indent. A more concise way of doing this would be:
555         //
556         //   write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
557         //
558         // But that is significantly slower. This code is sufficiently hot, and indents can get
559         // sufficiently large, that the difference is significant on some workloads.
560         self.out.reserve(self.pending_indentation as usize);
561         self.out.extend(std::iter::repeat(' ').take(self.pending_indentation as usize));
562         self.pending_indentation = 0;
563         self.out.push_str(&s);
564     }
565
566     fn print(&mut self, token: Token, l: isize) {
567         debug!("print {} {} (remaining line space={})", token, l, self.space);
568         debug!("{}", buf_str(&self.buf, self.left, self.right, 6));
569         match token {
570             Token::Begin(b) => self.print_begin(b, l),
571             Token::End => self.print_end(),
572             Token::Break(b) => self.print_break(b, l),
573             Token::String(s) => {
574                 let len = s.len() as isize;
575                 assert_eq!(len, l);
576                 self.print_string(s);
577             }
578             Token::Eof => panic!(), // Eof should never get here.
579         }
580     }
581
582     // Convenience functions to talk to the printer.
583
584     /// "raw box"
585     pub fn rbox(&mut self, indent: usize, b: Breaks) {
586         self.scan_begin(BeginToken { offset: indent as isize, breaks: b })
587     }
588
589     /// Inconsistent breaking box
590     pub fn ibox(&mut self, indent: usize) {
591         self.rbox(indent, Breaks::Inconsistent)
592     }
593
594     /// Consistent breaking box
595     pub fn cbox(&mut self, indent: usize) {
596         self.rbox(indent, Breaks::Consistent)
597     }
598
599     pub fn break_offset(&mut self, n: usize, off: isize) {
600         self.scan_break(BreakToken { offset: off, blank_space: n as isize })
601     }
602
603     pub fn end(&mut self) {
604         self.scan_end()
605     }
606
607     pub fn eof(mut self) -> String {
608         self.scan_eof();
609         self.out
610     }
611
612     pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
613         let s = wrd.into();
614         self.scan_string(s)
615     }
616
617     fn spaces(&mut self, n: usize) {
618         self.break_offset(n, 0)
619     }
620
621     crate fn zerobreak(&mut self) {
622         self.spaces(0)
623     }
624
625     pub fn space(&mut self) {
626         self.spaces(1)
627     }
628
629     pub fn hardbreak(&mut self) {
630         self.spaces(SIZE_INFINITY as usize)
631     }
632
633     pub fn is_beginning_of_line(&self) -> bool {
634         self.last_token().is_eof() || self.last_token().is_hardbreak_tok()
635     }
636
637     pub fn hardbreak_tok_offset(off: isize) -> Token {
638         Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY })
639     }
640 }