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