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