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