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