Skip to main content

rustc_ast_pretty/pprust/
state.rs

1//! AST pretty printing.
2//!
3//! Note that HIR pretty printing is layered on top of this crate.
4
5mod expr;
6mod fixup;
7mod item;
8
9use std::borrow::Cow;
10use std::sync::Arc;
11
12use rustc_ast::attr::AttrIdGenerator;
13use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree};
14use rustc_ast::util::classify;
15use rustc_ast::util::comments::{Comment, CommentStyle};
16use rustc_ast::{
17    self as ast, AttrArgs, AttrKind, BindingMode, BlockCheckMode, ByRef, DelimArgs, GenericArg,
18    GenericBound, InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass,
19    InlineAsmTemplatePiece, PatKind, RangeEnd, RangeSyntax, SelfKind, Term, attr, token as tk,
20};
21use rustc_span::edition::Edition;
22use rustc_span::source_map::SourceMap;
23use rustc_span::symbol::IdentPrinter;
24use rustc_span::{
25    BytePos, CharPos, DUMMY_SP, FileName, Ident, Pos, Span, Spanned, Symbol, kw, sym,
26};
27
28use crate::pp::Breaks::{Consistent, Inconsistent};
29use crate::pp::{self, BoxMarker, Breaks};
30use crate::pprust::state::fixup::FixupContext;
31
32pub enum MacHeader<'a> {
33    Path(&'a ast::Path),
34    Keyword(&'static str),
35}
36
37pub enum AnnNode<'a> {
38    Ident(&'a Ident),
39    Name(&'a Symbol),
40    Block(&'a ast::Block),
41    Item(&'a ast::Item),
42    SubItem(ast::NodeId),
43    Expr(&'a ast::Expr),
44    Pat(&'a ast::Pat),
45    Crate(&'a ast::Crate),
46}
47
48pub trait PpAnn {
49    fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
50    fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
51}
52
53struct NoAnn;
54
55impl PpAnn for NoAnn {}
56
57pub struct Comments<'a> {
58    sm: &'a SourceMap,
59    // Stored in reverse order so we can consume them by popping.
60    reversed_comments: Vec<Comment>,
61}
62
63/// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
64/// Otherwise returns `Some(k)` where `k` is first char offset after that leading
65/// whitespace. Note that `k` may be outside bounds of `s`.
66fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
67    let mut idx = 0;
68    for (i, ch) in s.char_indices().take(col.to_usize()) {
69        if !ch.is_whitespace() {
70            return None;
71        }
72        idx = i + ch.len_utf8();
73    }
74    Some(idx)
75}
76
77fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
78    let len = s.len();
79    match all_whitespace(s, col) {
80        Some(col) => {
81            if col < len {
82                &s[col..]
83            } else {
84                ""
85            }
86        }
87        None => s,
88    }
89}
90
91fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
92    let mut res: Vec<String> = ::alloc::vec::Vec::new()vec![];
93    let mut lines = text.lines();
94    // just push the first line
95    res.extend(lines.next().map(|it| it.to_string()));
96    // for other lines, strip common whitespace prefix
97    for line in lines {
98        res.push(trim_whitespace_prefix(line, col).to_string())
99    }
100    res
101}
102
103fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
104    let sm = SourceMap::new(sm.path_mapping().clone());
105    let source_file = sm.new_source_file(path, src);
106    let text = Arc::clone(&(*source_file.src.as_ref().unwrap()));
107
108    let text: &str = text.as_str();
109    let start_bpos = source_file.start_pos;
110    let mut pos = 0;
111    let mut comments: Vec<Comment> = Vec::new();
112    let mut code_to_the_left = false;
113
114    if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
115        comments.push(Comment {
116            style: CommentStyle::Isolated,
117            lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [text[..shebang_len].to_string()]))vec![text[..shebang_len].to_string()],
118            pos: start_bpos,
119        });
120        pos += shebang_len;
121    }
122
123    for token in rustc_lexer::tokenize(&text[pos..], rustc_lexer::FrontmatterAllowed::Yes) {
124        let token_text = &text[pos..pos + token.len as usize];
125        match token.kind {
126            rustc_lexer::TokenKind::Whitespace => {
127                if let Some(mut idx) = token_text.find('\n') {
128                    code_to_the_left = false;
129                    while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
130                        idx += 1 + next_newline;
131                        comments.push(Comment {
132                            style: CommentStyle::BlankLine,
133                            lines: ::alloc::vec::Vec::new()vec![],
134                            pos: start_bpos + BytePos((pos + idx) as u32),
135                        });
136                    }
137                }
138            }
139            rustc_lexer::TokenKind::BlockComment { doc_style, .. } => {
140                if doc_style.is_none() {
141                    let code_to_the_right = !#[allow(non_exhaustive_omitted_patterns)] match text[pos +
                        token.len as usize..].chars().next() {
    Some('\r' | '\n') => true,
    _ => false,
}matches!(
142                        text[pos + token.len as usize..].chars().next(),
143                        Some('\r' | '\n')
144                    );
145                    let style = match (code_to_the_left, code_to_the_right) {
146                        (_, true) => CommentStyle::Mixed,
147                        (false, false) => CommentStyle::Isolated,
148                        (true, false) => CommentStyle::Trailing,
149                    };
150
151                    // Count the number of chars since the start of the line by rescanning.
152                    let pos_in_file = start_bpos + BytePos(pos as u32);
153                    let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
154                    let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
155                    let col = CharPos(text[line_begin_pos..pos].chars().count());
156
157                    let lines = split_block_comment_into_lines(token_text, col);
158                    comments.push(Comment { style, lines, pos: pos_in_file })
159                }
160            }
161            rustc_lexer::TokenKind::LineComment { doc_style } => {
162                if doc_style.is_none() {
163                    comments.push(Comment {
164                        style: if code_to_the_left {
165                            CommentStyle::Trailing
166                        } else {
167                            CommentStyle::Isolated
168                        },
169                        lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [token_text.to_string()]))vec![token_text.to_string()],
170                        pos: start_bpos + BytePos(pos as u32),
171                    })
172                }
173            }
174            rustc_lexer::TokenKind::Frontmatter { .. } => {
175                code_to_the_left = false;
176                comments.push(Comment {
177                    style: CommentStyle::Isolated,
178                    lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [token_text.to_string()]))vec![token_text.to_string()],
179                    pos: start_bpos + BytePos(pos as u32),
180                });
181            }
182            _ => {
183                code_to_the_left = true;
184            }
185        }
186        pos += token.len as usize;
187    }
188
189    comments
190}
191
192impl<'a> Comments<'a> {
193    pub fn new(sm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
194        let mut comments = gather_comments(sm, filename, input);
195        comments.reverse();
196        Comments { sm, reversed_comments: comments }
197    }
198
199    fn peek(&self) -> Option<&Comment> {
200        self.reversed_comments.last()
201    }
202
203    fn next(&mut self) -> Option<Comment> {
204        self.reversed_comments.pop()
205    }
206
207    fn trailing_comment(
208        &mut self,
209        span: rustc_span::Span,
210        next_pos: Option<BytePos>,
211    ) -> Option<Comment> {
212        if let Some(cmnt) = self.peek() {
213            if cmnt.style != CommentStyle::Trailing {
214                return None;
215            }
216            let span_line = self.sm.lookup_char_pos(span.hi());
217            let comment_line = self.sm.lookup_char_pos(cmnt.pos);
218            let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
219            if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
220                return Some(self.next().unwrap());
221            }
222        }
223
224        None
225    }
226}
227
228pub struct State<'a> {
229    pub s: pp::Printer,
230    comments: Option<Comments<'a>>,
231    ann: &'a (dyn PpAnn + 'a),
232    is_sdylib_interface: bool,
233}
234
235const INDENT_UNIT: isize = 4;
236
237/// Requires you to pass an input filename and reader so that
238/// it can scan the input text for comments to copy forward.
239pub fn print_crate<'a>(
240    sm: &'a SourceMap,
241    krate: &ast::Crate,
242    filename: FileName,
243    input: String,
244    ann: &'a dyn PpAnn,
245    is_expanded: bool,
246    edition: Edition,
247    g: &AttrIdGenerator,
248) -> String {
249    let mut s = State {
250        s: pp::Printer::new(),
251        comments: Some(Comments::new(sm, filename, input)),
252        ann,
253        is_sdylib_interface: false,
254    };
255
256    print_crate_inner(&mut s, krate, is_expanded, edition, g);
257    s.s.eof()
258}
259
260pub fn print_crate_as_interface(
261    krate: &ast::Crate,
262    edition: Edition,
263    g: &AttrIdGenerator,
264) -> String {
265    let mut s =
266        State { s: pp::Printer::new(), comments: None, ann: &NoAnn, is_sdylib_interface: true };
267
268    print_crate_inner(&mut s, krate, false, edition, g);
269    s.s.eof()
270}
271
272fn print_crate_inner<'a>(
273    s: &mut State<'a>,
274    krate: &ast::Crate,
275    is_expanded: bool,
276    edition: Edition,
277    g: &AttrIdGenerator,
278) {
279    // We need to print shebang before anything else
280    // otherwise the resulting code will not compile
281    // and shebang will be useless.
282    s.maybe_print_shebang();
283
284    if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
285        // We need to print `#![no_std]` (and its feature gate) so that
286        // compiling pretty-printed source won't inject libstd again.
287        // However, we don't want these attributes in the AST because
288        // of the feature gate, so we fake them up here.
289
290        // `#![feature(prelude_import)]`
291        let fake_attr = attr::mk_attr_nested_word(
292            g,
293            ast::AttrStyle::Inner,
294            sym::feature,
295            sym::prelude_import,
296            DUMMY_SP,
297        );
298        s.print_attribute(&fake_attr);
299
300        // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
301        // root, so this is not needed, and actually breaks things.
302        if edition.is_rust_2015() {
303            // `#![no_std]`
304            let fake_attr = attr::mk_attr_word(g, ast::AttrStyle::Inner, sym::no_std, DUMMY_SP);
305            s.print_attribute(&fake_attr);
306        }
307    }
308
309    s.print_inner_attributes(&krate.attrs);
310    for item in &krate.items {
311        s.print_item(item);
312    }
313    s.print_remaining_comments();
314    s.ann.post(s, AnnNode::Crate(krate));
315}
316
317/// Should two consecutive tokens be printed with a space between them?
318///
319/// Note: some old proc macros parse pretty-printed output, so changes here can
320/// break old code. For example:
321/// - #63896: `#[allow(unused,` must be printed rather than `#[allow(unused ,`
322/// - #73345: `#[allow(unused)]` must be printed rather than `# [allow(unused)]`
323///
324/// Returns `true` if both token trees are identifier-like tokens that would
325/// merge into a single token if printed without a space between them.
326/// E.g. `ident` + `where` would merge into `identwhere`.
327fn idents_would_merge(tt1: &TokenTree, tt2: &TokenTree) -> bool {
328    fn is_ident_like(tt: &TokenTree) -> bool {
329        #[allow(non_exhaustive_omitted_patterns)] match tt {
    TokenTree::Token(tk::Token { kind: tk::Ident(..) | tk::NtIdent(..), .. },
        _) => true,
    _ => false,
}matches!(tt, TokenTree::Token(tk::Token { kind: tk::Ident(..) | tk::NtIdent(..), .. }, _,))
330    }
331    is_ident_like(tt1) && is_ident_like(tt2)
332}
333
334fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool {
335    use TokenTree::{Delimited as Del, Token as Tok};
336    use tk::Delimiter::{Bracket, Parenthesis};
337
338    fn is_punct(tt: &TokenTree) -> bool {
339        #[allow(non_exhaustive_omitted_patterns)] match tt {
    TokenTree::Token(tok, _) if tok.is_punct() => true,
    _ => false,
}matches!(tt, TokenTree::Token(tok, _) if tok.is_punct())
340    }
341
342    // Each match arm has one or more examples in comments. The default is to
343    // insert space between adjacent tokens, except for the cases listed in
344    // this match.
345    match (tt1, tt2) {
346        // No space after line doc comments.
347        (Tok(tk::Token { kind: tk::DocComment(tk::CommentKind::Line, ..), .. }, _), _) => false,
348
349        // `.` + NON-PUNCT: `x.y`, `tup.0`
350        (Tok(tk::Token { kind: tk::Dot, .. }, _), tt2) if !is_punct(tt2) => false,
351
352        // `$` + IDENT: `$e`
353        (
354            Tok(tk::Token { kind: tk::Dollar, .. }, _),
355            Tok(tk::Token { kind: tk::Ident(..), .. }, _),
356        ) => false,
357
358        // NON-PUNCT + `,`: `foo,`
359        // NON-PUNCT + `;`: `x = 3;`, `[T; 3]`
360        // NON-PUNCT + `.`: `x.y`, `tup.0`
361        (tt1, Tok(tk::Token { kind: tk::Comma | tk::Semi | tk::Dot, .. }, _)) if !is_punct(tt1) => {
362            false
363        }
364
365        // IDENT + `!`: `println!()`, but `if !x { ... }` needs a space after the `if`
366        (
367            Tok(tk::Token { kind: tk::Ident(sym, is_raw), span }, _),
368            Tok(tk::Token { kind: tk::Bang, .. }, _),
369        ) if !Ident::new(*sym, *span).is_reserved() || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    tk::IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, tk::IdentIsRaw::Yes) => {
370            false
371        }
372
373        // IDENT|`fn`|`Self`|`pub` + `(`: `f(3)`, `fn(x: u8)`, `Self()`, `pub(crate)`,
374        //      but `let (a, b) = (1, 2)` needs a space after the `let`
375        (Tok(tk::Token { kind: tk::Ident(sym, is_raw), span }, _), Del(_, _, Parenthesis, _))
376            if !Ident::new(*sym, *span).is_reserved()
377                || *sym == kw::Fn
378                || *sym == kw::SelfUpper
379                || *sym == kw::Pub
380                || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    tk::IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, tk::IdentIsRaw::Yes) =>
381        {
382            false
383        }
384
385        // `#` + `[`: `#[attr]`
386        (Tok(tk::Token { kind: tk::Pound, .. }, _), Del(_, _, Bracket, _)) => false,
387
388        _ => true,
389    }
390}
391
392pub fn doc_comment_to_string(
393    fragment_kind: tk::DocFragmentKind,
394    attr_style: ast::AttrStyle,
395    data: Symbol,
396) -> String {
397    match fragment_kind {
398        tk::DocFragmentKind::Sugared(comment_kind) => match (comment_kind, attr_style) {
399            (tk::CommentKind::Line, ast::AttrStyle::Outer) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("///{0}", data))
    })format!("///{data}"),
400            (tk::CommentKind::Line, ast::AttrStyle::Inner) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("//!{0}", data))
    })format!("//!{data}"),
401            (tk::CommentKind::Block, ast::AttrStyle::Outer) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/**{0}*/", data))
    })format!("/**{data}*/"),
402            (tk::CommentKind::Block, ast::AttrStyle::Inner) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/*!{0}*/", data))
    })format!("/*!{data}*/"),
403        },
404        tk::DocFragmentKind::Raw(_) => {
405            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}[doc = {1:?}]",
                if attr_style == ast::AttrStyle::Inner { "!" } else { "" },
                data.to_string()))
    })format!(
406                "#{}[doc = {:?}]",
407                if attr_style == ast::AttrStyle::Inner { "!" } else { "" },
408                data.to_string(),
409            )
410        }
411    }
412}
413
414fn literal_to_string(lit: tk::Lit) -> String {
415    let tk::Lit { kind, symbol, suffix } = lit;
416    let mut out = match kind {
417        tk::Byte => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("b\'{0}\'", symbol))
    })format!("b'{symbol}'"),
418        tk::Char => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}\'", symbol))
    })format!("'{symbol}'"),
419        tk::Str => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", symbol))
    })format!("\"{symbol}\""),
420        tk::StrRaw(n) => {
421            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("r{0}\"{1}\"{0}",
                "#".repeat(n as usize), symbol))
    })format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
422        }
423        tk::ByteStr => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("b\"{0}\"", symbol))
    })format!("b\"{symbol}\""),
424        tk::ByteStrRaw(n) => {
425            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("br{0}\"{1}\"{0}",
                "#".repeat(n as usize), symbol))
    })format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
426        }
427        tk::CStr => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c\"{0}\"", symbol))
    })format!("c\"{symbol}\""),
428        tk::CStrRaw(n) => {
429            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cr{0}\"{1}\"{0}",
                "#".repeat(n as usize), symbol))
    })format!("cr{delim}\"{symbol}\"{delim}", delim = "#".repeat(n as usize))
430        }
431        tk::Integer | tk::Float | tk::Bool | tk::Err(_) => symbol.to_string(),
432    };
433
434    if let Some(suffix) = suffix {
435        out.push_str(suffix.as_str())
436    }
437
438    out
439}
440
441impl std::ops::Deref for State<'_> {
442    type Target = pp::Printer;
443    fn deref(&self) -> &Self::Target {
444        &self.s
445    }
446}
447
448impl std::ops::DerefMut for State<'_> {
449    fn deref_mut(&mut self) -> &mut Self::Target {
450        &mut self.s
451    }
452}
453
454/// This trait is used for both AST and HIR pretty-printing.
455pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
456    fn comments(&self) -> Option<&Comments<'a>>;
457    fn comments_mut(&mut self) -> Option<&mut Comments<'a>>;
458    fn ann_post(&mut self, ident: Ident);
459    fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
460
461    fn print_ident(&mut self, ident: Ident) {
462        self.word(IdentPrinter::for_ast_ident(ident, ident.guess_print_mode()).to_string());
463        self.ann_post(ident)
464    }
465
466    fn strsep<'x, T: 'x, F, I>(
467        &mut self,
468        sep: &'static str,
469        space_before: bool,
470        b: Breaks,
471        elts: I,
472        mut op: F,
473    ) where
474        F: FnMut(&mut Self, &T),
475        I: IntoIterator<Item = &'x T>,
476    {
477        let mut it = elts.into_iter();
478
479        let rb = self.rbox(0, b);
480        if let Some(first) = it.next() {
481            op(self, first);
482            for elt in it {
483                if space_before {
484                    self.space();
485                }
486                self.word_space(sep);
487                op(self, elt);
488            }
489        }
490        self.end(rb);
491    }
492
493    fn commasep<'x, T: 'x, F, I>(&mut self, b: Breaks, elts: I, op: F)
494    where
495        F: FnMut(&mut Self, &T),
496        I: IntoIterator<Item = &'x T>,
497    {
498        self.strsep(",", false, b, elts, op)
499    }
500
501    fn maybe_print_comment(&mut self, pos: BytePos) -> bool {
502        let mut has_comment = false;
503        while let Some(cmnt) = self.peek_comment() {
504            if cmnt.pos >= pos {
505                break;
506            }
507            has_comment = true;
508            let cmnt = self.next_comment().unwrap();
509            self.print_comment(cmnt);
510        }
511        has_comment
512    }
513
514    fn print_comment(&mut self, cmnt: Comment) {
515        match cmnt.style {
516            CommentStyle::Mixed => {
517                if !self.is_beginning_of_line() {
518                    self.zerobreak();
519                }
520                if let Some((last, lines)) = cmnt.lines.split_last() {
521                    let ib = self.ibox(0);
522
523                    for line in lines {
524                        self.word(line.clone());
525                        self.hardbreak()
526                    }
527
528                    self.word(last.clone());
529                    self.space();
530
531                    self.end(ib);
532                }
533                self.zerobreak()
534            }
535            CommentStyle::Isolated => {
536                self.hardbreak_if_not_bol();
537                for line in &cmnt.lines {
538                    // Don't print empty lines because they will end up as trailing
539                    // whitespace.
540                    if !line.is_empty() {
541                        self.word(line.clone());
542                    }
543                    self.hardbreak();
544                }
545            }
546            CommentStyle::Trailing => {
547                if !self.is_beginning_of_line() {
548                    self.word(" ");
549                }
550                if let [line] = cmnt.lines.as_slice() {
551                    self.word(line.clone());
552                    self.hardbreak()
553                } else {
554                    let vb = self.visual_align();
555                    for line in &cmnt.lines {
556                        if !line.is_empty() {
557                            self.word(line.clone());
558                        }
559                        self.hardbreak();
560                    }
561                    self.end(vb);
562                }
563            }
564            CommentStyle::BlankLine => {
565                // We need to do at least one, possibly two hardbreaks.
566                let twice = match self.last_token() {
567                    Some(pp::Token::String(s)) => ";" == s,
568                    Some(pp::Token::Begin(_)) => true,
569                    Some(pp::Token::End) => true,
570                    _ => false,
571                };
572                if twice {
573                    self.hardbreak();
574                }
575                self.hardbreak();
576            }
577        }
578    }
579
580    fn peek_comment<'b>(&'b self) -> Option<&'b Comment>
581    where
582        'a: 'b,
583    {
584        self.comments().and_then(|c| c.peek())
585    }
586
587    fn next_comment(&mut self) -> Option<Comment> {
588        self.comments_mut().and_then(|c| c.next())
589    }
590
591    fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option<BytePos>) {
592        if let Some(cmnts) = self.comments_mut()
593            && let Some(cmnt) = cmnts.trailing_comment(span, next_pos)
594        {
595            self.print_comment(cmnt);
596        }
597    }
598
599    fn print_remaining_comments(&mut self) {
600        // If there aren't any remaining comments, then we need to manually
601        // make sure there is a line break at the end.
602        if self.peek_comment().is_none() {
603            self.hardbreak();
604        }
605        while let Some(cmnt) = self.next_comment() {
606            self.print_comment(cmnt)
607        }
608    }
609
610    fn print_string(&mut self, st: &str, style: ast::StrStyle) {
611        let st = match style {
612            ast::StrStyle::Cooked => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", st.escape_debug()))
    })format!("\"{}\"", st.escape_debug()),
613            ast::StrStyle::Raw(n) => {
614                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("r{0}\"{1}\"{0}",
                "#".repeat(n as usize), st))
    })format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
615            }
616        };
617        self.word(st)
618    }
619
620    fn maybe_print_shebang(&mut self) {
621        if let Some(cmnt) = self.peek_comment() {
622            // Comment is a shebang if it's:
623            // Isolated, starts with #! and doesn't continue with `[`
624            // See [rustc_lexer::strip_shebang] and [gather_comments] from pprust/state.rs for details
625            if cmnt.style == CommentStyle::Isolated
626                && cmnt.lines.first().map_or(false, |l| l.starts_with("#!"))
627            {
628                let cmnt = self.next_comment().unwrap();
629                self.print_comment(cmnt);
630            }
631        }
632    }
633
634    fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
635        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
636    }
637
638    fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
639        self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
640    }
641
642    fn print_either_attributes(
643        &mut self,
644        attrs: &[ast::Attribute],
645        kind: ast::AttrStyle,
646        is_inline: bool,
647        trailing_hardbreak: bool,
648    ) -> bool {
649        let mut printed = false;
650        for attr in attrs {
651            if attr.style == kind {
652                if self.print_attribute_inline(attr, is_inline) {
653                    if is_inline {
654                        self.nbsp();
655                    }
656                    printed = true;
657                }
658            }
659        }
660        if printed && trailing_hardbreak && !is_inline {
661            self.hardbreak_if_not_bol();
662        }
663        printed
664    }
665
666    fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) -> bool {
667        use ast::SyntheticAttr::*;
668        match attr.kind {
669            AttrKind::Synthetic(CfgTrace(_) | CfgAttrTrace(_)) => {
670                // These are internal synthetic attributes with no syntax, so avoid printing them
671                // to keep the printed code reasonably parse-able.
672                return false;
673            }
674            AttrKind::Normal(_) | AttrKind::DocComment(..) => {}
675        }
676        if !is_inline {
677            self.hardbreak_if_not_bol();
678        }
679        self.maybe_print_comment(attr.span.lo());
680        match &attr.kind {
681            ast::AttrKind::Normal(normal) => {
682                match attr.style {
683                    ast::AttrStyle::Inner => self.word("#!["),
684                    ast::AttrStyle::Outer => self.word("#["),
685                }
686                self.print_attr_item(&normal.item, attr.span);
687                self.word("]");
688            }
689            ast::AttrKind::Synthetic(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(), // due to early return above
690            ast::AttrKind::DocComment(comment_kind, data) => {
691                self.word(doc_comment_to_string(
692                    tk::DocFragmentKind::Sugared(*comment_kind),
693                    attr.style,
694                    *data,
695                ));
696                self.hardbreak()
697            }
698        }
699        true
700    }
701
702    fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
703        let ib = self.ibox(0);
704        match item.unsafety {
705            ast::Safety::Unsafe(_) => {
706                self.word("unsafe");
707                self.popen();
708            }
709            ast::Safety::Default | ast::Safety::Safe(_) => {}
710        }
711        match &item.args {
712            AttrArgs::Delimited(DelimArgs { dspan: _, delim, tokens }) => self.print_mac_common(
713                Some(MacHeader::Path(&item.path)),
714                false,
715                None,
716                *delim,
717                None,
718                tokens,
719                true,
720                span,
721            ),
722            AttrArgs::Empty => {
723                self.print_path(&item.path, false, 0);
724            }
725            AttrArgs::Eq { expr, .. } => {
726                self.print_path(&item.path, false, 0);
727                self.space();
728                self.word_space("=");
729                let token_str = self.expr_to_string(expr);
730                self.word(token_str);
731            }
732        }
733        match item.unsafety {
734            ast::Safety::Unsafe(_) => self.pclose(),
735            ast::Safety::Default | ast::Safety::Safe(_) => {}
736        }
737        self.end(ib);
738    }
739
740    /// This doesn't deserve to be called "pretty" printing, but it should be
741    /// meaning-preserving. A quick hack that might help would be to look at the
742    /// spans embedded in the TTs to decide where to put spaces and newlines.
743    /// But it'd be better to parse these according to the grammar of the
744    /// appropriate macro, transcribe back into the grammar we just parsed from,
745    /// and then pretty-print the resulting AST nodes (so, e.g., we print
746    /// expression arguments as expressions). It can be done! I think.
747    fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) -> Spacing {
748        match tt {
749            TokenTree::Token(token, spacing) => {
750                let token_str = self.token_to_string_ext(token, convert_dollar_crate);
751                self.word(token_str);
752                // Emit hygiene annotations for identity-bearing tokens,
753                // matching how print_ident() and print_lifetime() call ann_post().
754                match token.kind {
755                    tk::Ident(name, _) => {
756                        self.ann_post(Ident::new(name, token.span));
757                    }
758                    tk::NtIdent(ident, _) => {
759                        self.ann_post(ident);
760                    }
761                    tk::Lifetime(name, _) => {
762                        self.ann_post(Ident::new(name, token.span));
763                    }
764                    tk::NtLifetime(ident, _) => {
765                        self.ann_post(ident);
766                    }
767                    _ => {}
768                }
769                if let tk::DocComment(..) = token.kind {
770                    self.hardbreak()
771                }
772                *spacing
773            }
774            TokenTree::Delimited(dspan, spacing, delim, tts) => {
775                self.print_mac_common(
776                    None,
777                    false,
778                    None,
779                    *delim,
780                    Some(spacing.open),
781                    tts,
782                    convert_dollar_crate,
783                    dspan.entire(),
784                );
785                spacing.close
786            }
787        }
788    }
789
790    // The easiest way to implement token stream pretty printing would be to
791    // print each token followed by a single space. But that would produce ugly
792    // output, so we go to some effort to do better.
793    //
794    // First, we track whether each token that appears in source code is
795    // followed by a space, with `Spacing`, and reproduce that in the output.
796    // This works well in a lot of cases. E.g. `stringify!(x + y)` produces
797    // "x + y" and `stringify!(x+y)` produces "x+y".
798    //
799    // But this doesn't work for code produced by proc macros (which have no
800    // original source text representation) nor for code produced by decl
801    // macros (which are tricky because the whitespace after tokens appearing
802    // in macro rules isn't always what you want in the produced output). For
803    // these we mostly use `Spacing::Alone`, which is the conservative choice.
804    //
805    // So we have a backup mechanism for when `Spacing::Alone` occurs between a
806    // pair of tokens: we check if that pair of tokens can obviously go
807    // together without a space between them. E.g. token `x` followed by token
808    // `,` is better printed as `x,` than `x ,`. (Even if the original source
809    // code was `x ,`.)
810    //
811    // Finally, we must be careful about changing the output. tk::Token pretty
812    // printing is used by `stringify!` and `impl Display for
813    // proc_macro::TokenStream`, and some programs rely on the output having a
814    // particular form, even though they shouldn't. In particular, some proc
815    // macros do `format!({stream})` on a token stream and then "parse" the
816    // output with simple string matching that can't handle whitespace changes.
817    // E.g. we have seen cases where a proc macro can handle `a :: b` but not
818    // `a::b`. See #117433 for some examples.
819    fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
820        let mut iter = tts.iter().peekable();
821        while let Some(tt) = iter.next() {
822            let spacing = self.print_tt(tt, convert_dollar_crate);
823            if let Some(next) = iter.peek() {
824                if spacing == Spacing::Alone && space_between(tt, next) {
825                    self.space();
826                } else if spacing != Spacing::Alone && idents_would_merge(tt, next) {
827                    // When tokens from macro `tt` captures preserve their
828                    // original `Joint`/`JointHidden` spacing, adjacent
829                    // identifier-like tokens can be concatenated without a
830                    // space (e.g. `$x:identwhere`). Insert a space to
831                    // prevent this.
832                    self.space();
833                }
834            }
835        }
836    }
837
838    fn print_mac_common(
839        &mut self,
840        header: Option<MacHeader<'_>>,
841        has_bang: bool,
842        ident: Option<Ident>,
843        delim: tk::Delimiter,
844        open_spacing: Option<Spacing>,
845        tts: &TokenStream,
846        convert_dollar_crate: bool,
847        span: Span,
848    ) {
849        let cb = (delim == tk::Delimiter::Brace).then(|| self.cbox(INDENT_UNIT));
850        match header {
851            Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
852            Some(MacHeader::Keyword(kw)) => self.word(kw),
853            None => {}
854        }
855        if has_bang {
856            self.word("!");
857        }
858        if let Some(ident) = ident {
859            self.nbsp();
860            self.print_ident(ident);
861        }
862        match delim {
863            tk::Delimiter::Brace => {
864                if header.is_some() || has_bang || ident.is_some() {
865                    self.nbsp();
866                }
867                self.word("{");
868
869                // Respect `Alone`, if provided, and print a space. Unless the list is empty.
870                let open_space = (open_spacing == None || open_spacing == Some(Spacing::Alone))
871                    && !tts.is_empty();
872                if open_space {
873                    self.space();
874                }
875                let ib = self.ibox(0);
876                self.print_tts(tts, convert_dollar_crate);
877                self.end(ib);
878
879                // Use `open_space` for the spacing *before* the closing delim.
880                // Because spacing on delimiters is lost when going through
881                // proc macros, and otherwise we can end up with ugly cases
882                // like `{ x}`. Symmetry is better.
883                self.bclose(span, !open_space, cb.unwrap());
884            }
885            delim => {
886                // `open_spacing` is ignored. We never print spaces after
887                // non-brace opening delims or before non-brace closing delims.
888                let token_str = self.token_kind_to_string(&delim.as_open_token_kind());
889                self.word(token_str);
890                let ib = self.ibox(0);
891                self.print_tts(tts, convert_dollar_crate);
892                self.end(ib);
893                let token_str = self.token_kind_to_string(&delim.as_close_token_kind());
894                self.word(token_str);
895            }
896        }
897    }
898
899    fn print_mac_def(
900        &mut self,
901        macro_def: &ast::MacroDef,
902        ident: &Ident,
903        sp: Span,
904        print_visibility: impl FnOnce(&mut Self),
905    ) {
906        if let Some(eii_decl) = &macro_def.eii_declaration {
907            self.word("#[eii_declaration(");
908            self.print_path(&eii_decl.foreign_item, false, 0);
909            if eii_decl.impl_unsafe {
910                self.word(",");
911                self.space();
912                self.word("unsafe");
913            }
914            self.word(")]");
915            self.hardbreak();
916        }
917        let (kw, has_bang) = if macro_def.macro_rules {
918            ("macro_rules", true)
919        } else {
920            print_visibility(self);
921            ("macro", false)
922        };
923        self.print_mac_common(
924            Some(MacHeader::Keyword(kw)),
925            has_bang,
926            Some(*ident),
927            macro_def.body.delim,
928            None,
929            &macro_def.body.tokens,
930            true,
931            sp,
932        );
933        if macro_def.body.need_semicolon() {
934            self.word(";");
935        }
936    }
937
938    fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
939        self.maybe_print_comment(path.span.lo());
940
941        for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
942            if i > 0 {
943                self.word("::")
944            }
945            self.print_path_segment(segment, colons_before_params);
946        }
947    }
948
949    fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
950        if segment.ident.name != kw::PathRoot {
951            self.print_ident(segment.ident);
952            if let Some(args) = &segment.args {
953                self.print_generic_args(args, colons_before_params);
954            }
955        }
956    }
957
958    fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> (BoxMarker, BoxMarker) {
959        let w = w.into();
960        // Outer-box is consistent.
961        let cb = self.cbox(INDENT_UNIT);
962        // Head-box is inconsistent.
963        let ib = self.ibox(0);
964        // Keyword that starts the head.
965        if !w.is_empty() {
966            self.word_nbsp(w);
967        }
968        (cb, ib)
969    }
970
971    fn bopen(&mut self, ib: BoxMarker) {
972        self.word("{");
973        self.end(ib);
974    }
975
976    fn bclose_maybe_open(&mut self, span: rustc_span::Span, no_space: bool, cb: Option<BoxMarker>) {
977        let has_comment = self.maybe_print_comment(span.hi());
978        if !no_space || has_comment {
979            self.break_offset_if_not_bol(1, -INDENT_UNIT);
980        }
981        self.word("}");
982        if let Some(cb) = cb {
983            self.end(cb);
984        }
985    }
986
987    fn bclose(&mut self, span: rustc_span::Span, no_space: bool, cb: BoxMarker) {
988        let cb = Some(cb);
989        self.bclose_maybe_open(span, no_space, cb)
990    }
991
992    fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
993        if !self.is_beginning_of_line() {
994            self.break_offset(n, off)
995        } else if off != 0 {
996            if let Some(last_token) = self.last_token_still_buffered() {
997                if last_token.is_hardbreak_tok() {
998                    // We do something pretty sketchy here: tuck the nonzero
999                    // offset-adjustment we were going to deposit along with the
1000                    // break into the previous hardbreak.
1001                    self.replace_last_token_still_buffered(pp::Printer::hardbreak_tok_offset(off));
1002                }
1003            }
1004        }
1005    }
1006
1007    /// Print the token kind precisely, without converting `$crate` into its respective crate name.
1008    fn token_kind_to_string(&self, tok: &tk::TokenKind) -> Cow<'static, str> {
1009        self.token_kind_to_string_ext(tok, None)
1010    }
1011
1012    fn token_kind_to_string_ext(
1013        &self,
1014        tok: &tk::TokenKind,
1015        convert_dollar_crate: Option<Span>,
1016    ) -> Cow<'static, str> {
1017        match *tok {
1018            tk::Eq => "=".into(),
1019            tk::Lt => "<".into(),
1020            tk::Le => "<=".into(),
1021            tk::EqEq => "==".into(),
1022            tk::Ne => "!=".into(),
1023            tk::Ge => ">=".into(),
1024            tk::Gt => ">".into(),
1025            tk::Bang => "!".into(),
1026            tk::Tilde => "~".into(),
1027            tk::OrOr => "||".into(),
1028            tk::AndAnd => "&&".into(),
1029            tk::Plus => "+".into(),
1030            tk::Minus => "-".into(),
1031            tk::Star => "*".into(),
1032            tk::Slash => "/".into(),
1033            tk::Percent => "%".into(),
1034            tk::Caret => "^".into(),
1035            tk::And => "&".into(),
1036            tk::Or => "|".into(),
1037            tk::Shl => "<<".into(),
1038            tk::Shr => ">>".into(),
1039            tk::PlusEq => "+=".into(),
1040            tk::MinusEq => "-=".into(),
1041            tk::StarEq => "*=".into(),
1042            tk::SlashEq => "/=".into(),
1043            tk::PercentEq => "%=".into(),
1044            tk::CaretEq => "^=".into(),
1045            tk::AndEq => "&=".into(),
1046            tk::OrEq => "|=".into(),
1047            tk::ShlEq => "<<=".into(),
1048            tk::ShrEq => ">>=".into(),
1049
1050            /* Structural symbols */
1051            tk::At => "@".into(),
1052            tk::Dot => ".".into(),
1053            tk::DotDot => "..".into(),
1054            tk::DotDotDot => "...".into(),
1055            tk::DotDotEq => "..=".into(),
1056            tk::Comma => ",".into(),
1057            tk::Semi => ";".into(),
1058            tk::Colon => ":".into(),
1059            tk::PathSep => "::".into(),
1060            tk::RArrow => "->".into(),
1061            tk::LArrow => "<-".into(),
1062            tk::FatArrow => "=>".into(),
1063            tk::OpenParen => "(".into(),
1064            tk::CloseParen => ")".into(),
1065            tk::OpenBracket => "[".into(),
1066            tk::CloseBracket => "]".into(),
1067            tk::OpenBrace => "{".into(),
1068            tk::CloseBrace => "}".into(),
1069            tk::OpenInvisible(_) | tk::CloseInvisible(_) => "".into(),
1070            tk::Pound => "#".into(),
1071            tk::Dollar => "$".into(),
1072            tk::Question => "?".into(),
1073            tk::SingleQuote => "'".into(),
1074
1075            /* Literals */
1076            tk::Literal(lit) => literal_to_string(lit).into(),
1077
1078            /* Name components */
1079            tk::Ident(name, is_raw) => {
1080                IdentPrinter::new(name, is_raw.to_print_mode_ident(), convert_dollar_crate)
1081                    .to_string()
1082                    .into()
1083            }
1084            tk::NtIdent(ident, is_raw) => {
1085                IdentPrinter::for_ast_ident(ident, is_raw.to_print_mode_ident()).to_string().into()
1086            }
1087
1088            tk::Lifetime(name, is_raw) | tk::NtLifetime(Ident { name, .. }, is_raw) => {
1089                IdentPrinter::new(name, is_raw.to_print_mode_lifetime(), None).to_string().into()
1090            }
1091
1092            /* Other */
1093            tk::DocComment(comment_kind, attr_style, data) => {
1094                doc_comment_to_string(tk::DocFragmentKind::Sugared(comment_kind), attr_style, data)
1095                    .into()
1096            }
1097            tk::Eof => "<eof>".into(),
1098        }
1099    }
1100
1101    /// Print the token precisely, without converting `$crate` into its respective crate name.
1102    fn token_to_string(&self, token: &tk::Token) -> Cow<'static, str> {
1103        self.token_to_string_ext(token, false)
1104    }
1105
1106    fn token_to_string_ext(
1107        &self,
1108        token: &tk::Token,
1109        convert_dollar_crate: bool,
1110    ) -> Cow<'static, str> {
1111        let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
1112        self.token_kind_to_string_ext(&token.kind, convert_dollar_crate)
1113    }
1114
1115    fn ty_to_string(&self, ty: &ast::Ty) -> String {
1116        Self::to_string(|s| s.print_type(ty))
1117    }
1118
1119    fn pat_to_string(&self, pat: &ast::Pat) -> String {
1120        Self::to_string(|s| s.print_pat(pat))
1121    }
1122
1123    fn expr_to_string(&self, e: &ast::Expr) -> String {
1124        Self::to_string(|s| s.print_expr(e, FixupContext::default()))
1125    }
1126
1127    fn meta_item_lit_to_string(&self, lit: &ast::MetaItemLit) -> String {
1128        Self::to_string(|s| s.print_meta_item_lit(lit))
1129    }
1130
1131    fn stmt_to_string(&self, stmt: &ast::Stmt) -> String {
1132        Self::to_string(|s| s.print_stmt(stmt))
1133    }
1134
1135    fn item_to_string(&self, i: &ast::Item) -> String {
1136        Self::to_string(|s| s.print_item(i))
1137    }
1138
1139    fn assoc_item_to_string(&self, i: &ast::AssocItem) -> String {
1140        Self::to_string(|s| s.print_assoc_item(i))
1141    }
1142
1143    fn foreign_item_to_string(&self, i: &ast::ForeignItem) -> String {
1144        Self::to_string(|s| s.print_foreign_item(i))
1145    }
1146
1147    fn path_to_string(&self, p: &ast::Path) -> String {
1148        Self::to_string(|s| s.print_path(p, false, 0))
1149    }
1150
1151    fn vis_to_string(&self, v: &ast::Visibility) -> String {
1152        Self::to_string(|s| s.print_visibility(v))
1153    }
1154
1155    fn impl_restriction_to_string(&self, r: &ast::ImplRestriction) -> String {
1156        Self::to_string(|s| s.print_impl_restriction(r))
1157    }
1158
1159    fn mut_restriction_to_string(&self, r: &ast::MutRestriction) -> String {
1160        Self::to_string(|s| s.print_mut_restriction(r))
1161    }
1162
1163    fn block_to_string(&self, blk: &ast::Block) -> String {
1164        Self::to_string(|s| {
1165            let (cb, ib) = s.head("");
1166            s.print_block(blk, cb, ib)
1167        })
1168    }
1169
1170    fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String {
1171        Self::to_string(|s| s.print_attr_item(ai, ai.path.span))
1172    }
1173
1174    fn tts_to_string(&self, tokens: &TokenStream) -> String {
1175        Self::to_string(|s| s.print_tts(tokens, false))
1176    }
1177
1178    fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
1179        let mut printer = State::new();
1180        f(&mut printer);
1181        printer.s.eof()
1182    }
1183}
1184
1185impl<'a> PrintState<'a> for State<'a> {
1186    fn comments(&self) -> Option<&Comments<'a>> {
1187        self.comments.as_ref()
1188    }
1189
1190    fn comments_mut(&mut self) -> Option<&mut Comments<'a>> {
1191        self.comments.as_mut()
1192    }
1193
1194    fn ann_post(&mut self, ident: Ident) {
1195        self.ann.post(self, AnnNode::Ident(&ident));
1196    }
1197
1198    fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
1199        if colons_before_params {
1200            self.word("::")
1201        }
1202
1203        match args {
1204            ast::GenericArgs::AngleBracketed(data) => {
1205                self.word("<");
1206                self.commasep(Inconsistent, &data.args, |s, arg| match arg {
1207                    ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
1208                    ast::AngleBracketedArg::Constraint(c) => s.print_assoc_item_constraint(c),
1209                });
1210                self.word(">")
1211            }
1212
1213            ast::GenericArgs::Parenthesized(data) => {
1214                self.word("(");
1215                self.commasep(Inconsistent, &data.inputs, |s, param| s.print_param(param, false));
1216                self.word(")");
1217                self.print_fn_ret_ty(&data.output);
1218            }
1219            ast::GenericArgs::ParenthesizedElided(_) => {
1220                self.word("(");
1221                self.word("..");
1222                self.word(")");
1223            }
1224        }
1225    }
1226}
1227
1228impl<'a> State<'a> {
1229    pub fn new() -> State<'a> {
1230        State { s: pp::Printer::new(), comments: None, ann: &NoAnn, is_sdylib_interface: false }
1231    }
1232
1233    fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
1234    where
1235        F: FnMut(&mut State<'_>, &T),
1236        G: FnMut(&T) -> rustc_span::Span,
1237    {
1238        let rb = self.rbox(0, b);
1239        let len = elts.len();
1240        let mut i = 0;
1241        for elt in elts {
1242            self.maybe_print_comment(get_span(elt).hi());
1243            op(self, elt);
1244            i += 1;
1245            if i < len {
1246                self.word(",");
1247                self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
1248                self.space_if_not_bol();
1249            }
1250        }
1251        self.end(rb);
1252    }
1253
1254    fn commasep_exprs(&mut self, b: Breaks, exprs: &[Box<ast::Expr>]) {
1255        self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e, FixupContext::default()), |e| e.span)
1256    }
1257
1258    pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
1259        if let Some(lt) = *lifetime {
1260            self.print_lifetime(lt);
1261            self.nbsp();
1262        }
1263    }
1264
1265    fn print_view(&mut self, fields: &[Ident]) {
1266        self.word(".{");
1267
1268        if !fields.is_empty() {
1269            self.space();
1270            self.commasep(Consistent, fields, |s, field| {
1271                s.print_ident(*field);
1272            });
1273            self.space();
1274        }
1275
1276        self.word("}");
1277    }
1278
1279    pub fn print_assoc_item_constraint(&mut self, constraint: &ast::AssocItemConstraint) {
1280        self.print_ident(constraint.ident);
1281        if let Some(args) = constraint.gen_args.as_ref() {
1282            self.print_generic_args(args, false)
1283        }
1284        self.space();
1285        match &constraint.kind {
1286            ast::AssocItemConstraintKind::Equality { term } => {
1287                self.word_space("=");
1288                match term {
1289                    Term::Ty(ty) => self.print_type(ty),
1290                    Term::Const(c) => self.print_expr_anon_const(c, &[]),
1291                }
1292            }
1293            ast::AssocItemConstraintKind::Bound { bounds } => {
1294                if !bounds.is_empty() {
1295                    self.word_nbsp(":");
1296                    self.print_type_bounds(bounds);
1297                }
1298            }
1299        }
1300    }
1301
1302    pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
1303        match generic_arg {
1304            GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1305            GenericArg::Type(ty) => self.print_type(ty),
1306            GenericArg::Const(ct) => self.print_expr(&ct.value, FixupContext::default()),
1307        }
1308    }
1309
1310    pub fn print_ty_pat(&mut self, pat: &ast::TyPat) {
1311        match &pat.kind {
1312            rustc_ast::TyPatKind::Range(start, end, include_end) => {
1313                if let Some(start) = start {
1314                    self.print_expr_anon_const(start, &[]);
1315                }
1316                self.word("..");
1317                if let Some(end) = end {
1318                    if let RangeEnd::Included(_) = include_end.node {
1319                        self.word("=");
1320                    }
1321                    self.print_expr_anon_const(end, &[]);
1322                }
1323            }
1324            rustc_ast::TyPatKind::NotNull => self.word("!null"),
1325            rustc_ast::TyPatKind::Or(variants) => {
1326                let mut first = true;
1327                for pat in variants {
1328                    if first {
1329                        first = false
1330                    } else {
1331                        self.word(" | ");
1332                    }
1333                    self.print_ty_pat(pat);
1334                }
1335            }
1336            rustc_ast::TyPatKind::Err(_) => {
1337                self.popen();
1338                self.word("/*ERROR*/");
1339                self.pclose();
1340            }
1341        }
1342    }
1343
1344    pub fn print_type(&mut self, ty: &ast::Ty) {
1345        self.maybe_print_comment(ty.span.lo());
1346        let ib = self.ibox(0);
1347        match &ty.kind {
1348            ast::TyKind::Slice(ty) => {
1349                self.word("[");
1350                self.print_type(ty);
1351                self.word("]");
1352            }
1353            ast::TyKind::Ptr(mt) => {
1354                self.word("*");
1355                self.print_mt(mt, true);
1356            }
1357            ast::TyKind::Ref(lifetime, mt) => {
1358                self.word("&");
1359                self.print_opt_lifetime(lifetime);
1360                self.print_mt(mt, false);
1361            }
1362            ast::TyKind::PinnedRef(lifetime, mt) => {
1363                self.word("&");
1364                self.print_opt_lifetime(lifetime);
1365                self.word("pin ");
1366                self.print_mt(mt, true);
1367            }
1368            ast::TyKind::Never => {
1369                self.word("!");
1370            }
1371            ast::TyKind::Tup(elts) => {
1372                self.popen();
1373                self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
1374                if elts.len() == 1 {
1375                    self.word(",");
1376                }
1377                self.pclose();
1378            }
1379            ast::TyKind::Paren(typ) => {
1380                self.popen();
1381                self.print_type(typ);
1382                self.pclose();
1383            }
1384            ast::TyKind::FnPtr(f) => {
1385                self.print_ty_fn(f.ext, f.safety, &f.decl, None, &f.generic_params);
1386            }
1387            ast::TyKind::UnsafeBinder(f) => {
1388                let ib = self.ibox(INDENT_UNIT);
1389                self.word("unsafe");
1390                self.print_generic_params(&f.generic_params);
1391                self.nbsp();
1392                self.print_type(&f.inner_ty);
1393                self.end(ib);
1394            }
1395            ast::TyKind::Path(None, path) => {
1396                self.print_path(path, false, 0);
1397            }
1398            ast::TyKind::Path(Some(qself), path) => self.print_qpath(path, qself, false),
1399            ast::TyKind::TraitObject(bounds, syntax) => {
1400                match syntax {
1401                    ast::TraitObjectSyntax::Dyn => self.word_nbsp("dyn"),
1402                    ast::TraitObjectSyntax::None => {}
1403                }
1404                self.print_type_bounds(bounds);
1405            }
1406            ast::TyKind::ImplTrait(_, bounds) => {
1407                self.word_nbsp("impl");
1408                self.print_type_bounds(bounds);
1409            }
1410            ast::TyKind::Array(ty, length) => {
1411                self.word("[");
1412                self.print_type(ty);
1413                self.word("; ");
1414                self.print_expr(&length.value, FixupContext::default());
1415                self.word("]");
1416            }
1417            ast::TyKind::Infer => {
1418                self.word("_");
1419            }
1420            ast::TyKind::Err(_) => {
1421                self.popen();
1422                self.word("/*ERROR*/");
1423                self.pclose();
1424            }
1425            ast::TyKind::Dummy => {
1426                self.popen();
1427                self.word("/*DUMMY*/");
1428                self.pclose();
1429            }
1430            ast::TyKind::ImplicitSelf => {
1431                self.word("Self");
1432            }
1433            ast::TyKind::MacCall(m) => {
1434                self.print_mac(m);
1435            }
1436            ast::TyKind::CVarArgs => {
1437                self.word("...");
1438            }
1439            ast::TyKind::Pat(ty, pat) => {
1440                self.print_type(ty);
1441                self.word(" is ");
1442                self.print_ty_pat(pat);
1443            }
1444            ast::TyKind::FieldOf(ty, variant, field) => {
1445                self.word("builtin # field_of");
1446                self.popen();
1447                let ib = self.ibox(0);
1448                self.print_type(ty);
1449                self.word(",");
1450                self.space();
1451
1452                if let Some(variant) = variant {
1453                    self.print_ident(*variant);
1454                    self.word(".");
1455                }
1456                self.print_ident(*field);
1457
1458                self.end(ib);
1459                self.pclose();
1460            }
1461            ast::TyKind::View(ty, fields) => {
1462                self.print_type(ty);
1463                self.print_view(fields);
1464            }
1465            ast::TyKind::DirectConstArg(expr) => {
1466                self.word_nbsp("core::direct_const_arg!");
1467                self.popen();
1468                self.print_expr(expr, FixupContext::default());
1469                self.pclose();
1470            }
1471        }
1472        self.end(ib);
1473    }
1474
1475    fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1476        self.print_path(&t.path, false, 0)
1477    }
1478
1479    fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1480        if !generic_params.is_empty() {
1481            self.word("for");
1482            self.print_generic_params(generic_params);
1483            self.nbsp();
1484        }
1485    }
1486
1487    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1488        if let ast::Parens::Yes = t.parens {
1489            self.popen();
1490        }
1491        self.print_formal_generic_params(&t.bound_generic_params);
1492
1493        let ast::TraitBoundModifiers { constness, asyncness, polarity } = t.modifiers;
1494        match constness {
1495            ast::BoundConstness::Never => {}
1496            ast::BoundConstness::Always(_) | ast::BoundConstness::Maybe(_) => {
1497                self.word_space(constness.as_str());
1498            }
1499        }
1500        match asyncness {
1501            ast::BoundAsyncness::Normal => {}
1502            ast::BoundAsyncness::Async(_) => {
1503                self.word_space(asyncness.as_str());
1504            }
1505        }
1506        match polarity {
1507            ast::BoundPolarity::Positive => {}
1508            ast::BoundPolarity::Negative(_) | ast::BoundPolarity::Maybe(_) => {
1509                self.word(polarity.as_str());
1510            }
1511        }
1512
1513        self.print_trait_ref(&t.trait_ref);
1514        if let ast::Parens::Yes = t.parens {
1515            self.pclose();
1516        }
1517    }
1518
1519    fn print_stmt(&mut self, st: &ast::Stmt) {
1520        self.maybe_print_comment(st.span.lo());
1521        match &st.kind {
1522            ast::StmtKind::Let(loc) => {
1523                self.print_outer_attributes(&loc.attrs);
1524                self.space_if_not_bol();
1525                let ib1 = self.ibox(INDENT_UNIT);
1526                if loc.super_.is_some() {
1527                    self.word_nbsp("super");
1528                }
1529                self.word_nbsp("let");
1530
1531                let ib2 = self.ibox(INDENT_UNIT);
1532                self.print_local_decl(loc);
1533                self.end(ib2);
1534                if let Some((init, els)) = loc.kind.init_else_opt() {
1535                    self.nbsp();
1536                    self.word_space("=");
1537                    self.print_expr_cond_paren(
1538                        init,
1539                        els.is_some() && classify::expr_trailing_brace(init).is_some(),
1540                        FixupContext::default(),
1541                    );
1542                    if let Some(els) = els {
1543                        let cb = self.cbox(INDENT_UNIT);
1544                        let ib = self.ibox(INDENT_UNIT);
1545                        self.word(" else ");
1546                        self.print_block(els, cb, ib);
1547                    }
1548                }
1549                self.word(";");
1550                self.end(ib1);
1551            }
1552            ast::StmtKind::Item(item) => self.print_item(item),
1553            ast::StmtKind::Expr(expr) => {
1554                self.space_if_not_bol();
1555                self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1556                if classify::expr_requires_semi_to_be_stmt(expr) {
1557                    self.word(";");
1558                }
1559            }
1560            ast::StmtKind::Semi(expr) => {
1561                self.space_if_not_bol();
1562                self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1563                self.word(";");
1564            }
1565            ast::StmtKind::Empty => {
1566                self.space_if_not_bol();
1567                self.word(";");
1568            }
1569            ast::StmtKind::MacCall(mac) => {
1570                self.space_if_not_bol();
1571                self.print_outer_attributes(&mac.attrs);
1572                self.print_mac(&mac.mac);
1573                if mac.style == ast::MacStmtStyle::Semicolon {
1574                    self.word(";");
1575                }
1576            }
1577        }
1578        self.maybe_print_trailing_comment(st.span, None)
1579    }
1580
1581    fn print_block(&mut self, blk: &ast::Block, cb: BoxMarker, ib: BoxMarker) {
1582        self.print_block_with_attrs(blk, &[], cb, ib)
1583    }
1584
1585    fn print_block_unclosed_indent(&mut self, blk: &ast::Block, ib: BoxMarker) {
1586        self.print_block_maybe_unclosed(blk, &[], None, ib)
1587    }
1588
1589    fn print_block_with_attrs(
1590        &mut self,
1591        blk: &ast::Block,
1592        attrs: &[ast::Attribute],
1593        cb: BoxMarker,
1594        ib: BoxMarker,
1595    ) {
1596        self.print_block_maybe_unclosed(blk, attrs, Some(cb), ib)
1597    }
1598
1599    fn print_block_maybe_unclosed(
1600        &mut self,
1601        blk: &ast::Block,
1602        attrs: &[ast::Attribute],
1603        cb: Option<BoxMarker>,
1604        ib: BoxMarker,
1605    ) {
1606        match blk.rules {
1607            BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1608            BlockCheckMode::Default => (),
1609        }
1610        self.maybe_print_comment(blk.span.lo());
1611        self.ann.pre(self, AnnNode::Block(blk));
1612        self.bopen(ib);
1613
1614        let has_attrs = self.print_inner_attributes(attrs);
1615
1616        for (i, st) in blk.stmts.iter().enumerate() {
1617            match &st.kind {
1618                ast::StmtKind::Expr(expr) if i == blk.stmts.len() - 1 => {
1619                    self.maybe_print_comment(st.span.lo());
1620                    self.space_if_not_bol();
1621                    self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1622                    self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1623                }
1624                _ => self.print_stmt(st),
1625            }
1626        }
1627
1628        let no_space = !has_attrs && blk.stmts.is_empty();
1629        self.bclose_maybe_open(blk.span, no_space, cb);
1630        self.ann.post(self, AnnNode::Block(blk))
1631    }
1632
1633    /// Print a `let pat = expr` expression.
1634    ///
1635    /// Parentheses are inserted surrounding `expr` if a round-trip through the
1636    /// parser would otherwise work out the wrong way in a condition position.
1637    ///
1638    /// For example each of the following would mean the wrong thing without
1639    /// parentheses.
1640    ///
1641    /// ```ignore (illustrative)
1642    /// if let _ = (Struct {}) {}
1643    ///
1644    /// if let _ = (true && false) {}
1645    /// ```
1646    ///
1647    /// In a match guard, the second case still requires parens, but the first
1648    /// case no longer does because anything until `=>` is considered part of
1649    /// the match guard expression. Parsing of the expression is not terminated
1650    /// by `{` in that position.
1651    ///
1652    /// ```ignore (illustrative)
1653    /// match () {
1654    ///     () if let _ = Struct {} => {}
1655    ///     () if let _ = (true && false) => {}
1656    /// }
1657    /// ```
1658    fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, fixup: FixupContext) {
1659        self.word("let ");
1660        self.print_pat(pat);
1661        self.space();
1662        self.word_space("=");
1663        self.print_expr_cond_paren(
1664            expr,
1665            fixup.needs_par_as_let_scrutinee(expr),
1666            FixupContext::default(),
1667        );
1668    }
1669
1670    fn print_mac(&mut self, m: &ast::MacCall) {
1671        self.print_mac_common(
1672            Some(MacHeader::Path(&m.path)),
1673            true,
1674            None,
1675            m.args.delim,
1676            None,
1677            &m.args.tokens,
1678            true,
1679            m.span(),
1680        );
1681    }
1682
1683    fn inline_asm_template_and_operands<'asm>(
1684        asm: &'asm ast::InlineAsm,
1685    ) -> (String, Vec<&'asm InlineAsmOperand>) {
1686        fn is_explicit_reg(op: &InlineAsmOperand) -> bool {
1687            match op {
1688                InlineAsmOperand::In { reg, .. }
1689                | InlineAsmOperand::Out { reg, .. }
1690                | InlineAsmOperand::InOut { reg, .. }
1691                | InlineAsmOperand::SplitInOut { reg, .. } => {
1692                    #[allow(non_exhaustive_omitted_patterns)] match reg {
    InlineAsmRegOrRegClass::Reg(_) => true,
    _ => false,
}matches!(reg, InlineAsmRegOrRegClass::Reg(_))
1693                }
1694                InlineAsmOperand::Const { .. }
1695                | InlineAsmOperand::Sym { .. }
1696                | InlineAsmOperand::Label { .. } => false,
1697            }
1698        }
1699
1700        // After macro expansion, named operands become positional. The grammar
1701        // requires positional operands to precede explicit register operands,
1702        // so we must reorder when any non-explicit operand follows an explicit
1703        // one. When no reordering is needed, we use the original template
1704        // string and operand order to avoid duplicating the Display logic in
1705        // InlineAsmTemplatePiece.
1706        let needs_reorder = {
1707            let mut seen_explicit = false;
1708            asm.operands.iter().any(|(op, _)| {
1709                if is_explicit_reg(op) {
1710                    seen_explicit = true;
1711                    false
1712                } else {
1713                    seen_explicit
1714                }
1715            })
1716        };
1717
1718        if !needs_reorder {
1719            let template = InlineAsmTemplatePiece::to_string(&asm.template);
1720            let operands = asm.operands.iter().map(|(op, _)| op).collect();
1721            return (template, operands);
1722        }
1723
1724        let mut non_explicit = Vec::new();
1725        let mut explicit = Vec::new();
1726        for (i, (op, _)) in asm.operands.iter().enumerate() {
1727            if is_explicit_reg(op) {
1728                explicit.push(i);
1729            } else {
1730                non_explicit.push(i);
1731            }
1732        }
1733        let order = non_explicit.into_iter().chain(explicit).collect::<Vec<_>>();
1734
1735        // Build old-index -> new-index mapping for template renumbering.
1736        let mut old_to_new = ::alloc::vec::from_elem(0usize, asm.operands.len())vec![0usize; asm.operands.len()];
1737        for (new_idx, old_idx) in order.iter().copied().enumerate() {
1738            old_to_new[old_idx] = new_idx;
1739        }
1740
1741        // Remap template placeholder indices and reuse the existing Display
1742        // impl to build the template string.
1743        let remapped = asm
1744            .template
1745            .iter()
1746            .map(|piece| match piece {
1747                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } => {
1748                    InlineAsmTemplatePiece::Placeholder {
1749                        operand_idx: old_to_new[*operand_idx],
1750                        modifier: *modifier,
1751                        span: *span,
1752                    }
1753                }
1754                other => other.clone(),
1755            })
1756            .collect::<Vec<_>>();
1757        let template = InlineAsmTemplatePiece::to_string(&remapped);
1758        let operands = order.iter().map(|&idx| &asm.operands[idx].0).collect();
1759        (template, operands)
1760    }
1761
1762    fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
1763        enum AsmArg<'a> {
1764            Template(String),
1765            Operand(&'a InlineAsmOperand),
1766            ClobberAbi(Symbol),
1767            Options(InlineAsmOptions),
1768        }
1769
1770        let (template, operands) = Self::inline_asm_template_and_operands(asm);
1771        let mut args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [AsmArg::Template(template)]))vec![AsmArg::Template(template)];
1772        args.extend(operands.into_iter().map(AsmArg::Operand));
1773        for (abi, _) in &asm.clobber_abis {
1774            args.push(AsmArg::ClobberAbi(*abi));
1775        }
1776        if !asm.options.is_empty() {
1777            args.push(AsmArg::Options(asm.options));
1778        }
1779
1780        self.popen();
1781        self.commasep(Consistent, &args, |s, arg| match arg {
1782            AsmArg::Template(template) => s.print_string(template, ast::StrStyle::Cooked),
1783            AsmArg::Operand(op) => {
1784                let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
1785                    InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
1786                    InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
1787                };
1788                match op {
1789                    InlineAsmOperand::In { reg, expr } => {
1790                        s.word("in");
1791                        s.popen();
1792                        print_reg_or_class(s, reg);
1793                        s.pclose();
1794                        s.space();
1795                        s.print_expr(expr, FixupContext::default());
1796                    }
1797                    InlineAsmOperand::Out { reg, late, expr } => {
1798                        s.word(if *late { "lateout" } else { "out" });
1799                        s.popen();
1800                        print_reg_or_class(s, reg);
1801                        s.pclose();
1802                        s.space();
1803                        match expr {
1804                            Some(expr) => s.print_expr(expr, FixupContext::default()),
1805                            None => s.word("_"),
1806                        }
1807                    }
1808                    InlineAsmOperand::InOut { reg, late, expr } => {
1809                        s.word(if *late { "inlateout" } else { "inout" });
1810                        s.popen();
1811                        print_reg_or_class(s, reg);
1812                        s.pclose();
1813                        s.space();
1814                        s.print_expr(expr, FixupContext::default());
1815                    }
1816                    InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1817                        s.word(if *late { "inlateout" } else { "inout" });
1818                        s.popen();
1819                        print_reg_or_class(s, reg);
1820                        s.pclose();
1821                        s.space();
1822                        s.print_expr(in_expr, FixupContext::default());
1823                        s.space();
1824                        s.word_space("=>");
1825                        match out_expr {
1826                            Some(out_expr) => s.print_expr(out_expr, FixupContext::default()),
1827                            None => s.word("_"),
1828                        }
1829                    }
1830                    InlineAsmOperand::Const { anon_const } => {
1831                        s.word("const");
1832                        s.space();
1833                        s.print_expr(&anon_const.value, FixupContext::default());
1834                    }
1835                    InlineAsmOperand::Sym { sym } => {
1836                        s.word("sym");
1837                        s.space();
1838                        if let Some(qself) = &sym.qself {
1839                            s.print_qpath(&sym.path, qself, true);
1840                        } else {
1841                            s.print_path(&sym.path, true, 0);
1842                        }
1843                    }
1844                    InlineAsmOperand::Label { block } => {
1845                        let (cb, ib) = s.head("label");
1846                        s.print_block(block, cb, ib);
1847                    }
1848                }
1849            }
1850            AsmArg::ClobberAbi(abi) => {
1851                s.word("clobber_abi");
1852                s.popen();
1853                s.print_symbol(*abi, ast::StrStyle::Cooked);
1854                s.pclose();
1855            }
1856            AsmArg::Options(opts) => {
1857                s.word("options");
1858                s.popen();
1859                s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| {
1860                    s.word(opt);
1861                });
1862                s.pclose();
1863            }
1864        });
1865        self.pclose();
1866    }
1867
1868    fn print_local_decl(&mut self, loc: &ast::Local) {
1869        self.print_pat(&loc.pat);
1870        if let Some(ty) = &loc.ty {
1871            self.word_space(":");
1872            self.print_type(ty);
1873        }
1874    }
1875
1876    fn print_name(&mut self, name: Symbol) {
1877        self.word(name.to_string());
1878        self.ann.post(self, AnnNode::Name(&name))
1879    }
1880
1881    fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
1882        self.word("<");
1883        self.print_type(&qself.ty);
1884        if qself.position > 0 {
1885            self.space();
1886            self.word_space("as");
1887            let depth = path.segments.len() - qself.position;
1888            self.print_path(path, false, depth);
1889        }
1890        self.word(">");
1891        for item_segment in &path.segments[qself.position..] {
1892            self.word("::");
1893            self.print_ident(item_segment.ident);
1894            if let Some(args) = &item_segment.args {
1895                self.print_generic_args(args, colons_before_params)
1896            }
1897        }
1898    }
1899
1900    /// Print a pattern, parenthesizing it if it is an or-pattern (`A | B`).
1901    ///
1902    /// Or-patterns have the lowest precedence among patterns, so they need
1903    /// parentheses when nested inside `@` bindings, `&` references, or `box`
1904    /// patterns — otherwise `x @ A | B` parses as `(x @ A) | B`, `&A | B`
1905    /// parses as `(&A) | B`, etc.
1906    fn print_pat_paren_if_or(&mut self, pat: &ast::Pat) {
1907        let needs_paren = #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
    PatKind::Or(..) => true,
    _ => false,
}matches!(pat.kind, PatKind::Or(..));
1908        if needs_paren {
1909            self.popen();
1910        }
1911        self.print_pat(pat);
1912        if needs_paren {
1913            self.pclose();
1914        }
1915    }
1916
1917    fn print_pat(&mut self, pat: &ast::Pat) {
1918        self.maybe_print_comment(pat.span.lo());
1919        self.ann.pre(self, AnnNode::Pat(pat));
1920        /* Pat isn't normalized, but the beauty of it is that it doesn't matter */
1921        match &pat.kind {
1922            PatKind::Missing => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1923            PatKind::Wild => self.word("_"),
1924            PatKind::Never => self.word("!"),
1925            PatKind::Ident(BindingMode(by_ref, mutbl), ident, sub) => {
1926                if mutbl.is_mut() {
1927                    self.word_nbsp("mut");
1928                }
1929                if let ByRef::Yes(pinnedness, rmutbl) = by_ref {
1930                    self.word_nbsp("ref");
1931                    if pinnedness.is_pinned() {
1932                        self.word_nbsp("pin");
1933                    }
1934                    if rmutbl.is_mut() {
1935                        self.word_nbsp("mut");
1936                    } else if pinnedness.is_pinned() {
1937                        self.word_nbsp("const");
1938                    }
1939                }
1940                self.print_ident(*ident);
1941                if let Some(p) = sub {
1942                    self.space();
1943                    self.word_space("@");
1944                    self.print_pat_paren_if_or(p);
1945                }
1946            }
1947            PatKind::TupleStruct(qself, path, elts) => {
1948                if let Some(qself) = qself {
1949                    self.print_qpath(path, qself, true);
1950                } else {
1951                    self.print_path(path, true, 0);
1952                }
1953                self.popen();
1954                self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1955                self.pclose();
1956            }
1957            PatKind::Or(pats) => {
1958                self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1959            }
1960            PatKind::Path(None, path) => {
1961                self.print_path(path, true, 0);
1962            }
1963            PatKind::Path(Some(qself), path) => {
1964                self.print_qpath(path, qself, false);
1965            }
1966            PatKind::Struct(qself, path, fields, etc) => {
1967                if let Some(qself) = qself {
1968                    self.print_qpath(path, qself, true);
1969                } else {
1970                    self.print_path(path, true, 0);
1971                }
1972                self.nbsp();
1973                self.word("{");
1974                let empty = fields.is_empty() && *etc == ast::PatFieldsRest::None;
1975                if !empty {
1976                    self.space();
1977                }
1978                self.commasep_cmnt(
1979                    Consistent,
1980                    fields,
1981                    |s, f| {
1982                        let cb = s.cbox(INDENT_UNIT);
1983                        if !f.is_shorthand {
1984                            s.print_ident(f.ident);
1985                            s.word_nbsp(":");
1986                        }
1987                        s.print_pat(&f.pat);
1988                        s.end(cb);
1989                    },
1990                    |f| f.pat.span,
1991                );
1992                if let ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) = etc {
1993                    if !fields.is_empty() {
1994                        self.word_space(",");
1995                    }
1996                    self.word("..");
1997                    if let ast::PatFieldsRest::Recovered(_) = etc {
1998                        self.word("/* recovered parse error */");
1999                    }
2000                }
2001                if !empty {
2002                    self.space();
2003                }
2004                self.word("}");
2005            }
2006            PatKind::Tuple(elts) => {
2007                self.popen();
2008                self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2009                if elts.len() == 1 {
2010                    self.word(",");
2011                }
2012                self.pclose();
2013            }
2014            PatKind::Box(inner) => {
2015                self.word("box ");
2016                self.print_pat_paren_if_or(inner);
2017            }
2018            PatKind::Deref(inner) => {
2019                self.word("deref!");
2020                self.popen();
2021                self.print_pat(inner);
2022                self.pclose();
2023            }
2024            PatKind::Ref(inner, pinned, mutbl) => {
2025                self.word("&");
2026                if pinned.is_pinned() {
2027                    self.word("pin ");
2028                    if mutbl.is_not() {
2029                        self.word("const ");
2030                    }
2031                }
2032                if mutbl.is_mut() {
2033                    self.word("mut ");
2034                }
2035                if let PatKind::Ident(ast::BindingMode::MUT, ..) = inner.kind {
2036                    self.popen();
2037                    self.print_pat(inner);
2038                    self.pclose();
2039                } else {
2040                    self.print_pat_paren_if_or(inner);
2041                }
2042            }
2043            PatKind::Expr(e) => self.print_expr(e, FixupContext::default()),
2044            PatKind::Range(begin, end, Spanned { node: end_kind, .. }) => {
2045                if let Some(e) = begin {
2046                    self.print_expr(e, FixupContext::default());
2047                }
2048                match end_kind {
2049                    RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2050                    RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2051                    RangeEnd::Excluded => self.word(".."),
2052                }
2053                if let Some(e) = end {
2054                    self.print_expr(e, FixupContext::default());
2055                }
2056            }
2057            PatKind::Guard(subpat, guard) => {
2058                self.popen();
2059                self.print_pat(subpat);
2060                self.space();
2061                self.word_space("if");
2062                self.print_expr(&guard.cond, FixupContext::default());
2063                self.pclose();
2064            }
2065            PatKind::Slice(elts) => {
2066                self.word("[");
2067                self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2068                self.word("]");
2069            }
2070            PatKind::Rest => self.word(".."),
2071            PatKind::Paren(inner) => {
2072                self.popen();
2073                self.print_pat(inner);
2074                self.pclose();
2075            }
2076            PatKind::MacCall(m) => self.print_mac(m),
2077            PatKind::Err(_) => {
2078                self.popen();
2079                self.word("/*ERROR*/");
2080                self.pclose();
2081            }
2082        }
2083        self.ann.post(self, AnnNode::Pat(pat))
2084    }
2085
2086    fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2087        match &explicit_self.node {
2088            SelfKind::Value(m) => {
2089                self.print_mutability(*m, false);
2090                self.word("self")
2091            }
2092            SelfKind::Region(lt, m) => {
2093                self.word("&");
2094                self.print_opt_lifetime(lt);
2095                self.print_mutability(*m, false);
2096                self.word("self")
2097            }
2098            SelfKind::Pinned(lt, m) => {
2099                self.word("&");
2100                self.print_opt_lifetime(lt);
2101                self.word("pin ");
2102                self.print_mutability(*m, true);
2103                self.word("self")
2104            }
2105            SelfKind::Explicit(typ, m) => {
2106                self.print_mutability(*m, false);
2107                self.word("self");
2108                self.word_space(":");
2109                self.print_type(typ)
2110            }
2111        }
2112    }
2113
2114    fn print_coroutine_kind(&mut self, coroutine_kind: ast::CoroutineKind) {
2115        match coroutine_kind {
2116            ast::CoroutineKind::Gen { .. } => {
2117                self.word_nbsp("gen");
2118            }
2119            ast::CoroutineKind::Async { .. } => {
2120                self.word_nbsp("async");
2121            }
2122            ast::CoroutineKind::AsyncGen { .. } => {
2123                self.word_nbsp("async");
2124                self.word_nbsp("gen");
2125            }
2126        }
2127    }
2128
2129    pub fn print_type_bounds(&mut self, bounds: &[ast::GenericBound]) {
2130        let mut first = true;
2131        for bound in bounds {
2132            if first {
2133                first = false;
2134            } else {
2135                self.nbsp();
2136                self.word_space("+");
2137            }
2138
2139            match bound {
2140                GenericBound::Trait(tref) => {
2141                    self.print_poly_trait_ref(tref);
2142                }
2143                GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2144                GenericBound::Use(args, _) => {
2145                    self.word("use");
2146                    self.word("<");
2147                    self.commasep(Inconsistent, args, |s, arg| match arg {
2148                        ast::PreciseCapturingArg::Arg(p, _) => s.print_path(p, false, 0),
2149                        ast::PreciseCapturingArg::Lifetime(lt) => s.print_lifetime(*lt),
2150                    });
2151                    self.word(">")
2152                }
2153            }
2154        }
2155    }
2156
2157    fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2158        self.word(lifetime.ident.name.to_string());
2159        self.ann_post(lifetime.ident)
2160    }
2161
2162    fn print_lifetime_bounds(&mut self, bounds: &ast::GenericBounds) {
2163        for (i, bound) in bounds.iter().enumerate() {
2164            if i != 0 {
2165                self.word(" + ");
2166            }
2167            match bound {
2168                ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2169                _ => {
2170                    {
    ::core::panicking::panic_fmt(format_args!("expected a lifetime bound, found a trait bound"));
}panic!("expected a lifetime bound, found a trait bound")
2171                }
2172            }
2173        }
2174    }
2175
2176    fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2177        if generic_params.is_empty() {
2178            return;
2179        }
2180
2181        self.word("<");
2182
2183        self.commasep(Inconsistent, generic_params, |s, param| {
2184            s.print_outer_attributes_inline(&param.attrs);
2185
2186            match &param.kind {
2187                ast::GenericParamKind::Lifetime => {
2188                    let lt = ast::Lifetime { id: param.id, ident: param.ident };
2189                    s.print_lifetime(lt);
2190                    if !param.bounds.is_empty() {
2191                        s.word_nbsp(":");
2192                        s.print_lifetime_bounds(&param.bounds)
2193                    }
2194                }
2195                ast::GenericParamKind::Type { default } => {
2196                    s.print_ident(param.ident);
2197                    if !param.bounds.is_empty() {
2198                        s.word_nbsp(":");
2199                        s.print_type_bounds(&param.bounds);
2200                    }
2201                    if let Some(default) = default {
2202                        s.space();
2203                        s.word_space("=");
2204                        s.print_type(default)
2205                    }
2206                }
2207                ast::GenericParamKind::Const { ty, default, .. } => {
2208                    s.word_space("const");
2209                    s.print_ident(param.ident);
2210                    s.space();
2211                    s.word_space(":");
2212                    s.print_type(ty);
2213                    if !param.bounds.is_empty() {
2214                        s.word_nbsp(":");
2215                        s.print_type_bounds(&param.bounds);
2216                    }
2217                    if let Some(default) = default {
2218                        s.space();
2219                        s.word_space("=");
2220                        s.print_expr(&default.value, FixupContext::default());
2221                    }
2222                }
2223            }
2224        });
2225
2226        self.word(">");
2227    }
2228
2229    pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2230        match mutbl {
2231            ast::Mutability::Mut => self.word_nbsp("mut"),
2232            ast::Mutability::Not => {
2233                if print_const {
2234                    self.word_nbsp("const");
2235                }
2236            }
2237        }
2238    }
2239
2240    fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2241        self.print_mutability(mt.mutbl, print_const);
2242        self.print_type(&mt.ty)
2243    }
2244
2245    fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2246        let ib = self.ibox(INDENT_UNIT);
2247
2248        self.print_outer_attributes_inline(&input.attrs);
2249
2250        match input.ty.kind {
2251            ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2252            _ => {
2253                if let Some(eself) = input.to_self() {
2254                    self.print_explicit_self(&eself);
2255                } else {
2256                    if !#[allow(non_exhaustive_omitted_patterns)] match input.pat.kind {
    PatKind::Missing => true,
    _ => false,
}matches!(input.pat.kind, PatKind::Missing) {
2257                        self.print_pat(&input.pat);
2258                        self.word(":");
2259                        self.space();
2260                    }
2261                    self.print_type(&input.ty);
2262                }
2263            }
2264        }
2265        self.end(ib);
2266    }
2267
2268    fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2269        if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2270            self.space_if_not_bol();
2271            let ib = self.ibox(INDENT_UNIT);
2272            self.word_space("->");
2273            self.print_type(ty);
2274            self.end(ib);
2275            self.maybe_print_comment(ty.span.lo());
2276        }
2277    }
2278
2279    fn print_ty_fn(
2280        &mut self,
2281        ext: ast::Extern,
2282        safety: ast::Safety,
2283        decl: &ast::FnDecl,
2284        name: Option<Ident>,
2285        generic_params: &[ast::GenericParam],
2286    ) {
2287        let ib = self.ibox(INDENT_UNIT);
2288        self.print_formal_generic_params(generic_params);
2289        let generics = ast::Generics::default();
2290        let header = ast::FnHeader { safety, ext, ..ast::FnHeader::default() };
2291        self.print_fn(decl, header, name, &generics);
2292        self.end(ib);
2293    }
2294
2295    fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2296        self.print_constness(header.constness);
2297        header.coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind));
2298        self.print_safety(header.safety);
2299
2300        match header.ext {
2301            ast::Extern::None => {}
2302            ast::Extern::Implicit(_) => {
2303                self.word_nbsp("extern");
2304            }
2305            ast::Extern::Explicit(abi, _) => {
2306                self.word_nbsp("extern");
2307                self.print_token_literal(abi.as_token_lit(), abi.span);
2308                self.nbsp();
2309            }
2310        }
2311
2312        self.word("fn")
2313    }
2314
2315    fn print_safety(&mut self, s: ast::Safety) {
2316        match s {
2317            ast::Safety::Default => {}
2318            ast::Safety::Safe(_) => self.word_nbsp("safe"),
2319            ast::Safety::Unsafe(_) => self.word_nbsp("unsafe"),
2320        }
2321    }
2322
2323    fn print_constness(&mut self, s: ast::Const) {
2324        match s {
2325            ast::Const::No => {}
2326            ast::Const::Yes(_) => self.word_nbsp("const"),
2327        }
2328    }
2329
2330    fn print_is_auto(&mut self, s: ast::IsAuto) {
2331        match s {
2332            ast::IsAuto::Yes => self.word_nbsp("auto"),
2333            ast::IsAuto::No => {}
2334        }
2335    }
2336
2337    fn print_meta_item_lit(&mut self, lit: &ast::MetaItemLit) {
2338        self.print_token_literal(lit.as_token_lit(), lit.span)
2339    }
2340
2341    fn print_token_literal(&mut self, token_lit: tk::Lit, span: Span) {
2342        self.maybe_print_comment(span.lo());
2343        self.word(token_lit.to_string())
2344    }
2345
2346    fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
2347        self.print_string(sym.as_str(), style);
2348    }
2349
2350    fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool {
2351        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
2352    }
2353
2354    fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool {
2355        self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
2356    }
2357
2358    fn print_attribute(&mut self, attr: &ast::Attribute) {
2359        self.print_attribute_inline(attr, false);
2360    }
2361
2362    fn print_meta_list_item(&mut self, item: &ast::MetaItemInner) {
2363        match item {
2364            ast::MetaItemInner::MetaItem(mi) => self.print_meta_item(mi),
2365            ast::MetaItemInner::Lit(lit) => self.print_meta_item_lit(lit),
2366        }
2367    }
2368
2369    fn print_meta_item(&mut self, item: &ast::MetaItem) {
2370        let ib = self.ibox(INDENT_UNIT);
2371
2372        match item.unsafety {
2373            ast::Safety::Unsafe(_) => {
2374                self.word("unsafe");
2375                self.popen();
2376            }
2377            ast::Safety::Default | ast::Safety::Safe(_) => {}
2378        }
2379
2380        match &item.kind {
2381            ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
2382            ast::MetaItemKind::NameValue(value) => {
2383                self.print_path(&item.path, false, 0);
2384                self.space();
2385                self.word_space("=");
2386                self.print_meta_item_lit(value);
2387            }
2388            ast::MetaItemKind::List(items) => {
2389                self.print_path(&item.path, false, 0);
2390                self.popen();
2391                self.commasep(Consistent, items, |s, i| s.print_meta_list_item(i));
2392                self.pclose();
2393            }
2394        }
2395
2396        match item.unsafety {
2397            ast::Safety::Unsafe(_) => self.pclose(),
2398            ast::Safety::Default | ast::Safety::Safe(_) => {}
2399        }
2400
2401        self.end(ib);
2402    }
2403
2404    pub(crate) fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String {
2405        Self::to_string(|s| s.print_type_bounds(bounds))
2406    }
2407
2408    pub(crate) fn where_bound_predicate_to_string(
2409        &self,
2410        where_bound_predicate: &ast::WhereBoundPredicate,
2411    ) -> String {
2412        Self::to_string(|s| s.print_where_bound_predicate(where_bound_predicate))
2413    }
2414
2415    pub(crate) fn tt_to_string(&self, tt: &TokenTree) -> String {
2416        Self::to_string(|s| {
2417            s.print_tt(tt, false);
2418        })
2419    }
2420
2421    pub(crate) fn path_segment_to_string(&self, p: &ast::PathSegment) -> String {
2422        Self::to_string(|s| s.print_path_segment(p, false))
2423    }
2424
2425    pub(crate) fn meta_list_item_to_string(&self, li: &ast::MetaItemInner) -> String {
2426        Self::to_string(|s| s.print_meta_list_item(li))
2427    }
2428
2429    pub(crate) fn attribute_to_string(&self, attr: &ast::Attribute) -> String {
2430        Self::to_string(|s| s.print_attribute(attr))
2431    }
2432}