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