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