rustc_ast_pretty/pp.rs
1//! This pretty-printer is a direct reimplementation of Philip Karlton's
2//! Mesa pretty-printer, as described in the appendix to
3//! Derek C. Oppen, "Pretty Printing" (1979),
4//! Stanford Computer Science Department STAN-CS-79-770,
5//! <http://i.stanford.edu/pub/cstr/reports/cs/tr/79/770/CS-TR-79-770.pdf>.
6//!
7//! The algorithm's aim is to break a stream into as few lines as possible
8//! while respecting the indentation-consistency requirements of the enclosing
9//! block, and avoiding breaking at silly places on block boundaries, for
10//! example, between "x" and ")" in "x)".
11//!
12//! I am implementing this algorithm because it comes with 20 pages of
13//! documentation explaining its theory, and because it addresses the set of
14//! concerns I've seen other pretty-printers fall down on. Weirdly. Even though
15//! it's 32 years old. What can I say?
16//!
17//! Despite some redundancies and quirks in the way it's implemented in that
18//! paper, I've opted to keep the implementation here as similar as I can,
19//! changing only what was blatantly wrong, a typo, or sufficiently
20//! non-idiomatic rust that it really stuck out.
21//!
22//! In particular you'll see a certain amount of churn related to INTEGER vs.
23//! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two
24//! somewhat readily? In any case, I've used usize for indices-in-buffers and
25//! ints for character-sizes-and-indentation-offsets. This respects the need
26//! for ints to "go negative" while carrying a pending-calculation balance, and
27//! helps differentiate all the numbers flying around internally (slightly).
28//!
29//! I also inverted the indentation arithmetic used in the print stack, since
30//! the Mesa implementation (somewhat randomly) stores the offset on the print
31//! stack in terms of margin-col rather than col itself. I store col.
32//!
33//! I also implemented a small change in the String token, in that I store an
34//! explicit length for the string. For most tokens this is just the length of
35//! the accompanying string. But it's necessary to permit it to differ, for
36//! encoding things that are supposed to "go on their own line" -- certain
37//! classes of comment and blank-line -- where relying on adjacent
38//! hardbreak-like Break tokens with long blankness indication doesn't actually
39//! work. To see why, consider when there is a "thing that should be on its own
40//! line" between two long blocks, say functions. If you put a hardbreak after
41//! each function (or before each) and the breaking algorithm decides to break
42//! there anyways (because the functions themselves are long) you wind up with
43//! extra blank lines. If you don't put hardbreaks you can wind up with the
44//! "thing which should be on its own line" not getting its own line in the
45//! rare case of "really small functions" or such. This re-occurs with comments
46//! and explicit blank lines. So in those cases we use a string with a payload
47//! we want isolated to a line and an explicit length that's huge, surrounded
48//! by two zero-length breaks. The algorithm will try its best to fit it on a
49//! line (which it can't) and so naturally place the content on its own line to
50//! avoid combining it with other lines and making matters even worse.
51//!
52//! # Explanation
53//!
54//! In case you do not have the paper, here is an explanation of what's going
55//! on.
56//!
57//! There is a stream of input tokens flowing through this printer.
58//!
59//! The printer buffers up to 3N tokens inside itself, where N is linewidth.
60//! Yes, linewidth is chars and tokens are multi-char, but in the worst
61//! case every token worth buffering is 1 char long, so it's ok.
62//!
63//! Tokens are String, Break, and Begin/End to delimit blocks.
64//!
65//! Begin tokens can carry an offset, saying "how far to indent when you break
66//! inside here", as well as a flag indicating "consistent" or "inconsistent"
67//! breaking. Consistent breaking means that after the first break, no attempt
68//! will be made to flow subsequent breaks together onto lines. Inconsistent
69//! is the opposite. Inconsistent breaking example would be, say:
70//!
71//! ```ignore (illustrative)
72//! foo(hello, there, good, friends)
73//! ```
74//!
75//! breaking inconsistently to become
76//!
77//! ```ignore (illustrative)
78//! foo(hello, there,
79//! good, friends);
80//! ```
81//!
82//! whereas a consistent breaking would yield:
83//!
84//! ```ignore (illustrative)
85//! foo(hello,
86//! there,
87//! good,
88//! friends);
89//! ```
90//!
91//! That is, in the consistent-break blocks we value vertical alignment
92//! more than the ability to cram stuff onto a line. But in all cases if it
93//! can make a block a one-liner, it'll do so.
94//!
95//! Carrying on with high-level logic:
96//!
97//! The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and
98//! 'right' indices denote the active portion of the ring buffer as well as
99//! describing hypothetical points-in-the-infinite-stream at most 3N tokens
100//! apart (i.e., "not wrapped to ring-buffer boundaries"). The paper will switch
101//! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer
102//! and point-in-infinite-stream senses freely.
103//!
104//! There is a parallel ring buffer, `size`, that holds the calculated size of
105//! each token. Why calculated? Because for Begin/End pairs, the "size"
106//! includes everything between the pair. That is, the "size" of Begin is
107//! actually the sum of the sizes of everything between Begin and the paired
108//! End that follows. Since that is arbitrarily far in the future, `size` is
109//! being rewritten regularly while the printer runs; in fact most of the
110//! machinery is here to work out `size` entries on the fly (and give up when
111//! they're so obviously over-long that "infinity" is a good enough
112//! approximation for purposes of line breaking).
113//!
114//! The "input side" of the printer is managed as an abstract process called
115//! SCAN, which uses `scan_stack`, to manage calculating `size`. SCAN is, in
116//! other words, the process of calculating 'size' entries.
117//!
118//! The "output side" of the printer is managed by an abstract process called
119//! PRINT, which uses `print_stack`, `margin` and `space` to figure out what to
120//! do with each token/size pair it consumes as it goes. It's trying to consume
121//! the entire buffered window, but can't output anything until the size is >=
122//! 0 (sizes are set to negative while they're pending calculation).
123//!
124//! So SCAN takes input and buffers tokens and pending calculations, while
125//! PRINT gobbles up completed calculations and tokens from the buffer. The
126//! theory is that the two can never get more than 3N tokens apart, because
127//! once there's "obviously" too much data to fit on a line, in a size
128//! calculation, SCAN will write "infinity" to the size and let PRINT consume
129//! it.
130//!
131//! In this implementation (following the paper, again) the SCAN process is the
132//! methods called `Printer::scan_*`, and the 'PRINT' process is the
133//! method called `Printer::print`.
134
135mod convenience;
136mod ring;
137
138use std::borrow::Cow;
139use std::collections::VecDeque;
140use std::{cmp, iter};
141
142use ring::RingBuffer;
143
144/// How to break. Described in more detail in the module docs.
145#[derive(Clone, Copy, PartialEq)]
146pub enum Breaks {
147 Consistent,
148 Inconsistent,
149}
150
151#[derive(Clone, Copy, PartialEq)]
152enum IndentStyle {
153 /// Vertically aligned under whatever column this block begins at.
154 ///
155 /// fn demo(arg1: usize,
156 /// arg2: usize) {}
157 Visual,
158 /// Indented relative to the indentation level of the previous line.
159 ///
160 /// fn demo(
161 /// arg1: usize,
162 /// arg2: usize,
163 /// ) {}
164 Block { offset: isize },
165}
166
167#[derive(Clone, Copy, Default, PartialEq)]
168pub(crate) struct BreakToken {
169 offset: isize,
170 blank_space: isize,
171 pre_break: Option<char>,
172}
173
174#[derive(Clone, Copy, PartialEq)]
175pub(crate) struct BeginToken {
176 indent: IndentStyle,
177 breaks: Breaks,
178}
179
180#[derive(PartialEq)]
181pub(crate) enum Token {
182 // In practice a string token contains either a `&'static str` or a
183 // `String`. `Cow` is overkill for this because we never modify the data,
184 // but it's more convenient than rolling our own more specialized type.
185 String(Cow<'static, str>),
186 Break(BreakToken),
187 Begin(BeginToken),
188 End,
189}
190
191#[derive(Copy, Clone)]
192enum PrintFrame {
193 Fits,
194 Broken { indent: usize, breaks: Breaks },
195}
196
197const SIZE_INFINITY: isize = 0xffff;
198
199/// Target line width.
200const MARGIN: isize = 78;
201/// Every line is allowed at least this much space, even if highly indented.
202const MIN_SPACE: isize = 60;
203
204pub struct Printer {
205 out: String,
206 /// Number of spaces left on line
207 space: isize,
208 /// Ring-buffer of tokens and calculated sizes
209 buf: RingBuffer<BufEntry>,
210 /// Running size of stream "...left"
211 left_total: isize,
212 /// Running size of stream "...right"
213 right_total: isize,
214 /// Pseudo-stack, really a ring too. Holds the
215 /// primary-ring-buffers index of the Begin that started the
216 /// current block, possibly with the most recent Break after that
217 /// Begin (if there is any) on top of it. Stuff is flushed off the
218 /// bottom as it becomes irrelevant due to the primary ring-buffer
219 /// advancing.
220 scan_stack: VecDeque<usize>,
221 /// Stack of blocks-in-progress being flushed by print
222 print_stack: Vec<PrintFrame>,
223 /// Level of indentation of current line
224 indent: usize,
225 /// Buffered indentation to avoid writing trailing whitespace
226 pending_indentation: isize,
227 /// The token most recently popped from the left boundary of the
228 /// ring-buffer for printing
229 last_printed: Option<Token>,
230}
231
232struct BufEntry {
233 token: Token,
234 size: isize,
235}
236
237// Boxes opened with methods like `Printer::{cbox,ibox}` must be closed with
238// `Printer::end`. Failure to do so can result in bad indenting, or in extreme
239// cases, cause no output to be produced at all.
240//
241// Box opening and closing used to be entirely implicit, which was hard to
242// understand and easy to get wrong. This marker type is now returned from the
243// box opening methods and forgotten by `Printer::end`. Any marker that isn't
244// forgotten will trigger a panic in `drop`. (Closing a box more than once
245// isn't possible because `BoxMarker` doesn't implement `Copy` or `Clone`.)
246//
247// Note: it would be better to make open/close mismatching impossible and avoid
248// the need for this marker type altogether by having functions like
249// `with_ibox` that open a box, call a closure, and then close the box. That
250// would work for simple cases, but box lifetimes sometimes interact with
251// complex control flow and across function boundaries in ways that are
252// difficult to handle with such a technique.
253#[must_use]
254pub struct BoxMarker;
255
256impl !Clone for BoxMarker {}
257impl !Copy for BoxMarker {}
258
259impl Drop for BoxMarker {
260 fn drop(&mut self) {
261 panic!("BoxMarker not ended with `Printer::end()`");
262 }
263}
264
265impl Printer {
266 pub fn new() -> Self {
267 Printer {
268 out: String::new(),
269 space: MARGIN,
270 buf: RingBuffer::new(),
271 left_total: 0,
272 right_total: 0,
273 scan_stack: VecDeque::new(),
274 print_stack: Vec::new(),
275 indent: 0,
276 pending_indentation: 0,
277 last_printed: None,
278 }
279 }
280
281 pub(crate) fn last_token(&self) -> Option<&Token> {
282 self.last_token_still_buffered().or_else(|| self.last_printed.as_ref())
283 }
284
285 pub(crate) fn last_token_still_buffered(&self) -> Option<&Token> {
286 self.buf.last().map(|last| &last.token)
287 }
288
289 /// Be very careful with this!
290 pub(crate) fn replace_last_token_still_buffered(&mut self, token: Token) {
291 self.buf.last_mut().unwrap().token = token;
292 }
293
294 fn scan_eof(&mut self) {
295 if !self.scan_stack.is_empty() {
296 self.check_stack(0);
297 self.advance_left();
298 }
299 }
300
301 // This is is where `BoxMarker`s are produced.
302 fn scan_begin(&mut self, token: BeginToken) -> BoxMarker {
303 if self.scan_stack.is_empty() {
304 self.left_total = 1;
305 self.right_total = 1;
306 self.buf.clear();
307 }
308 let right = self.buf.push(BufEntry { token: Token::Begin(token), size: -self.right_total });
309 self.scan_stack.push_back(right);
310 BoxMarker
311 }
312
313 // This is is where `BoxMarker`s are consumed.
314 fn scan_end(&mut self, b: BoxMarker) {
315 if self.scan_stack.is_empty() {
316 self.print_end();
317 } else {
318 let right = self.buf.push(BufEntry { token: Token::End, size: -1 });
319 self.scan_stack.push_back(right);
320 }
321 std::mem::forget(b)
322 }
323
324 fn scan_break(&mut self, token: BreakToken) {
325 if self.scan_stack.is_empty() {
326 self.left_total = 1;
327 self.right_total = 1;
328 self.buf.clear();
329 } else {
330 self.check_stack(0);
331 }
332 let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total });
333 self.scan_stack.push_back(right);
334 self.right_total += token.blank_space;
335 }
336
337 fn scan_string(&mut self, string: Cow<'static, str>) {
338 if self.scan_stack.is_empty() {
339 self.print_string(&string);
340 } else {
341 let len = string.len() as isize;
342 self.buf.push(BufEntry { token: Token::String(string), size: len });
343 self.right_total += len;
344 self.check_stream();
345 }
346 }
347
348 pub(crate) fn offset(&mut self, offset: isize) {
349 if let Some(BufEntry { token: Token::Break(token), .. }) = &mut self.buf.last_mut() {
350 token.offset += offset;
351 }
352 }
353
354 fn check_stream(&mut self) {
355 while self.right_total - self.left_total > self.space {
356 if *self.scan_stack.front().unwrap() == self.buf.index_of_first() {
357 self.scan_stack.pop_front().unwrap();
358 self.buf.first_mut().unwrap().size = SIZE_INFINITY;
359 }
360 self.advance_left();
361 if self.buf.is_empty() {
362 break;
363 }
364 }
365 }
366
367 fn advance_left(&mut self) {
368 while self.buf.first().unwrap().size >= 0 {
369 let left = self.buf.pop_first().unwrap();
370
371 match &left.token {
372 Token::String(string) => {
373 self.left_total += string.len() as isize;
374 self.print_string(string);
375 }
376 Token::Break(token) => {
377 self.left_total += token.blank_space;
378 self.print_break(*token, left.size);
379 }
380 Token::Begin(token) => self.print_begin(*token, left.size),
381 Token::End => self.print_end(),
382 }
383
384 self.last_printed = Some(left.token);
385
386 if self.buf.is_empty() {
387 break;
388 }
389 }
390 }
391
392 fn check_stack(&mut self, mut depth: usize) {
393 while let Some(&index) = self.scan_stack.back() {
394 let entry = &mut self.buf[index];
395 match entry.token {
396 Token::Begin(_) => {
397 if depth == 0 {
398 break;
399 }
400 self.scan_stack.pop_back().unwrap();
401 entry.size += self.right_total;
402 depth -= 1;
403 }
404 Token::End => {
405 // paper says + not =, but that makes no sense.
406 self.scan_stack.pop_back().unwrap();
407 entry.size = 1;
408 depth += 1;
409 }
410 _ => {
411 self.scan_stack.pop_back().unwrap();
412 entry.size += self.right_total;
413 if depth == 0 {
414 break;
415 }
416 }
417 }
418 }
419 }
420
421 fn get_top(&self) -> PrintFrame {
422 *self
423 .print_stack
424 .last()
425 .unwrap_or(&PrintFrame::Broken { indent: 0, breaks: Breaks::Inconsistent })
426 }
427
428 fn print_begin(&mut self, token: BeginToken, size: isize) {
429 if size > self.space {
430 self.print_stack.push(PrintFrame::Broken { indent: self.indent, breaks: token.breaks });
431 self.indent = match token.indent {
432 IndentStyle::Block { offset } => {
433 usize::try_from(self.indent as isize + offset).unwrap()
434 }
435 IndentStyle::Visual => (MARGIN - self.space) as usize,
436 };
437 } else {
438 self.print_stack.push(PrintFrame::Fits);
439 }
440 }
441
442 fn print_end(&mut self) {
443 if let PrintFrame::Broken { indent, .. } = self.print_stack.pop().unwrap() {
444 self.indent = indent;
445 }
446 }
447
448 fn print_break(&mut self, token: BreakToken, size: isize) {
449 let fits = match self.get_top() {
450 PrintFrame::Fits => true,
451 PrintFrame::Broken { breaks: Breaks::Consistent, .. } => false,
452 PrintFrame::Broken { breaks: Breaks::Inconsistent, .. } => size <= self.space,
453 };
454 if fits {
455 self.pending_indentation += token.blank_space;
456 self.space -= token.blank_space;
457 } else {
458 if let Some(pre_break) = token.pre_break {
459 self.out.push(pre_break);
460 }
461 self.out.push('\n');
462 let indent = self.indent as isize + token.offset;
463 self.pending_indentation = indent;
464 self.space = cmp::max(MARGIN - indent, MIN_SPACE);
465 }
466 }
467
468 fn print_string(&mut self, string: &str) {
469 // Write the pending indent. A more concise way of doing this would be:
470 //
471 // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
472 //
473 // But that is significantly slower. This code is sufficiently hot, and indents can get
474 // sufficiently large, that the difference is significant on some workloads.
475 self.out.reserve(self.pending_indentation as usize);
476 self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize));
477 self.pending_indentation = 0;
478
479 self.out.push_str(string);
480 self.space -= string.len() as isize;
481 }
482}