Skip to main content

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 ring;
136
137use std::borrow::Cow;
138use std::collections::VecDeque;
139use std::{cmp, iter};
140
141use ring::RingBuffer;
142
143/// How to break. Described in more detail in the module docs.
144#[derive(#[automatically_derived]
impl ::core::clone::Clone for Breaks {
    #[inline]
    fn clone(&self) -> Breaks { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Breaks { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Breaks {
    #[inline]
    fn eq(&self, other: &Breaks) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
145pub enum Breaks {
146    Consistent,
147    Inconsistent,
148}
149
150#[derive(#[automatically_derived]
impl ::core::clone::Clone for IndentStyle {
    #[inline]
    fn clone(&self) -> IndentStyle {
        let _: ::core::clone::AssertParamIsClone<isize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IndentStyle { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for IndentStyle {
    #[inline]
    fn eq(&self, other: &IndentStyle) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (IndentStyle::Block { offset: __self_0 }, IndentStyle::Block {
                    offset: __arg1_0 }) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
151enum IndentStyle {
152    /// Vertically aligned under whatever column this block begins at.
153    ///
154    ///     fn demo(arg1: usize,
155    ///             arg2: usize) {}
156    Visual,
157    /// Indented relative to the indentation level of the previous line.
158    ///
159    ///     fn demo(
160    ///         arg1: usize,
161    ///         arg2: usize,
162    ///     ) {}
163    Block { offset: isize },
164}
165
166#[derive(#[automatically_derived]
impl ::core::clone::Clone for BreakToken {
    #[inline]
    fn clone(&self) -> BreakToken {
        let _: ::core::clone::AssertParamIsClone<isize>;
        let _: ::core::clone::AssertParamIsClone<Option<char>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BreakToken { }Copy, #[automatically_derived]
impl ::core::default::Default for BreakToken {
    #[inline]
    fn default() -> BreakToken {
        BreakToken {
            offset: ::core::default::Default::default(),
            blank_space: ::core::default::Default::default(),
            pre_break: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for BreakToken {
    #[inline]
    fn eq(&self, other: &BreakToken) -> bool {
        self.offset == other.offset && self.blank_space == other.blank_space
            && self.pre_break == other.pre_break
    }
}PartialEq)]
167pub(crate) struct BreakToken {
168    offset: isize,
169    blank_space: isize,
170    pre_break: Option<char>,
171}
172
173#[derive(#[automatically_derived]
impl ::core::clone::Clone for BeginToken {
    #[inline]
    fn clone(&self) -> BeginToken {
        let _: ::core::clone::AssertParamIsClone<IndentStyle>;
        let _: ::core::clone::AssertParamIsClone<Breaks>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BeginToken { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BeginToken {
    #[inline]
    fn eq(&self, other: &BeginToken) -> bool {
        self.indent == other.indent && self.breaks == other.breaks
    }
}PartialEq)]
174pub(crate) struct BeginToken {
175    indent: IndentStyle,
176    breaks: Breaks,
177}
178
179#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for Token {
    #[inline]
    fn eq(&self, other: &Token) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Token::String(__self_0), Token::String(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Break(__self_0), Token::Break(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Token::Begin(__self_0), Token::Begin(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
180pub(crate) enum Token {
181    // In practice a string token contains either a `&'static str` or a
182    // `String`. `Cow` is overkill for this because we never modify the data,
183    // but it's more convenient than rolling our own more specialized type.
184    String(Cow<'static, str>),
185    Break(BreakToken),
186    Begin(BeginToken),
187    End,
188}
189
190impl Token {
191    pub(crate) fn is_hardbreak_tok(&self) -> bool {
192        *self == Printer::hardbreak_tok_offset(0)
193    }
194}
195
196#[derive(#[automatically_derived]
impl ::core::marker::Copy for PrintFrame { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PrintFrame {
    #[inline]
    fn clone(&self) -> PrintFrame {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<Breaks>;
        *self
    }
}Clone)]
197enum PrintFrame {
198    Fits,
199    Broken { indent: usize, breaks: Breaks },
200}
201
202const SIZE_INFINITY: isize = 0xffff;
203
204/// Target line width.
205const MARGIN: isize = 78;
206/// Every line is allowed at least this much space, even if highly indented.
207const MIN_SPACE: isize = 60;
208
209pub struct Printer {
210    out: String,
211    /// Number of spaces left on line
212    space: isize,
213    /// Ring-buffer of tokens and calculated sizes
214    buf: RingBuffer<BufEntry>,
215    /// Running size of stream "...left"
216    left_total: isize,
217    /// Running size of stream "...right"
218    right_total: isize,
219    /// Pseudo-stack, really a ring too. Holds the
220    /// primary-ring-buffers index of the Begin that started the
221    /// current block, possibly with the most recent Break after that
222    /// Begin (if there is any) on top of it. Stuff is flushed off the
223    /// bottom as it becomes irrelevant due to the primary ring-buffer
224    /// advancing.
225    scan_stack: VecDeque<usize>,
226    /// Stack of blocks-in-progress being flushed by print
227    print_stack: Vec<PrintFrame>,
228    /// Level of indentation of current line
229    indent: usize,
230    /// Buffered indentation to avoid writing trailing whitespace
231    pending_indentation: isize,
232    /// The token most recently popped from the left boundary of the
233    /// ring-buffer for printing
234    last_printed: Option<Token>,
235}
236
237struct BufEntry {
238    token: Token,
239    size: isize,
240}
241
242// Boxes opened with methods like `Printer::{cbox,ibox}` must be closed with
243// `Printer::end`. Failure to do so can result in bad indenting, or in extreme
244// cases, cause no output to be produced at all.
245//
246// Box opening and closing used to be entirely implicit, which was hard to
247// understand and easy to get wrong. This marker type is now returned from the
248// box opening methods and forgotten by `Printer::end`. Any marker that isn't
249// forgotten will trigger a panic in `drop`. (Closing a box more than once
250// isn't possible because `BoxMarker` doesn't implement `Copy` or `Clone`.)
251//
252// Note: it would be better to make open/close mismatching impossible and avoid
253// the need for this marker type altogether by having functions like
254// `with_ibox` that open a box, call a closure, and then close the box. That
255// would work for simple cases, but box lifetimes sometimes interact with
256// complex control flow and across function boundaries in ways that are
257// difficult to handle with such a technique.
258#[must_use]
259pub struct BoxMarker;
260
261impl !Clone for BoxMarker {}
262impl !Copy for BoxMarker {}
263
264impl Drop for BoxMarker {
265    fn drop(&mut self) {
266        {
    ::core::panicking::panic_fmt(format_args!("BoxMarker not ended with `Printer::end()`"));
};panic!("BoxMarker not ended with `Printer::end()`");
267    }
268}
269
270impl Printer {
271    pub fn new() -> Self {
272        Printer {
273            out: String::new(),
274            space: MARGIN,
275            buf: RingBuffer::new(),
276            left_total: 0,
277            right_total: 0,
278            scan_stack: VecDeque::new(),
279            print_stack: Vec::new(),
280            indent: 0,
281            pending_indentation: 0,
282            last_printed: None,
283        }
284    }
285
286    pub(crate) fn last_token(&self) -> Option<&Token> {
287        self.last_token_still_buffered().or_else(|| self.last_printed.as_ref())
288    }
289
290    pub(crate) fn last_token_still_buffered(&self) -> Option<&Token> {
291        self.buf.last().map(|last| &last.token)
292    }
293
294    /// Be very careful with this!
295    pub(crate) fn replace_last_token_still_buffered(&mut self, token: Token) {
296        self.buf.last_mut().unwrap().token = token;
297    }
298
299    fn scan_eof(&mut self) {
300        if !self.scan_stack.is_empty() {
301            self.check_stack(0);
302            self.advance_left();
303        }
304    }
305
306    // This is where `BoxMarker`s are produced.
307    fn scan_begin(&mut self, token: BeginToken) -> BoxMarker {
308        if self.scan_stack.is_empty() {
309            self.left_total = 1;
310            self.right_total = 1;
311            self.buf.clear();
312        }
313        let right = self.buf.push(BufEntry { token: Token::Begin(token), size: -self.right_total });
314        self.scan_stack.push_back(right);
315        BoxMarker
316    }
317
318    // This is where `BoxMarker`s are consumed.
319    fn scan_end(&mut self, b: BoxMarker) {
320        if self.scan_stack.is_empty() {
321            self.print_end();
322        } else {
323            let right = self.buf.push(BufEntry { token: Token::End, size: -1 });
324            self.scan_stack.push_back(right);
325        }
326        std::mem::forget(b)
327    }
328
329    fn scan_break(&mut self, token: BreakToken) {
330        if self.scan_stack.is_empty() {
331            self.left_total = 1;
332            self.right_total = 1;
333            self.buf.clear();
334        } else {
335            self.check_stack(0);
336        }
337        let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total });
338        self.scan_stack.push_back(right);
339        self.right_total += token.blank_space;
340    }
341
342    fn scan_string(&mut self, string: Cow<'static, str>) {
343        if self.scan_stack.is_empty() {
344            self.print_string(&string);
345        } else {
346            let len = string.len() as isize;
347            self.buf.push(BufEntry { token: Token::String(string), size: len });
348            self.right_total += len;
349            self.check_stream();
350        }
351    }
352
353    pub(crate) fn offset(&mut self, offset: isize) {
354        if let Some(BufEntry { token: Token::Break(token), .. }) = &mut self.buf.last_mut() {
355            token.offset += offset;
356        }
357    }
358
359    fn check_stream(&mut self) {
360        while self.right_total - self.left_total > self.space {
361            if *self.scan_stack.front().unwrap() == self.buf.index_of_first() {
362                self.scan_stack.pop_front().unwrap();
363                self.buf.first_mut().unwrap().size = SIZE_INFINITY;
364            }
365            self.advance_left();
366            if self.buf.is_empty() {
367                break;
368            }
369        }
370    }
371
372    fn advance_left(&mut self) {
373        while self.buf.first().unwrap().size >= 0 {
374            let left = self.buf.pop_first().unwrap();
375
376            match &left.token {
377                Token::String(string) => {
378                    self.left_total += string.len() as isize;
379                    self.print_string(string);
380                }
381                Token::Break(token) => {
382                    self.left_total += token.blank_space;
383                    self.print_break(*token, left.size);
384                }
385                Token::Begin(token) => self.print_begin(*token, left.size),
386                Token::End => self.print_end(),
387            }
388
389            self.last_printed = Some(left.token);
390
391            if self.buf.is_empty() {
392                break;
393            }
394        }
395    }
396
397    fn check_stack(&mut self, mut depth: usize) {
398        while let Some(&index) = self.scan_stack.back() {
399            let entry = &mut self.buf[index];
400            match entry.token {
401                Token::Begin(_) => {
402                    if depth == 0 {
403                        break;
404                    }
405                    self.scan_stack.pop_back().unwrap();
406                    entry.size += self.right_total;
407                    depth -= 1;
408                }
409                Token::End => {
410                    // paper says + not =, but that makes no sense.
411                    self.scan_stack.pop_back().unwrap();
412                    entry.size = 1;
413                    depth += 1;
414                }
415                _ => {
416                    self.scan_stack.pop_back().unwrap();
417                    entry.size += self.right_total;
418                    if depth == 0 {
419                        break;
420                    }
421                }
422            }
423        }
424    }
425
426    fn get_top(&self) -> PrintFrame {
427        *self
428            .print_stack
429            .last()
430            .unwrap_or(&PrintFrame::Broken { indent: 0, breaks: Breaks::Inconsistent })
431    }
432
433    fn print_begin(&mut self, token: BeginToken, size: isize) {
434        if size > self.space {
435            self.print_stack.push(PrintFrame::Broken { indent: self.indent, breaks: token.breaks });
436            self.indent = match token.indent {
437                IndentStyle::Block { offset } => {
438                    usize::try_from(self.indent as isize + offset).unwrap()
439                }
440                IndentStyle::Visual => (MARGIN - self.space) as usize,
441            };
442        } else {
443            self.print_stack.push(PrintFrame::Fits);
444        }
445    }
446
447    fn print_end(&mut self) {
448        if let PrintFrame::Broken { indent, .. } = self.print_stack.pop().unwrap() {
449            self.indent = indent;
450        }
451    }
452
453    fn print_break(&mut self, token: BreakToken, size: isize) {
454        let fits = match self.get_top() {
455            PrintFrame::Fits => true,
456            PrintFrame::Broken { breaks: Breaks::Consistent, .. } => false,
457            PrintFrame::Broken { breaks: Breaks::Inconsistent, .. } => size <= self.space,
458        };
459        if fits {
460            self.pending_indentation += token.blank_space;
461            self.space -= token.blank_space;
462        } else {
463            if let Some(pre_break) = token.pre_break {
464                self.out.push(pre_break);
465            }
466            self.out.push('\n');
467            let indent = self.indent as isize + token.offset;
468            self.pending_indentation = indent;
469            self.space = cmp::max(MARGIN - indent, MIN_SPACE);
470        }
471    }
472
473    fn print_string(&mut self, string: &str) {
474        // Write the pending indent. A more concise way of doing this would be:
475        //
476        //   write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
477        //
478        // But that is significantly slower. This code is sufficiently hot, and indents can get
479        // sufficiently large, that the difference is significant on some workloads.
480        self.out.reserve(self.pending_indentation as usize);
481        self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize));
482        self.pending_indentation = 0;
483
484        self.out.push_str(string);
485        self.space -= string.len() as isize;
486    }
487
488    /// Synthesizes a comment that was not textually present in the original
489    /// source file.
490    pub fn synth_comment(&mut self, text: impl Into<Cow<'static, str>>) {
491        self.word("/*");
492        self.space();
493        self.word(text);
494        self.space();
495        self.word("*/")
496    }
497
498    /// "raw box"
499    pub fn rbox(&mut self, indent: isize, breaks: Breaks) -> BoxMarker {
500        self.scan_begin(BeginToken { indent: IndentStyle::Block { offset: indent }, breaks })
501    }
502
503    /// Inconsistent breaking box
504    pub fn ibox(&mut self, indent: isize) -> BoxMarker {
505        self.rbox(indent, Breaks::Inconsistent)
506    }
507
508    /// Consistent breaking box
509    pub fn cbox(&mut self, indent: isize) -> BoxMarker {
510        self.rbox(indent, Breaks::Consistent)
511    }
512
513    pub fn visual_align(&mut self) -> BoxMarker {
514        self.scan_begin(BeginToken { indent: IndentStyle::Visual, breaks: Breaks::Consistent })
515    }
516
517    pub fn break_offset(&mut self, n: usize, off: isize) {
518        self.scan_break(BreakToken {
519            offset: off,
520            blank_space: n as isize,
521            ..BreakToken::default()
522        });
523    }
524
525    pub fn end(&mut self, b: BoxMarker) {
526        self.scan_end(b)
527    }
528
529    pub fn eof(mut self) -> String {
530        self.scan_eof();
531        self.out
532    }
533
534    pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
535        let string = wrd.into();
536        self.scan_string(string)
537    }
538
539    pub fn word_space<W: Into<Cow<'static, str>>>(&mut self, w: W) {
540        self.word(w);
541        self.space();
542    }
543
544    pub fn nbsp(&mut self) {
545        self.word(" ")
546    }
547
548    pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
549        self.word(w);
550        self.nbsp()
551    }
552
553    fn spaces(&mut self, n: usize) {
554        self.break_offset(n, 0)
555    }
556
557    pub fn zerobreak(&mut self) {
558        self.spaces(0)
559    }
560
561    pub fn space(&mut self) {
562        self.spaces(1)
563    }
564
565    pub fn popen(&mut self) {
566        self.word("(");
567    }
568
569    pub fn pclose(&mut self) {
570        self.word(")");
571    }
572
573    pub fn hardbreak(&mut self) {
574        self.spaces(SIZE_INFINITY as usize)
575    }
576
577    pub fn is_beginning_of_line(&self) -> bool {
578        match self.last_token() {
579            Some(last_token) => last_token.is_hardbreak_tok(),
580            None => true,
581        }
582    }
583
584    pub fn hardbreak_if_not_bol(&mut self) {
585        if !self.is_beginning_of_line() {
586            self.hardbreak()
587        }
588    }
589
590    pub fn space_if_not_bol(&mut self) {
591        if !self.is_beginning_of_line() {
592            self.space();
593        }
594    }
595
596    pub(crate) fn hardbreak_tok_offset(off: isize) -> Token {
597        Token::Break(BreakToken {
598            offset: off,
599            blank_space: SIZE_INFINITY,
600            ..BreakToken::default()
601        })
602    }
603
604    pub fn trailing_comma(&mut self) {
605        self.scan_break(BreakToken { pre_break: Some(','), ..BreakToken::default() });
606    }
607
608    pub fn trailing_comma_or_space(&mut self) {
609        self.scan_break(BreakToken {
610            blank_space: 1,
611            pre_break: Some(','),
612            ..BreakToken::default()
613        });
614    }
615}