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.
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.
12 * This pretty-printer is a direct reimplementation of Philip Karlton's
13 * Mesa pretty-printer, as described in appendix A of
15 * STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen.
16 * Stanford Department of Computer Science, 1979.
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)".
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?
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.
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).
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.
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.
64 pub enum breaks { consistent, inconsistent, }
85 fn is_eof(&self) -> bool {
86 match *self { EOF => true, _ => false }
88 fn is_hardbreak_tok(&self) -> bool {
93 }) if bs == size_infinity =>
101 pub fn tok_str(t: token) -> ~str {
103 STRING(s, len) => return fmt!("STR(%s,%d)", *s, len),
104 BREAK(_) => return ~"BREAK",
105 BEGIN(_) => return ~"BEGIN",
106 END => return ~"END",
111 pub fn buf_str(toks: ~[token], szs: ~[int], left: uint, right: uint,
113 let n = vec::len(toks);
114 assert!(n == vec::len(szs));
118 while i != right && L != 0u {
120 if i != left { s += ~", "; }
121 s += fmt!("%d=%s", szs[i], tok_str(toks[i]));
129 pub enum print_stack_break { fits, broken(breaks), }
131 pub struct print_stack_elt {
133 pbreak: print_stack_break
136 pub static size_infinity: int = 0xffff;
138 pub fn mk_printer(out: @io::Writer, linewidth: uint) -> @mut Printer {
139 // Yes 3, it makes the ring buffers big enough to never
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);
149 margin: linewidth as int,
150 space: linewidth as int,
157 scan_stack: scan_stack,
158 scan_stack_empty: true,
161 print_stack: @mut ~[],
162 pending_indentation: 0
168 * In case you do not have the paper, here is an explanation of what's going
171 * There is a stream of input tokens flowing through this printer.
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.
177 * Tokens are STRING, BREAK, and BEGIN/END to delimit blocks.
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:
185 * foo(hello, there, good, friends)
187 * breaking inconsistently to become
192 * whereas a consistent breaking would yield:
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.
203 * Carrying on with high-level logic:
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.
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).
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.
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).
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
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
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
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,
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);
279 if !self.scan_stack_empty {
281 self.advance_left(self.token[self.left],
282 self.size[self.left]);
287 if self.scan_stack_empty {
289 self.right_total = 1;
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);
300 if self.scan_stack_empty {
301 debug!("pp END/print ~[%u,%u]", self.left, self.right);
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);
312 if self.scan_stack_empty {
314 self.right_total = 1;
317 } else { self.advance_right(); }
318 debug!("pp BREAK(%d)/buffer ~[%u,%u]",
319 b.offset, self.left, self.right);
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;
327 if self.scan_stack_empty {
328 debug!("pp STRING('%s')/print ~[%u,%u]",
329 *s, self.left, self.right);
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;
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;
355 self.advance_left(self.token[self.left], self.size[self.left]);
356 if self.left != self.right { self.check_stream(); }
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;
365 self.top %= self.buf_len;
366 assert!((self.top != self.bottom));
368 self.scan_stack[self.top] = x;
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; }
378 fn scan_top(&mut self) -> uint {
379 assert!((!self.scan_stack_empty));
380 return self.scan_stack[self.top];
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; }
390 fn advance_right(&mut self) {
392 self.right %= self.buf_len;
393 assert!((self.right != self.left));
395 fn advance_left(&mut self, x: token, L: int) {
396 debug!("advnce_left ~[%u,%u], sizeof(%u)=%d", self.left, self.right,
401 BREAK(b) => self.left_total += b.blank_space,
403 assert!((len == L)); self.left_total += len;
407 if self.left != self.right {
409 self.left %= self.buf_len;
410 self.advance_left(self.token[self.left],
411 self.size[self.left]);
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] {
421 self.size[self.scan_pop()] = self.size[x] +
423 self.check_stack(k - 1);
427 // paper says + not =, but that makes no sense.
428 self.size[self.scan_pop()] = 1;
429 self.check_stack(k + 1);
432 self.size[self.scan_pop()] = self.size[x] + self.right_total;
433 if k > 0 { self.check_stack(k); }
438 fn print_newline(&mut self, amount: int) {
439 debug!("NEWLINE %d", amount);
440 (*self.out).write_str(~"\n");
441 self.pending_indentation = 0;
444 fn indent(&mut self, amount: int) {
445 debug!("INDENT %d", amount);
446 self.pending_indentation += amount;
448 fn get_top(&mut self) -> print_stack_elt {
449 let print_stack = &mut *self.print_stack;
450 let n = print_stack.len();
456 pbreak: broken(inconsistent)
460 fn print_str(&mut self, s: ~str) {
461 while self.pending_indentation > 0 {
462 (*self.out).write_str(~" ");
463 self.pending_indentation -= 1;
465 (*self.out).write_str(s);
467 fn print(&mut self, x: token, L: int) {
468 debug!("print %s %d (remaining line space=%d)", tok_str(x), L,
470 debug!("%s", buf_str(copy self.token,
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 {
482 pbreak: broken(b.breaks)
485 debug!("print BEGIN -> push fitting block");
486 self.print_stack.push(print_stack_elt {
493 debug!("print END -> pop END");
494 let print_stack = &*self.print_stack;
495 assert!((print_stack.len() != 0u));
496 self.print_stack.pop();
499 let top = self.get_top();
502 debug!("print BREAK(%d) in fitting block", b.blank_space);
503 self.space -= b.blank_space;
504 self.indent(b.blank_space);
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);
512 broken(inconsistent) => {
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);
519 debug!("print BREAK(%d) w/o newline in inconsistent",
521 self.indent(b.blank_space);
522 self.space -= b.blank_space;
528 debug!("print STRING(%s)", *s);
530 // assert!(L <= space);
535 // EOF should never get here.
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,
550 pub fn ibox(p: @mut Printer, indent: uint) { box(p, indent, inconsistent); }
552 pub fn cbox(p: @mut Printer, indent: uint) { box(p, indent, consistent); }
554 pub fn break_offset(p: @mut Printer, n: uint, off: int) {
555 p.pretty_print(BREAK(break_t {
557 blank_space: n as int
561 pub fn end(p: @mut Printer) { p.pretty_print(END); }
563 pub fn eof(p: @mut Printer) { p.pretty_print(EOF); }
565 pub fn word(p: @mut Printer, wrd: ~str) {
566 p.pretty_print(STRING(@/*bad*/ copy wrd, wrd.len() as int));
569 pub fn huge_word(p: @mut Printer, wrd: ~str) {
570 p.pretty_print(STRING(@/*bad*/ copy wrd, size_infinity));
573 pub fn zero_word(p: @mut Printer, wrd: ~str) {
574 p.pretty_print(STRING(@/*bad*/ copy wrd, 0));
577 pub fn spaces(p: @mut Printer, n: uint) { break_offset(p, n, 0); }
579 pub fn zerobreak(p: @mut Printer) { spaces(p, 0u); }
581 pub fn space(p: @mut Printer) { spaces(p, 1u); }
583 pub fn hardbreak(p: @mut Printer) { spaces(p, size_infinity as uint); }
585 pub fn hardbreak_tok_offset(off: int) -> token {
586 BREAK(break_t {offset: off, blank_space: size_infinity})
589 pub fn hardbreak_tok() -> token { return hardbreak_tok_offset(0); }
596 // indent-tabs-mode: nil
598 // buffer-file-coding-system: utf-8-unix