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