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