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