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