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