Skip to main content

rustc_hir_pretty/
lib.rs

1//! HIR pretty-printing is layered on top of AST pretty-printing. A number of
2//! the definitions in this file have equivalents in `rustc_ast_pretty`.
3
4// tidy-alphabetical-start
5#![recursion_limit = "256"]
6// tidy-alphabetical-end
7
8use std::cell::Cell;
9use std::vec;
10
11use rustc_abi::ExternAbi;
12use rustc_ast as ast;
13use rustc_ast::util::parser::{self, ExprPrecedence, Fixity};
14use rustc_ast::{DUMMY_NODE_ID, DelimArgs};
15use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
16use rustc_ast_pretty::pp::{self, BoxMarker, Breaks};
17use rustc_ast_pretty::pprust::state::MacHeader;
18use rustc_ast_pretty::pprust::{Comments, PrintState};
19use rustc_hir as hir;
20use rustc_hir::attrs::{AttributeKind, PrintAttribute};
21use rustc_hir::{
22    BindingMode, ByRef, ConstArg, ConstArgExprField, ConstArgKind, GenericArg, GenericBound,
23    GenericParam, GenericParamKind, HirId, ImplicitSelfKind, LifetimeParamKind, Node, PatKind,
24    PreciseCapturingArg, RangeEnd, Term, TyFieldPath, TyPatKind,
25};
26use rustc_span::source_map::SourceMap;
27use rustc_span::{DUMMY_SP, FileName, Ident, Span, Spanned, Symbol, kw, sym};
28
29pub fn id_to_string(cx: &dyn rustc_hir::intravisit::HirTyCtxt<'_>, hir_id: HirId) -> String {
30    to_string(&cx, |s| s.print_node(cx.hir_node(hir_id)))
31}
32
33pub enum AnnNode<'a> {
34    Name(&'a Symbol),
35    Block(&'a hir::Block<'a>),
36    Item(&'a hir::Item<'a>),
37    SubItem(HirId),
38    Expr(&'a hir::Expr<'a>),
39    Pat(&'a hir::Pat<'a>),
40    TyPat(&'a hir::TyPat<'a>),
41    Arm(&'a hir::Arm<'a>),
42}
43
44pub enum Nested {
45    Item(hir::ItemId),
46    TraitItem(hir::TraitItemId),
47    ImplItem(hir::ImplItemId),
48    ForeignItem(hir::ForeignItemId),
49    Body(hir::BodyId),
50    BodyParamPat(hir::BodyId, usize),
51}
52
53pub trait PpAnn {
54    fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
55    fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
56    fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
57}
58
59impl PpAnn for &dyn rustc_hir::intravisit::HirTyCtxt<'_> {
60    fn nested(&self, state: &mut State<'_>, nested: Nested) {
61        match nested {
62            Nested::Item(id) => state.print_item(self.hir_item(id)),
63            Nested::TraitItem(id) => state.print_trait_item(self.hir_trait_item(id)),
64            Nested::ImplItem(id) => state.print_impl_item(self.hir_impl_item(id)),
65            Nested::ForeignItem(id) => state.print_foreign_item(self.hir_foreign_item(id)),
66            Nested::Body(id) => state.print_expr(self.hir_body(id).value),
67            Nested::BodyParamPat(id, i) => state.print_pat(self.hir_body(id).params[i].pat),
68        }
69    }
70}
71
72pub struct State<'a> {
73    pub s: pp::Printer,
74    comments: Option<Comments<'a>>,
75    attrs: &'a dyn Fn(HirId) -> &'a [hir::Attribute],
76    ann: &'a (dyn PpAnn + 'a),
77}
78
79impl<'a> State<'a> {
80    fn attrs(&self, id: HirId) -> &'a [hir::Attribute] {
81        (self.attrs)(id)
82    }
83
84    fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
85        let has_attr = |id: HirId| !self.attrs(id).is_empty();
86        expr.precedence(&has_attr)
87    }
88
89    fn print_attrs(&mut self, attrs: &[hir::Attribute]) {
90        if attrs.is_empty() {
91            return;
92        }
93
94        for attr in attrs {
95            self.print_attribute_as_style(attr, ast::AttrStyle::Outer);
96        }
97        self.hardbreak_if_not_bol();
98    }
99
100    /// Print a single attribute as if it has style `style`, disregarding the
101    /// actual style of the attribute.
102    fn print_attribute_as_style(&mut self, attr: &hir::Attribute, style: ast::AttrStyle) {
103        match &attr {
104            hir::Attribute::Unparsed(unparsed) => {
105                self.maybe_print_comment(unparsed.span.lo());
106                match style {
107                    ast::AttrStyle::Inner => self.word("#!["),
108                    ast::AttrStyle::Outer => self.word("#["),
109                }
110                self.print_attr_item(&unparsed, unparsed.span);
111                self.word("]");
112                self.hardbreak()
113            }
114            hir::Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
115                self.word(rustc_ast_pretty::pprust::state::doc_comment_to_string(
116                    *kind, style, *comment,
117                ));
118                self.hardbreak()
119            }
120            hir::Attribute::Parsed(pa) => {
121                match style {
122                    ast::AttrStyle::Inner => self.word("#![attr = "),
123                    ast::AttrStyle::Outer => self.word("#[attr = "),
124                }
125                pa.print_attribute(self);
126                self.word("]");
127                self.hardbreak()
128            }
129        }
130    }
131
132    fn print_attr_item(&mut self, item: &hir::AttrItem, span: Span) {
133        let ib = self.ibox(0);
134        let path = ast::Path {
135            span,
136            segments: item
137                .path
138                .segments
139                .iter()
140                .map(|i| ast::PathSegment {
141                    ident: Ident { name: *i, span: DUMMY_SP },
142                    args: None,
143                    id: DUMMY_NODE_ID,
144                })
145                .collect(),
146        };
147
148        match &item.args {
149            hir::AttrArgs::Delimited(DelimArgs { dspan: _, delim, tokens }) => self
150                .print_mac_common(
151                    Some(MacHeader::Path(&path)),
152                    false,
153                    None,
154                    *delim,
155                    None,
156                    &tokens,
157                    true,
158                    span,
159                ),
160            hir::AttrArgs::Empty => {
161                PrintState::print_path(self, &path, false, 0);
162            }
163            hir::AttrArgs::Eq { eq_span: _, expr } => {
164                PrintState::print_path(self, &path, false, 0);
165                self.space();
166                self.word_space("=");
167                let token_str = self.meta_item_lit_to_string(expr);
168                self.word(token_str);
169            }
170        }
171        self.end(ib);
172    }
173
174    fn print_node(&mut self, node: Node<'_>) {
175        match node {
176            Node::Param(a) => self.print_param(a),
177            Node::Item(a) => self.print_item(a),
178            Node::ForeignItem(a) => self.print_foreign_item(a),
179            Node::TraitItem(a) => self.print_trait_item(a),
180            Node::ImplItem(a) => self.print_impl_item(a),
181            Node::Variant(a) => self.print_variant(a),
182            Node::AnonConst(a) => self.print_anon_const(a),
183            Node::ConstBlock(a) => self.print_inline_const(a),
184            Node::ConstArg(a) => self.print_const_arg(a),
185            Node::Expr(a) => self.print_expr(a),
186            Node::ExprField(a) => self.print_expr_field(a),
187            // FIXME(mgca): proper printing for struct exprs
188            Node::ConstArgExprField(_) => self.word("/* STRUCT EXPR */"),
189            Node::Stmt(a) => self.print_stmt(a),
190            Node::PathSegment(a) => self.print_path_segment(a),
191            Node::Ty(a) => self.print_type(a),
192            Node::AssocItemConstraint(a) => self.print_assoc_item_constraint(a),
193            Node::TraitRef(a) => self.print_trait_ref(a),
194            Node::OpaqueTy(_) => { ::core::panicking::panic_fmt(format_args!("cannot print Node::OpaqueTy")); }panic!("cannot print Node::OpaqueTy"),
195            Node::Pat(a) => self.print_pat(a),
196            Node::TyPat(a) => self.print_ty_pat(a),
197            Node::PatField(a) => self.print_patfield(a),
198            Node::PatExpr(a) => self.print_pat_expr(a),
199            Node::Arm(a) => self.print_arm(a),
200            Node::Infer(_) => self.word("_"),
201            Node::PreciseCapturingNonLifetimeArg(param) => self.print_ident(param.ident),
202            Node::Block(a) => {
203                // Containing cbox, will be closed by print-block at `}`.
204                let cb = self.cbox(INDENT_UNIT);
205                // Head-ibox, will be closed by print-block after `{`.
206                let ib = self.ibox(0);
207                self.print_block(a, cb, ib);
208            }
209            Node::Lifetime(a) => self.print_lifetime(a),
210            Node::GenericParam(_) => {
    ::core::panicking::panic_fmt(format_args!("cannot print Node::GenericParam"));
}panic!("cannot print Node::GenericParam"),
211            Node::Field(_) => { ::core::panicking::panic_fmt(format_args!("cannot print Node::Field")); }panic!("cannot print Node::Field"),
212            // These cases do not carry enough information in the
213            // `hir_map` to reconstruct their full structure for pretty
214            // printing.
215            Node::Ctor(..) => { ::core::panicking::panic_fmt(format_args!("cannot print isolated Ctor")); }panic!("cannot print isolated Ctor"),
216            Node::LetStmt(a) => self.print_local_decl(a),
217            Node::Crate(..) => { ::core::panicking::panic_fmt(format_args!("cannot print Crate")); }panic!("cannot print Crate"),
218            Node::WherePredicate(pred) => self.print_where_predicate(pred),
219            Node::TestBinderForall(_) => {
    ::core::panicking::panic_fmt(format_args!("cannot print Node::TestBinderForall"));
}panic!("cannot print Node::TestBinderForall"),
220            Node::TestBinderExists(_) => {
    ::core::panicking::panic_fmt(format_args!("cannot print Node::TestBinderExists"));
}panic!("cannot print Node::TestBinderExists"),
221            Node::TestBinderBoundTypeConstraint(_) => {
222                {
    ::core::panicking::panic_fmt(format_args!("cannot print Node::TestBinderBoundTypeConstraint"));
}panic!("cannot print Node::TestBinderBoundTypeConstraint")
223            }
224            Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
225            Node::Err(_) => self.word("/*ERROR*/"),
226        }
227    }
228
229    fn print_generic_arg(&mut self, generic_arg: &GenericArg<'_>, elide_lifetimes: bool) {
230        match generic_arg {
231            GenericArg::Lifetime(lt) if !elide_lifetimes => self.print_lifetime(lt),
232            GenericArg::Lifetime(_) => {}
233            GenericArg::Type(ty) => self.print_type(ty.as_unambig_ty()),
234            GenericArg::Const(ct) => self.print_const_arg(ct.as_unambig_ct()),
235            GenericArg::Infer(_inf) => self.word("_"),
236        }
237    }
238}
239
240impl std::ops::Deref for State<'_> {
241    type Target = pp::Printer;
242    fn deref(&self) -> &Self::Target {
243        &self.s
244    }
245}
246
247impl std::ops::DerefMut for State<'_> {
248    fn deref_mut(&mut self) -> &mut Self::Target {
249        &mut self.s
250    }
251}
252
253impl<'a> PrintState<'a> for State<'a> {
254    fn comments(&self) -> Option<&Comments<'a>> {
255        self.comments.as_ref()
256    }
257
258    fn comments_mut(&mut self) -> Option<&mut Comments<'a>> {
259        self.comments.as_mut()
260    }
261
262    fn ann_post(&mut self, ident: Ident) {
263        self.ann.post(self, AnnNode::Name(&ident.name));
264    }
265
266    fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
267        {
    ::core::panicking::panic_fmt(format_args!("AST generic args printed by HIR pretty-printer"));
};panic!("AST generic args printed by HIR pretty-printer");
268    }
269}
270
271const INDENT_UNIT: isize = 4;
272
273/// Requires you to pass an input filename and reader so that
274/// it can scan the input text for comments to copy forward.
275pub fn print_crate<'a>(
276    sm: &'a SourceMap,
277    krate: &hir::Mod<'_>,
278    filename: FileName,
279    input: String,
280    attrs: &'a dyn Fn(HirId) -> &'a [hir::Attribute],
281    ann: &'a dyn PpAnn,
282) -> String {
283    let mut s = State {
284        s: pp::Printer::new(),
285        comments: Some(Comments::new(sm, filename, input)),
286        attrs,
287        ann,
288    };
289
290    // Print all attributes, regardless of actual style, as inner attributes
291    // since this is the crate root with nothing above it to print outer
292    // attributes.
293    for attr in s.attrs(hir::CRATE_HIR_ID) {
294        s.print_attribute_as_style(attr, ast::AttrStyle::Inner);
295    }
296
297    // When printing the AST, we sometimes need to inject `#[no_std]` here.
298    // Since you can't compile the HIR, it's not necessary.
299
300    s.print_mod(krate);
301    s.print_remaining_comments();
302    s.s.eof()
303}
304
305fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
306where
307    F: FnOnce(&mut State<'_>),
308{
309    let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
310    f(&mut printer);
311    printer.s.eof()
312}
313
314pub fn attribute_to_string(ann: &dyn PpAnn, attr: &hir::Attribute) -> String {
315    to_string(ann, |s| s.print_attribute_as_style(attr, ast::AttrStyle::Outer))
316}
317
318pub fn ty_to_string(ann: &dyn PpAnn, ty: &hir::Ty<'_>) -> String {
319    to_string(ann, |s| s.print_type(ty))
320}
321
322pub fn qpath_to_string(ann: &dyn PpAnn, segment: &hir::QPath<'_>) -> String {
323    to_string(ann, |s| s.print_qpath(segment, false))
324}
325
326pub fn pat_to_string(ann: &dyn PpAnn, pat: &hir::Pat<'_>) -> String {
327    to_string(ann, |s| s.print_pat(pat))
328}
329
330pub fn expr_to_string(ann: &dyn PpAnn, pat: &hir::Expr<'_>) -> String {
331    to_string(ann, |s| s.print_expr(pat))
332}
333
334pub fn item_to_string(ann: &dyn PpAnn, pat: &hir::Item<'_>) -> String {
335    to_string(ann, |s| s.print_item(pat))
336}
337
338impl<'a> State<'a> {
339    fn bclose_maybe_open(&mut self, span: rustc_span::Span, cb: Option<BoxMarker>) {
340        self.maybe_print_comment(span.hi());
341        self.break_offset_if_not_bol(1, -INDENT_UNIT);
342        self.word("}");
343        if let Some(cb) = cb {
344            self.end(cb);
345        }
346    }
347
348    fn bclose(&mut self, span: rustc_span::Span, cb: BoxMarker) {
349        self.bclose_maybe_open(span, Some(cb))
350    }
351
352    fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
353    where
354        F: FnMut(&mut State<'_>, &T),
355        G: FnMut(&T) -> rustc_span::Span,
356    {
357        let rb = self.rbox(0, b);
358        let len = elts.len();
359        let mut i = 0;
360        for elt in elts {
361            self.maybe_print_comment(get_span(elt).hi());
362            op(self, elt);
363            i += 1;
364            if i < len {
365                self.word(",");
366                self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
367                self.space_if_not_bol();
368            }
369        }
370        self.end(rb);
371    }
372
373    fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
374        self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
375    }
376
377    fn print_mod(&mut self, _mod: &hir::Mod<'_>) {
378        for &item_id in _mod.item_ids {
379            self.ann.nested(self, Nested::Item(item_id));
380        }
381    }
382
383    fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
384        if !lifetime.is_elided() {
385            self.print_lifetime(lifetime);
386            self.nbsp();
387        }
388    }
389
390    fn print_type(&mut self, ty: &hir::Ty<'_>) {
391        self.maybe_print_comment(ty.span.lo());
392        let ib = self.ibox(0);
393        match ty.kind {
394            hir::TyKind::Slice(ty) => {
395                self.word("[");
396                self.print_type(ty);
397                self.word("]");
398            }
399            hir::TyKind::Ptr(ref mt) => {
400                self.word("*");
401                self.print_mt(mt, true);
402            }
403            hir::TyKind::Ref(lifetime, ref mt) => {
404                self.word("&");
405                self.print_opt_lifetime(lifetime);
406                self.print_mt(mt, false);
407            }
408            hir::TyKind::Never => {
409                self.word("!");
410            }
411            hir::TyKind::Tup(elts) => {
412                self.popen();
413                self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
414                if elts.len() == 1 {
415                    self.word(",");
416                }
417                self.pclose();
418            }
419            hir::TyKind::FnPtr(f) => {
420                self.print_ty_fn(f.abi, f.safety, f.decl, None, f.generic_params, f.param_idents);
421            }
422            hir::TyKind::UnsafeBinder(unsafe_binder) => {
423                self.print_unsafe_binder(unsafe_binder);
424            }
425            hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
426            hir::TyKind::TraitAscription(bounds) => {
427                self.print_bounds("impl", bounds);
428            }
429            hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
430            hir::TyKind::TraitObject(bounds, lifetime) => {
431                let syntax = lifetime.tag();
432                match syntax {
433                    ast::TraitObjectSyntax::Dyn => self.word_nbsp("dyn"),
434                    ast::TraitObjectSyntax::None => {}
435                }
436                let mut first = true;
437                for bound in bounds {
438                    if first {
439                        first = false;
440                    } else {
441                        self.nbsp();
442                        self.word_space("+");
443                    }
444                    self.print_poly_trait_ref(bound);
445                }
446                if !lifetime.is_elided() {
447                    self.nbsp();
448                    self.word_space("+");
449                    self.print_lifetime(lifetime.pointer());
450                }
451            }
452            hir::TyKind::Array(ty, ref length) => {
453                self.word("[");
454                self.print_type(ty);
455                self.word("; ");
456                self.print_const_arg(length);
457                self.word("]");
458            }
459            hir::TyKind::Err(_) => {
460                self.popen();
461                self.word("/*ERROR*/");
462                self.pclose();
463            }
464            hir::TyKind::Infer(()) | hir::TyKind::InferDelegation(..) => {
465                self.word("_");
466            }
467            hir::TyKind::Pat(ty, pat) => {
468                self.print_type(ty);
469                self.word(" is ");
470                self.print_ty_pat(pat);
471            }
472            hir::TyKind::FieldOf(ty, TyFieldPath { variant, field }) => {
473                self.word("field_of!(");
474                self.print_type(ty);
475                self.word(", ");
476                if let Some(variant) = *variant {
477                    self.print_ident(variant);
478                    self.word(".");
479                }
480                self.print_ident(*field);
481                self.word(")");
482            }
483            hir::TyKind::View(ty, fields) => {
484                self.word("view_type!(");
485                self.print_type(ty);
486                self.word(".{");
487                if !fields.is_empty() {
488                    self.space();
489                    self.commasep(Breaks::Inconsistent, fields, |s, f| s.print_ident(*f));
490                    self.space();
491                }
492                self.word("})");
493            }
494        }
495        self.end(ib)
496    }
497
498    fn print_unsafe_binder(&mut self, unsafe_binder: &hir::UnsafeBinderTy<'_>) {
499        let ib = self.ibox(INDENT_UNIT);
500        self.word("unsafe");
501        self.print_generic_params(unsafe_binder.generic_params);
502        self.nbsp();
503        self.print_type(unsafe_binder.inner_ty);
504        self.end(ib);
505    }
506
507    fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
508        self.hardbreak_if_not_bol();
509        self.maybe_print_comment(item.span.lo());
510        self.print_attrs(self.attrs(item.hir_id()));
511        match item.kind {
512            hir::ForeignItemKind::Fn(sig, arg_idents, generics) => {
513                let (cb, ib) = self.head("");
514                self.print_fn(
515                    sig.header,
516                    Some(item.ident.name),
517                    generics,
518                    sig.decl,
519                    arg_idents,
520                    None,
521                );
522                self.end(ib);
523                self.word(";");
524                self.end(cb)
525            }
526            hir::ForeignItemKind::Static(t, m, safety) => {
527                self.print_safety(safety);
528                let (cb, ib) = self.head("static");
529                if m.is_mut() {
530                    self.word_space("mut");
531                }
532                self.print_ident(item.ident);
533                self.word_space(":");
534                self.print_type(t);
535                self.word(";");
536                self.end(ib);
537                self.end(cb)
538            }
539            hir::ForeignItemKind::Type => {
540                let (cb, ib) = self.head("type");
541                self.print_ident(item.ident);
542                self.word(";");
543                self.end(ib);
544                self.end(cb)
545            }
546        }
547    }
548
549    fn print_associated_const(
550        &mut self,
551        ident: Ident,
552        generics: &hir::Generics<'_>,
553        ty: &hir::Ty<'_>,
554        default: Option<hir::ConstItemRhs<'_>>,
555    ) {
556        self.word_space("const");
557        self.print_ident(ident);
558        self.print_generic_params(generics.params);
559        self.word_space(":");
560        self.print_type(ty);
561        if let Some(ct_rhs) = default {
562            self.space();
563            self.word_space("=");
564            self.print_const_item_rhs(ct_rhs);
565        }
566        self.print_where_clause(generics);
567        self.word(";")
568    }
569
570    fn print_associated_type(
571        &mut self,
572        ident: Ident,
573        generics: &hir::Generics<'_>,
574        bounds: Option<hir::GenericBounds<'_>>,
575        ty: Option<&hir::Ty<'_>>,
576    ) {
577        self.word_space("type");
578        self.print_ident(ident);
579        self.print_generic_params(generics.params);
580        if let Some(bounds) = bounds {
581            self.print_bounds(":", bounds);
582        }
583        self.print_where_clause(generics);
584        if let Some(ty) = ty {
585            self.space();
586            self.word_space("=");
587            self.print_type(ty);
588        }
589        self.word(";")
590    }
591
592    fn print_item(&mut self, item: &hir::Item<'_>) {
593        self.hardbreak_if_not_bol();
594        self.maybe_print_comment(item.span.lo());
595        let attrs = self.attrs(item.hir_id());
596        self.print_attrs(attrs);
597        self.ann.pre(self, AnnNode::Item(item));
598        match item.kind {
599            hir::ItemKind::ExternCrate(orig_name, ident) => {
600                let (cb, ib) = self.head("extern crate");
601                if let Some(orig_name) = orig_name {
602                    self.print_name(orig_name);
603                    self.space();
604                    self.word("as");
605                    self.space();
606                }
607                self.print_ident(ident);
608                self.word(";");
609                self.end(ib);
610                self.end(cb);
611            }
612            hir::ItemKind::Use(path, kind) => {
613                let (cb, ib) = self.head("use");
614                self.print_path(path, false);
615
616                match kind {
617                    hir::UseKind::Single(ident) => {
618                        if path.segments.last().unwrap().ident != ident {
619                            self.space();
620                            self.word_space("as");
621                            self.print_ident(ident);
622                        }
623                        self.word(";");
624                    }
625                    hir::UseKind::Glob => self.word("::*;"),
626                    hir::UseKind::ListStem => self.word("::{};"),
627                }
628                self.end(ib);
629                self.end(cb);
630            }
631            hir::ItemKind::Static(m, ident, ty, expr) => {
632                let (cb, ib) = self.head("static");
633                if m.is_mut() {
634                    self.word_space("mut");
635                }
636                self.print_ident(ident);
637                self.word_space(":");
638                self.print_type(ty);
639                self.space();
640                self.end(ib);
641
642                self.word_space("=");
643                self.ann.nested(self, Nested::Body(expr));
644                self.word(";");
645                self.end(cb);
646            }
647            hir::ItemKind::Const(ident, generics, ty, rhs) => {
648                let (cb, ib) = self.head("const");
649                self.print_ident(ident);
650                self.print_generic_params(generics.params);
651                self.word_space(":");
652                self.print_type(ty);
653                self.space();
654                self.end(ib);
655
656                self.word_space("=");
657                self.print_const_item_rhs(rhs);
658                self.print_where_clause(generics);
659                self.word(";");
660                self.end(cb);
661            }
662            hir::ItemKind::Fn { ident, sig, generics, body, .. } => {
663                let (cb, ib) = self.head("");
664                self.print_fn(sig.header, Some(ident.name), generics, sig.decl, &[], Some(body));
665                self.word(" ");
666                self.end(ib);
667                self.end(cb);
668                self.ann.nested(self, Nested::Body(body));
669            }
670            hir::ItemKind::Macro(ident, macro_def, _) => {
671                self.print_mac_def(macro_def, &ident, item.span, |_| {});
672            }
673            hir::ItemKind::Mod(ident, mod_) => {
674                let (cb, ib) = self.head("mod");
675                self.print_ident(ident);
676                self.nbsp();
677                self.bopen(ib);
678                self.print_mod(mod_);
679                self.bclose(item.span, cb);
680            }
681            hir::ItemKind::ForeignMod { abi, items } => {
682                let (cb, ib) = self.head("extern");
683                self.word_nbsp(abi.to_string());
684                self.bopen(ib);
685                for &foreign_item in items {
686                    self.ann.nested(self, Nested::ForeignItem(foreign_item));
687                }
688                self.bclose(item.span, cb);
689            }
690            hir::ItemKind::GlobalAsm { asm, .. } => {
691                let (cb, ib) = self.head("global_asm!");
692                self.print_inline_asm(asm);
693                self.word(";");
694                self.end(cb);
695                self.end(ib);
696            }
697            hir::ItemKind::TyAlias(ident, generics, ty) => {
698                let (cb, ib) = self.head("type");
699                self.print_ident(ident);
700                self.print_generic_params(generics.params);
701                self.end(ib);
702
703                self.print_where_clause(generics);
704                self.space();
705                self.word_space("=");
706                self.print_type(ty);
707                self.word(";");
708                self.end(cb);
709            }
710            hir::ItemKind::Enum(ident, generics, ref enum_def) => {
711                self.print_enum_def(ident.name, generics, enum_def, item.span);
712            }
713            hir::ItemKind::Struct(ident, generics, ref struct_def) => {
714                let (cb, ib) = self.head("struct");
715                self.print_struct(ident.name, generics, struct_def, item.span, true, cb, ib);
716            }
717            hir::ItemKind::Union(ident, generics, ref struct_def) => {
718                let (cb, ib) = self.head("union");
719                self.print_struct(ident.name, generics, struct_def, item.span, true, cb, ib);
720            }
721            hir::ItemKind::Impl(hir::Impl { generics, of_trait, self_ty, items, constness }) => {
722                let (cb, ib) = self.head("");
723
724                let impl_generics = |this: &mut Self| {
725                    this.word_nbsp("impl");
726                    if !generics.params.is_empty() {
727                        this.print_generic_params(generics.params);
728                        this.space();
729                    }
730                };
731
732                match of_trait {
733                    None => {
734                        if let hir::Constness::Const { always: false } = constness {
735                            self.word_nbsp("const");
736                        }
737                        impl_generics(self)
738                    }
739                    Some(&hir::TraitImplHeader {
740                        safety,
741                        polarity,
742                        defaultness,
743                        defaultness_span: _,
744                        ref trait_ref,
745                    }) => {
746                        self.print_defaultness(defaultness);
747                        self.print_safety(safety);
748
749                        impl_generics(self);
750
751                        if let hir::Constness::Const { always: false } = constness {
752                            self.word_nbsp("const");
753                        }
754
755                        if let hir::ImplPolarity::Negative(_) = polarity {
756                            self.word("!");
757                        }
758
759                        self.print_trait_ref(trait_ref);
760                        self.space();
761                        self.word_space("for");
762                    }
763                }
764
765                self.print_type(self_ty);
766                self.print_where_clause(generics);
767
768                self.space();
769                self.bopen(ib);
770                for &impl_item in items {
771                    self.ann.nested(self, Nested::ImplItem(impl_item));
772                }
773                self.bclose(item.span, cb);
774            }
775            hir::ItemKind::Trait {
776                impl_restriction,
777                constness,
778                is_auto,
779                safety,
780                ident,
781                generics,
782                bounds,
783                items: trait_items,
784            } => {
785                let (cb, ib) = self.head("");
786                self.print_impl_restriction(impl_restriction);
787                self.print_constness(constness);
788                self.print_is_auto(is_auto);
789                self.print_safety(safety);
790                self.word_nbsp("trait");
791                self.print_ident(ident);
792                self.print_generic_params(generics.params);
793                self.print_bounds(":", bounds);
794                self.print_where_clause(generics);
795                self.word(" ");
796                self.bopen(ib);
797                for &trait_item in trait_items {
798                    self.ann.nested(self, Nested::TraitItem(trait_item));
799                }
800                self.bclose(item.span, cb);
801            }
802            hir::ItemKind::TraitAlias(constness, ident, generics, bounds) => {
803                let (cb, ib) = self.head("");
804                self.print_constness(constness);
805                self.word_nbsp("trait");
806                self.print_ident(ident);
807                self.print_generic_params(generics.params);
808                self.nbsp();
809                self.print_bounds("=", bounds);
810                self.print_where_clause(generics);
811                self.word(";");
812                self.end(ib);
813                self.end(cb);
814            }
815            rustc_hir::ItemKind::TestBinderConstraints { .. } => {
816                self.word("test_binder_constraints!(/* pretty-printing not supported */)");
817            }
818        }
819        self.ann.post(self, AnnNode::Item(item))
820    }
821
822    fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
823        self.print_path(t.path, false);
824    }
825
826    fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
827        if !generic_params.is_empty() {
828            self.word("for");
829            self.print_generic_params(generic_params);
830            self.nbsp();
831        }
832    }
833
834    fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
835        let hir::TraitBoundModifiers { constness, polarity } = t.modifiers;
836        match constness {
837            hir::BoundConstness::Never => {}
838            hir::BoundConstness::Always(_) => self.word("const"),
839            hir::BoundConstness::Maybe(_) => self.word("[const]"),
840        }
841        match polarity {
842            hir::BoundPolarity::Positive => {}
843            hir::BoundPolarity::Negative(_) => self.word("!"),
844            hir::BoundPolarity::Maybe(_) => self.word("?"),
845        }
846        self.print_formal_generic_params(t.bound_generic_params);
847        self.print_trait_ref(&t.trait_ref);
848    }
849
850    fn print_enum_def(
851        &mut self,
852        name: Symbol,
853        generics: &hir::Generics<'_>,
854        enum_def: &hir::EnumDef<'_>,
855        span: rustc_span::Span,
856    ) {
857        let (cb, ib) = self.head("enum");
858        self.print_name(name);
859        self.print_generic_params(generics.params);
860        self.print_where_clause(generics);
861        self.space();
862        self.print_variants(enum_def.variants, span, cb, ib);
863    }
864
865    fn print_variants(
866        &mut self,
867        variants: &[hir::Variant<'_>],
868        span: rustc_span::Span,
869        cb: BoxMarker,
870        ib: BoxMarker,
871    ) {
872        self.bopen(ib);
873        for v in variants {
874            self.space_if_not_bol();
875            self.maybe_print_comment(v.span.lo());
876            self.print_attrs(self.attrs(v.hir_id));
877            let ib = self.ibox(INDENT_UNIT);
878            self.print_variant(v);
879            self.word(",");
880            self.end(ib);
881            self.maybe_print_trailing_comment(v.span, None);
882        }
883        self.bclose(span, cb)
884    }
885
886    fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
887        match defaultness {
888            hir::Defaultness::Default { .. } => self.word_nbsp("default"),
889            hir::Defaultness::Final => (),
890        }
891    }
892
893    fn print_struct(
894        &mut self,
895        name: Symbol,
896        generics: &hir::Generics<'_>,
897        struct_def: &hir::VariantData<'_>,
898        span: rustc_span::Span,
899        print_finalizer: bool,
900        cb: BoxMarker,
901        ib: BoxMarker,
902    ) {
903        self.print_name(name);
904        self.print_generic_params(generics.params);
905        match struct_def {
906            hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
907                if let hir::VariantData::Tuple(..) = struct_def {
908                    self.popen();
909                    self.commasep(Inconsistent, struct_def.fields(), |s, field| {
910                        s.maybe_print_comment(field.span.lo());
911                        s.print_attrs(s.attrs(field.hir_id));
912                        s.print_mut_restriction(field.mut_restriction);
913                        s.print_type(field.ty);
914                    });
915                    self.pclose();
916                }
917                self.print_where_clause(generics);
918                if print_finalizer {
919                    self.word(";");
920                }
921                self.end(ib);
922                self.end(cb);
923            }
924            hir::VariantData::Struct { .. } => {
925                self.print_where_clause(generics);
926                self.nbsp();
927                self.bopen(ib);
928                self.hardbreak_if_not_bol();
929
930                for field in struct_def.fields() {
931                    self.hardbreak_if_not_bol();
932                    self.maybe_print_comment(field.span.lo());
933                    self.print_attrs(self.attrs(field.hir_id));
934                    self.print_mut_restriction(field.mut_restriction);
935                    self.print_ident(field.ident);
936                    self.word_nbsp(":");
937                    self.print_type(field.ty);
938                    self.word(",");
939                }
940
941                self.bclose(span, cb)
942            }
943        }
944    }
945
946    pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
947        let (cb, ib) = self.head("");
948        let generics = hir::Generics::empty();
949        self.print_struct(v.ident.name, generics, &v.data, v.span, false, cb, ib);
950        if let Some(ref d) = v.disr_expr {
951            self.space();
952            self.word_space("=");
953            self.print_anon_const(d);
954        }
955    }
956
957    fn print_method_sig(
958        &mut self,
959        ident: Ident,
960        m: &hir::FnSig<'_>,
961        generics: &hir::Generics<'_>,
962        arg_idents: &[Option<Ident>],
963        body_id: Option<hir::BodyId>,
964    ) {
965        self.print_fn(m.header, Some(ident.name), generics, m.decl, arg_idents, body_id);
966    }
967
968    fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
969        self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
970        self.hardbreak_if_not_bol();
971        self.maybe_print_comment(ti.span.lo());
972        self.print_attrs(self.attrs(ti.hir_id()));
973        match ti.kind {
974            hir::TraitItemKind::Const(ty, default) => {
975                self.print_associated_const(ti.ident, ti.generics, ty, default);
976            }
977            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_idents)) => {
978                self.print_method_sig(ti.ident, sig, ti.generics, arg_idents, None);
979                self.word(";");
980            }
981            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
982                let (cb, ib) = self.head("");
983                self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
984                self.nbsp();
985                self.end(ib);
986                self.end(cb);
987                self.ann.nested(self, Nested::Body(body));
988            }
989            hir::TraitItemKind::Type(bounds, default) => {
990                self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
991            }
992        }
993        self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
994    }
995
996    fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
997        self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
998        self.hardbreak_if_not_bol();
999        self.maybe_print_comment(ii.span.lo());
1000        self.print_attrs(self.attrs(ii.hir_id()));
1001
1002        match ii.kind {
1003            hir::ImplItemKind::Const(ty, expr) => {
1004                self.print_associated_const(ii.ident, ii.generics, ty, Some(expr));
1005            }
1006            hir::ImplItemKind::Fn(ref sig, body) => {
1007                let (cb, ib) = self.head("");
1008                self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
1009                self.nbsp();
1010                self.end(ib);
1011                self.end(cb);
1012                self.ann.nested(self, Nested::Body(body));
1013            }
1014            hir::ImplItemKind::Type(ty) => {
1015                self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
1016            }
1017        }
1018        self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
1019    }
1020
1021    fn print_local(
1022        &mut self,
1023        super_: bool,
1024        init: Option<&hir::Expr<'_>>,
1025        els: Option<&hir::Block<'_>>,
1026        decl: impl Fn(&mut Self),
1027    ) {
1028        self.space_if_not_bol();
1029        let ibm1 = self.ibox(INDENT_UNIT);
1030        if super_ {
1031            self.word_nbsp("super");
1032        }
1033        self.word_nbsp("let");
1034
1035        let ibm2 = self.ibox(INDENT_UNIT);
1036        decl(self);
1037        self.end(ibm2);
1038
1039        if let Some(init) = init {
1040            self.nbsp();
1041            self.word_space("=");
1042            self.print_expr(init);
1043        }
1044
1045        if let Some(els) = els {
1046            self.nbsp();
1047            self.word_space("else");
1048            // containing cbox, will be closed by print-block at `}`
1049            let cb = self.cbox(0);
1050            // head-box, will be closed by print-block after `{`
1051            let ib = self.ibox(0);
1052            self.print_block(els, cb, ib);
1053        }
1054
1055        self.end(ibm1)
1056    }
1057
1058    fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1059        self.maybe_print_comment(st.span.lo());
1060        match st.kind {
1061            hir::StmtKind::Let(loc) => {
1062                self.print_local(loc.super_.is_some(), loc.init, loc.els, |this| {
1063                    this.print_local_decl(loc)
1064                });
1065            }
1066            hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1067            hir::StmtKind::Expr(expr) => {
1068                self.space_if_not_bol();
1069                self.print_expr(expr);
1070            }
1071            hir::StmtKind::Semi(expr) => {
1072                self.space_if_not_bol();
1073                self.print_expr(expr);
1074                self.word(";");
1075            }
1076        }
1077        if stmt_ends_with_semi(&st.kind) {
1078            self.word(";");
1079        }
1080        self.maybe_print_trailing_comment(st.span, None)
1081    }
1082
1083    fn print_block(&mut self, blk: &hir::Block<'_>, cb: BoxMarker, ib: BoxMarker) {
1084        self.print_block_maybe_unclosed(blk, Some(cb), ib)
1085    }
1086
1087    fn print_block_unclosed(&mut self, blk: &hir::Block<'_>, ib: BoxMarker) {
1088        self.print_block_maybe_unclosed(blk, None, ib)
1089    }
1090
1091    fn print_block_maybe_unclosed(
1092        &mut self,
1093        blk: &hir::Block<'_>,
1094        cb: Option<BoxMarker>,
1095        ib: BoxMarker,
1096    ) {
1097        match blk.rules {
1098            hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1099            hir::BlockCheckMode::DefaultBlock => (),
1100        }
1101        self.maybe_print_comment(blk.span.lo());
1102        self.ann.pre(self, AnnNode::Block(blk));
1103        self.bopen(ib);
1104
1105        for st in blk.stmts {
1106            self.print_stmt(st);
1107        }
1108        if let Some(expr) = blk.expr {
1109            self.space_if_not_bol();
1110            self.print_expr(expr);
1111            self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1112        }
1113        self.bclose_maybe_open(blk.span, cb);
1114        self.ann.post(self, AnnNode::Block(blk))
1115    }
1116
1117    fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1118        if let Some(els_inner) = els {
1119            match els_inner.kind {
1120                // Another `else if` block.
1121                hir::ExprKind::If(i, hir::Expr { kind: hir::ExprKind::Block(t, None), .. }, e) => {
1122                    let cb = self.cbox(0);
1123                    let ib = self.ibox(0);
1124                    self.word(" else if ");
1125                    self.print_expr_as_cond(i);
1126                    self.space();
1127                    self.print_block(t, cb, ib);
1128                    self.print_else(e);
1129                }
1130                // Final `else` block.
1131                hir::ExprKind::Block(b, None) => {
1132                    let cb = self.cbox(0);
1133                    let ib = self.ibox(0);
1134                    self.word(" else ");
1135                    self.print_block(b, cb, ib);
1136                }
1137                // Constraints would be great here!
1138                _ => {
1139                    {
    ::core::panicking::panic_fmt(format_args!("print_if saw if with weird alternative"));
};panic!("print_if saw if with weird alternative");
1140                }
1141            }
1142        }
1143    }
1144
1145    fn print_if(
1146        &mut self,
1147        test: &hir::Expr<'_>,
1148        blk: &hir::Expr<'_>,
1149        elseopt: Option<&hir::Expr<'_>>,
1150    ) {
1151        match blk.kind {
1152            hir::ExprKind::Block(blk, None) => {
1153                let cb = self.cbox(0);
1154                let ib = self.ibox(0);
1155                self.word_nbsp("if");
1156                self.print_expr_as_cond(test);
1157                self.space();
1158                self.print_block(blk, cb, ib);
1159                self.print_else(elseopt)
1160            }
1161            _ => { ::core::panicking::panic_fmt(format_args!("non-block then expr")); }panic!("non-block then expr"),
1162        }
1163    }
1164
1165    fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1166        self.ann.nested(self, Nested::Body(constant.body))
1167    }
1168
1169    fn print_const_item_rhs(&mut self, ct_rhs: hir::ConstItemRhs<'_>) {
1170        match ct_rhs {
1171            hir::ConstItemRhs::Body(body_id) => self.ann.nested(self, Nested::Body(body_id)),
1172            hir::ConstItemRhs::Direct(const_arg) => self.print_const_arg(const_arg),
1173        }
1174    }
1175
1176    fn print_const_arg(&mut self, const_arg: &hir::ConstArg<'_>) {
1177        match &const_arg.kind {
1178            ConstArgKind::Tup(exprs) => {
1179                self.popen();
1180                self.commasep_cmnt(
1181                    Inconsistent,
1182                    exprs,
1183                    |s, arg| s.print_const_arg(arg),
1184                    |arg| arg.span,
1185                );
1186                self.pclose();
1187            }
1188            ConstArgKind::Struct(qpath, fields) => self.print_const_struct(qpath, fields),
1189            ConstArgKind::TupleCall(qpath, args) => self.print_const_ctor(qpath, args),
1190            ConstArgKind::Array(..) => self.word("/* ARRAY EXPR */"),
1191            ConstArgKind::Path(qpath) => self.print_qpath(qpath, true),
1192            ConstArgKind::Anon(anon) => self.print_anon_const(anon),
1193            ConstArgKind::Error(_) => self.word("/*ERROR*/"),
1194            ConstArgKind::Infer(..) => self.word("_"),
1195            ConstArgKind::Literal { lit, negated } => {
1196                if *negated {
1197                    self.word("-");
1198                }
1199                let span = const_arg.span;
1200                self.print_literal(&Spanned { span, node: *lit })
1201            }
1202        }
1203    }
1204
1205    fn print_const_struct(&mut self, qpath: &hir::QPath<'_>, fields: &&[&ConstArgExprField<'_>]) {
1206        self.print_qpath(qpath, true);
1207        self.word(" ");
1208        self.word("{");
1209        if !fields.is_empty() {
1210            self.nbsp();
1211        }
1212        self.commasep(Inconsistent, *fields, |s, field| {
1213            s.word(field.field.as_str().to_string());
1214            s.word(":");
1215            s.nbsp();
1216            s.print_const_arg(field.expr);
1217        });
1218        self.word("}");
1219    }
1220
1221    fn print_const_ctor(&mut self, qpath: &hir::QPath<'_>, args: &&[&ConstArg<'_, ()>]) {
1222        self.print_qpath(qpath, true);
1223        self.word("(");
1224        self.commasep(Inconsistent, *args, |s, arg| {
1225            s.print_const_arg(arg);
1226        });
1227        self.word(")");
1228    }
1229
1230    fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1231        self.popen();
1232        self.commasep_exprs(Inconsistent, args);
1233        self.pclose()
1234    }
1235
1236    /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1237    /// `if cond { ... }`.
1238    fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1239        self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1240    }
1241
1242    /// Prints `expr` or `(expr)` when `needs_par` holds.
1243    fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1244        if needs_par {
1245            self.popen();
1246        }
1247        if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1248            self.print_expr(actual_expr);
1249        } else {
1250            self.print_expr(expr);
1251        }
1252        if needs_par {
1253            self.pclose();
1254        }
1255    }
1256
1257    /// Print a `let pat = expr` expression.
1258    fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1259        self.word_space("let");
1260        self.print_pat(pat);
1261        if let Some(ty) = ty {
1262            self.word_space(":");
1263            self.print_type(ty);
1264        }
1265        self.space();
1266        self.word_space("=");
1267        let npals = || parser::needs_par_as_let_scrutinee(self.precedence(init));
1268        self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1269    }
1270
1271    // Does `expr` need parentheses when printed in a condition position?
1272    //
1273    // These cases need parens due to the parse error observed in #26461: `if return {}`
1274    // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1275    fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1276        match expr.kind {
1277            hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1278                true
1279            }
1280            _ => contains_exterior_struct_lit(expr),
1281        }
1282    }
1283
1284    fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1285        let ib = self.ibox(INDENT_UNIT);
1286        self.word("[");
1287        self.commasep_exprs(Inconsistent, exprs);
1288        self.word("]");
1289        self.end(ib)
1290    }
1291
1292    fn print_inline_const(&mut self, constant: &hir::ConstBlock) {
1293        let ib = self.ibox(INDENT_UNIT);
1294        self.word_space("const");
1295        self.ann.nested(self, Nested::Body(constant.body));
1296        self.end(ib)
1297    }
1298
1299    fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ConstArg<'_>) {
1300        let ib = self.ibox(INDENT_UNIT);
1301        self.word("[");
1302        self.print_expr(element);
1303        self.word_space(";");
1304        self.print_const_arg(count);
1305        self.word("]");
1306        self.end(ib)
1307    }
1308
1309    fn print_expr_struct(
1310        &mut self,
1311        qpath: &hir::QPath<'_>,
1312        fields: &[hir::ExprField<'_>],
1313        wth: hir::StructTailExpr<'_>,
1314    ) {
1315        self.print_qpath(qpath, true);
1316        self.nbsp();
1317        self.word_space("{");
1318        self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1319        match wth {
1320            hir::StructTailExpr::Base(expr) => {
1321                let ib = self.ibox(INDENT_UNIT);
1322                if !fields.is_empty() {
1323                    self.word(",");
1324                    self.space();
1325                }
1326                self.word("..");
1327                self.print_expr(expr);
1328                self.end(ib);
1329            }
1330            hir::StructTailExpr::DefaultFields(_) => {
1331                let ib = self.ibox(INDENT_UNIT);
1332                if !fields.is_empty() {
1333                    self.word(",");
1334                    self.space();
1335                }
1336                self.word("..");
1337                self.end(ib);
1338            }
1339            hir::StructTailExpr::None => {}
1340            hir::StructTailExpr::NoneWithError(_) => {}
1341        }
1342        self.space();
1343        self.word("}");
1344    }
1345
1346    fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1347        let cb = self.cbox(INDENT_UNIT);
1348        self.print_attrs(self.attrs(field.hir_id));
1349        if !field.is_shorthand {
1350            self.print_ident(field.ident);
1351            self.word_space(":");
1352        }
1353        self.print_expr(field.expr);
1354        self.end(cb)
1355    }
1356
1357    fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1358        self.popen();
1359        self.commasep_exprs(Inconsistent, exprs);
1360        if exprs.len() == 1 {
1361            self.word(",");
1362        }
1363        self.pclose()
1364    }
1365
1366    fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1367        let needs_paren = match func.kind {
1368            hir::ExprKind::Field(..) => true,
1369            _ => self.precedence(func) < ExprPrecedence::Unambiguous,
1370        };
1371
1372        self.print_expr_cond_paren(func, needs_paren);
1373        self.print_call_post(args)
1374    }
1375
1376    fn print_expr_method_call(
1377        &mut self,
1378        segment: &hir::PathSegment<'_>,
1379        receiver: &hir::Expr<'_>,
1380        args: &[hir::Expr<'_>],
1381    ) {
1382        let base_args = args;
1383        self.print_expr_cond_paren(
1384            receiver,
1385            self.precedence(receiver) < ExprPrecedence::Unambiguous,
1386        );
1387        self.word(".");
1388        self.print_ident(segment.ident);
1389
1390        let generic_args = segment.args();
1391        if !generic_args.args.is_empty() || !generic_args.constraints.is_empty() {
1392            self.print_generic_args(generic_args, true);
1393        }
1394
1395        self.print_call_post(base_args)
1396    }
1397
1398    fn print_expr_binary(&mut self, op: hir::BinOpKind, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1399        let binop_prec = op.precedence();
1400        let left_prec = self.precedence(lhs);
1401        let right_prec = self.precedence(rhs);
1402
1403        let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
1404            Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
1405            Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
1406            Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
1407        };
1408
1409        match (&lhs.kind, op) {
1410            // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1411            // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1412            // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1413            (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1414                left_needs_paren = true;
1415            }
1416            (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(binop_prec) => {
1417                left_needs_paren = true;
1418            }
1419            _ => {}
1420        }
1421
1422        self.print_expr_cond_paren(lhs, left_needs_paren);
1423        self.space();
1424        self.word_space(op.as_str());
1425        self.print_expr_cond_paren(rhs, right_needs_paren);
1426    }
1427
1428    fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1429        self.word(op.as_str());
1430        self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1431    }
1432
1433    fn print_expr_addr_of(
1434        &mut self,
1435        kind: hir::BorrowKind,
1436        mutability: hir::Mutability,
1437        expr: &hir::Expr<'_>,
1438    ) {
1439        self.word("&");
1440        match kind {
1441            hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1442            hir::BorrowKind::Raw => {
1443                self.word_nbsp("raw");
1444                self.print_mutability(mutability, true);
1445            }
1446            hir::BorrowKind::Pin => {
1447                self.word_nbsp("pin");
1448                self.print_mutability(mutability, true);
1449            }
1450        }
1451        self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1452    }
1453
1454    fn print_literal(&mut self, lit: &hir::Lit) {
1455        self.maybe_print_comment(lit.span.lo());
1456        self.word(lit.node.to_string())
1457    }
1458
1459    fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1460        enum AsmArg<'a> {
1461            Template(String),
1462            Operand(&'a hir::InlineAsmOperand<'a>),
1463            Options(ast::InlineAsmOptions),
1464        }
1465
1466        let mut args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))]))vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1467        args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1468        if !asm.options.is_empty() {
1469            args.push(AsmArg::Options(asm.options));
1470        }
1471
1472        self.popen();
1473        self.commasep(Consistent, &args, |s, arg| match *arg {
1474            AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1475            AsmArg::Operand(op) => match *op {
1476                hir::InlineAsmOperand::In { reg, expr } => {
1477                    s.word("in");
1478                    s.popen();
1479                    s.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", reg))
    })format!("{reg}"));
1480                    s.pclose();
1481                    s.space();
1482                    s.print_expr(expr);
1483                }
1484                hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1485                    s.word(if late { "lateout" } else { "out" });
1486                    s.popen();
1487                    s.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", reg))
    })format!("{reg}"));
1488                    s.pclose();
1489                    s.space();
1490                    match expr {
1491                        Some(expr) => s.print_expr(expr),
1492                        None => s.word("_"),
1493                    }
1494                }
1495                hir::InlineAsmOperand::InOut { reg, late, expr } => {
1496                    s.word(if late { "inlateout" } else { "inout" });
1497                    s.popen();
1498                    s.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", reg))
    })format!("{reg}"));
1499                    s.pclose();
1500                    s.space();
1501                    s.print_expr(expr);
1502                }
1503                hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => {
1504                    s.word(if late { "inlateout" } else { "inout" });
1505                    s.popen();
1506                    s.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", reg))
    })format!("{reg}"));
1507                    s.pclose();
1508                    s.space();
1509                    s.print_expr(in_expr);
1510                    s.space();
1511                    s.word_space("=>");
1512                    match out_expr {
1513                        Some(out_expr) => s.print_expr(out_expr),
1514                        None => s.word("_"),
1515                    }
1516                }
1517                hir::InlineAsmOperand::Const { ref anon_const } => {
1518                    s.word("const");
1519                    s.space();
1520                    // Not using `print_inline_const` to avoid additional `const { ... }`
1521                    s.ann.nested(s, Nested::Body(anon_const.body))
1522                }
1523                hir::InlineAsmOperand::SymFn { ref expr } => {
1524                    s.word("sym_fn");
1525                    s.space();
1526                    s.print_expr(expr);
1527                }
1528                hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1529                    s.word("sym_static");
1530                    s.space();
1531                    s.print_qpath(path, true);
1532                }
1533                hir::InlineAsmOperand::Label { block } => {
1534                    let (cb, ib) = s.head("label");
1535                    s.print_block(block, cb, ib);
1536                }
1537            },
1538            AsmArg::Options(opts) => {
1539                s.word("options");
1540                s.popen();
1541                s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| {
1542                    s.word(opt);
1543                });
1544                s.pclose();
1545            }
1546        });
1547        self.pclose();
1548    }
1549
1550    fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1551        self.maybe_print_comment(expr.span.lo());
1552        self.print_attrs(self.attrs(expr.hir_id));
1553        let ib = self.ibox(INDENT_UNIT);
1554        self.ann.pre(self, AnnNode::Expr(expr));
1555        match expr.kind {
1556            hir::ExprKind::Array(exprs) => {
1557                self.print_expr_vec(exprs);
1558            }
1559            hir::ExprKind::ConstBlock(ref anon_const) => {
1560                self.print_inline_const(anon_const);
1561            }
1562            hir::ExprKind::Repeat(element, ref count) => {
1563                self.print_expr_repeat(element, count);
1564            }
1565            hir::ExprKind::Struct(qpath, fields, wth) => {
1566                self.print_expr_struct(qpath, fields, wth);
1567            }
1568            hir::ExprKind::Tup(exprs) => {
1569                self.print_expr_tup(exprs);
1570            }
1571            hir::ExprKind::Call(func, args) => {
1572                self.print_expr_call(func, args);
1573            }
1574            hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1575                self.print_expr_method_call(segment, receiver, args);
1576            }
1577            hir::ExprKind::Use(expr, _) => {
1578                self.print_expr(expr);
1579                self.word(".use");
1580            }
1581            hir::ExprKind::Binary(op, lhs, rhs) => {
1582                self.print_expr_binary(op.node, lhs, rhs);
1583            }
1584            hir::ExprKind::Unary(op, expr) => {
1585                self.print_expr_unary(op, expr);
1586            }
1587            hir::ExprKind::AddrOf(k, m, expr) => {
1588                self.print_expr_addr_of(k, m, expr);
1589            }
1590            hir::ExprKind::Lit(lit) => {
1591                self.print_literal(&lit);
1592            }
1593            hir::ExprKind::Cast(expr, ty) => {
1594                self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Cast);
1595                self.space();
1596                self.word_space("as");
1597                self.print_type(ty);
1598            }
1599            hir::ExprKind::Type(expr, ty) => {
1600                self.word("type_ascribe!(");
1601                let ib = self.ibox(0);
1602                self.print_expr(expr);
1603
1604                self.word(",");
1605                self.space_if_not_bol();
1606                self.print_type(ty);
1607
1608                self.end(ib);
1609                self.word(")");
1610            }
1611            hir::ExprKind::DropTemps(init) => {
1612                // Print `{`:
1613                let cb = self.cbox(0);
1614                let ib = self.ibox(0);
1615                self.bopen(ib);
1616
1617                // Print `let _t = $init;`:
1618                let temp = Ident::with_dummy_span(sym::_t);
1619                self.print_local(false, Some(init), None, |this| this.print_ident(temp));
1620                self.word(";");
1621
1622                // Print `_t`:
1623                self.space_if_not_bol();
1624                self.print_ident(temp);
1625
1626                // Print `}`:
1627                self.bclose_maybe_open(expr.span, Some(cb));
1628            }
1629            hir::ExprKind::Let(&hir::LetExpr { pat, ty, init, .. }) => {
1630                self.print_let(pat, ty, init);
1631            }
1632            hir::ExprKind::If(test, blk, elseopt) => {
1633                self.print_if(test, blk, elseopt);
1634            }
1635            hir::ExprKind::Loop(blk, opt_label, _, _) => {
1636                let cb = self.cbox(0);
1637                let ib = self.ibox(0);
1638                if let Some(label) = opt_label {
1639                    self.print_ident(label.ident);
1640                    self.word_space(":");
1641                }
1642                self.word_nbsp("loop");
1643                self.print_block(blk, cb, ib);
1644            }
1645            hir::ExprKind::Match(expr, arms, _) => {
1646                let cb = self.cbox(0);
1647                let ib = self.ibox(0);
1648                self.word_nbsp("match");
1649                self.print_expr_as_cond(expr);
1650                self.space();
1651                self.bopen(ib);
1652                for arm in arms {
1653                    self.print_arm(arm);
1654                }
1655                self.bclose(expr.span, cb);
1656            }
1657            hir::ExprKind::Closure(&hir::Closure {
1658                binder,
1659                constness,
1660                capture_clause,
1661                bound_generic_params,
1662                fn_decl,
1663                body,
1664                fn_decl_span: _,
1665                fn_arg_span: _,
1666                kind: _,
1667                def_id: _,
1668                explicit_captures: _,
1669            }) => {
1670                self.print_closure_binder(binder, bound_generic_params);
1671                self.print_constness(constness);
1672                self.print_capture_clause(capture_clause);
1673
1674                self.print_closure_params(fn_decl, body);
1675                self.space();
1676
1677                // This is a bare expression.
1678                self.ann.nested(self, Nested::Body(body));
1679            }
1680            hir::ExprKind::Block(blk, opt_label) => {
1681                if let Some(label) = opt_label {
1682                    self.print_ident(label.ident);
1683                    self.word_space(":");
1684                }
1685                // containing cbox, will be closed by print-block at `}`
1686                let cb = self.cbox(0);
1687                // head-box, will be closed by print-block after `{`
1688                let ib = self.ibox(0);
1689                self.print_block(blk, cb, ib);
1690            }
1691            hir::ExprKind::Assign(lhs, rhs, _) => {
1692                self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1693                self.space();
1694                self.word_space("=");
1695                self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1696            }
1697            hir::ExprKind::AssignOp(op, lhs, rhs) => {
1698                self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1699                self.space();
1700                self.word_space(op.node.as_str());
1701                self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1702            }
1703            hir::ExprKind::Field(expr, ident) => {
1704                self.print_expr_cond_paren(
1705                    expr,
1706                    self.precedence(expr) < ExprPrecedence::Unambiguous,
1707                );
1708                self.word(".");
1709                self.print_ident(ident);
1710            }
1711            hir::ExprKind::Index(expr, index, _) => {
1712                self.print_expr_cond_paren(
1713                    expr,
1714                    self.precedence(expr) < ExprPrecedence::Unambiguous,
1715                );
1716                self.word("[");
1717                self.print_expr(index);
1718                self.word("]");
1719            }
1720            hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1721            hir::ExprKind::Break(destination, opt_expr) => {
1722                self.word("break");
1723                if let Some(label) = destination.label {
1724                    self.space();
1725                    self.print_ident(label.ident);
1726                }
1727                if let Some(expr) = opt_expr {
1728                    self.space();
1729                    self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1730                }
1731            }
1732            hir::ExprKind::Continue(destination) => {
1733                self.word("continue");
1734                if let Some(label) = destination.label {
1735                    self.space();
1736                    self.print_ident(label.ident);
1737                }
1738            }
1739            hir::ExprKind::Ret(result) => {
1740                self.word("return");
1741                if let Some(expr) = result {
1742                    self.word(" ");
1743                    self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1744                }
1745            }
1746            hir::ExprKind::Become(result) => {
1747                self.word("become");
1748                self.word(" ");
1749                self.print_expr_cond_paren(result, self.precedence(result) < ExprPrecedence::Jump);
1750            }
1751            hir::ExprKind::InlineAsm(asm) => {
1752                self.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}!", asm.asm_macro.macro_name()))
    })format!("{}!", asm.asm_macro.macro_name()));
1753                self.print_inline_asm(asm);
1754            }
1755            hir::ExprKind::OffsetOf(container, fields) => {
1756                self.word("offset_of!(");
1757                self.print_type(container);
1758                self.word(",");
1759                self.space();
1760
1761                if let Some((&first, rest)) = fields.split_first() {
1762                    self.print_ident(first);
1763
1764                    for &field in rest {
1765                        self.word(".");
1766                        self.print_ident(field);
1767                    }
1768                }
1769
1770                self.word(")");
1771            }
1772            hir::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1773                match kind {
1774                    ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder!("),
1775                    ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder!("),
1776                }
1777                self.print_expr(expr);
1778                if let Some(ty) = ty {
1779                    self.word(",");
1780                    self.space();
1781                    self.print_type(ty);
1782                }
1783                self.word(")");
1784            }
1785            hir::ExprKind::Yield(expr, _) => {
1786                self.word_space("yield");
1787                self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1788            }
1789            hir::ExprKind::Err(_) => {
1790                self.popen();
1791                self.word("/*ERROR*/");
1792                self.pclose();
1793            }
1794        }
1795        self.ann.post(self, AnnNode::Expr(expr));
1796        self.end(ib)
1797    }
1798
1799    fn print_local_decl(&mut self, loc: &hir::LetStmt<'_>) {
1800        self.print_pat(loc.pat);
1801        if let Some(ty) = loc.ty {
1802            self.word_space(":");
1803            self.print_type(ty);
1804        }
1805    }
1806
1807    fn print_name(&mut self, name: Symbol) {
1808        self.print_ident(Ident::with_dummy_span(name))
1809    }
1810
1811    fn print_path<R>(&mut self, path: &hir::Path<'_, R>, colons_before_params: bool) {
1812        self.maybe_print_comment(path.span.lo());
1813
1814        for (i, segment) in path.segments.iter().enumerate() {
1815            if i > 0 {
1816                self.word("::")
1817            }
1818            if segment.ident.name != kw::PathRoot {
1819                self.print_ident(segment.ident);
1820                self.print_generic_args(segment.args(), colons_before_params);
1821            }
1822        }
1823    }
1824
1825    fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1826        if segment.ident.name != kw::PathRoot {
1827            self.print_ident(segment.ident);
1828            self.print_generic_args(segment.args(), false);
1829        }
1830    }
1831
1832    fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1833        match *qpath {
1834            hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1835            hir::QPath::Resolved(Some(qself), path) => {
1836                self.word("<");
1837                self.print_type(qself);
1838                self.space();
1839                self.word_space("as");
1840
1841                for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1842                    if i > 0 {
1843                        self.word("::")
1844                    }
1845                    if segment.ident.name != kw::PathRoot {
1846                        self.print_ident(segment.ident);
1847                        self.print_generic_args(segment.args(), colons_before_params);
1848                    }
1849                }
1850
1851                self.word(">");
1852                self.word("::");
1853                let item_segment = path.segments.last().unwrap();
1854                self.print_ident(item_segment.ident);
1855                self.print_generic_args(item_segment.args(), colons_before_params)
1856            }
1857            hir::QPath::TypeRelative(qself, item_segment) => {
1858                // If we've got a compound-qualified-path, let's push an additional pair of angle
1859                // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1860                // `A::B::C` (since the latter could be ambiguous to the user)
1861                if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1862                    self.print_type(qself);
1863                } else {
1864                    self.word("<");
1865                    self.print_type(qself);
1866                    self.word(">");
1867                }
1868
1869                self.word("::");
1870                self.print_ident(item_segment.ident);
1871                self.print_generic_args(item_segment.args(), colons_before_params)
1872            }
1873        }
1874    }
1875
1876    fn print_generic_args(
1877        &mut self,
1878        generic_args: &hir::GenericArgs<'_>,
1879        colons_before_params: bool,
1880    ) {
1881        match generic_args.parenthesized {
1882            hir::GenericArgsParentheses::No => {
1883                let start = if colons_before_params { "::<" } else { "<" };
1884                let empty = Cell::new(true);
1885                let start_or_comma = |this: &mut Self| {
1886                    if empty.get() {
1887                        empty.set(false);
1888                        this.word(start)
1889                    } else {
1890                        this.word_space(",")
1891                    }
1892                };
1893
1894                let mut nonelided_generic_args: bool = false;
1895                let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1896                    GenericArg::Lifetime(lt) if lt.is_elided() => true,
1897                    GenericArg::Lifetime(_) => {
1898                        nonelided_generic_args = true;
1899                        false
1900                    }
1901                    _ => {
1902                        nonelided_generic_args = true;
1903                        true
1904                    }
1905                });
1906
1907                if nonelided_generic_args {
1908                    start_or_comma(self);
1909                    self.commasep(Inconsistent, generic_args.args, |s, generic_arg| {
1910                        s.print_generic_arg(generic_arg, elide_lifetimes)
1911                    });
1912                }
1913
1914                for constraint in generic_args.constraints {
1915                    start_or_comma(self);
1916                    self.print_assoc_item_constraint(constraint);
1917                }
1918
1919                if !empty.get() {
1920                    self.word(">")
1921                }
1922            }
1923            hir::GenericArgsParentheses::ParenSugar => {
1924                let (inputs, output) = generic_args.paren_sugar_inputs_output().unwrap();
1925
1926                self.word("(");
1927                self.commasep(Inconsistent, inputs, |s, ty| s.print_type(ty));
1928                self.word(")");
1929
1930                self.space_if_not_bol();
1931                self.word_space("->");
1932                self.print_type(output);
1933            }
1934            hir::GenericArgsParentheses::ReturnTypeNotation => {
1935                self.word("(..)");
1936            }
1937        }
1938    }
1939
1940    fn print_assoc_item_constraint(&mut self, constraint: &hir::AssocItemConstraint<'_>) {
1941        self.print_ident(constraint.ident);
1942        self.print_generic_args(constraint.gen_args, false);
1943        self.space();
1944        match constraint.kind {
1945            hir::AssocItemConstraintKind::Equality { ref term } => {
1946                self.word_space("=");
1947                match term {
1948                    Term::Ty(ty) => self.print_type(ty),
1949                    Term::Const(c) => self.print_const_arg(c),
1950                }
1951            }
1952            hir::AssocItemConstraintKind::Bound { bounds } => {
1953                self.print_bounds(":", bounds);
1954            }
1955        }
1956    }
1957
1958    fn print_pat_expr(&mut self, expr: &hir::PatExpr<'_>) {
1959        match &expr.kind {
1960            hir::PatExprKind::Lit { lit, negated } => {
1961                if *negated {
1962                    self.word("-");
1963                }
1964                self.print_literal(lit);
1965            }
1966            hir::PatExprKind::Path(qpath) => self.print_qpath(qpath, true),
1967        }
1968    }
1969
1970    fn print_ty_pat(&mut self, pat: &hir::TyPat<'_>) {
1971        self.maybe_print_comment(pat.span.lo());
1972        self.ann.pre(self, AnnNode::TyPat(pat));
1973        // Pat isn't normalized, but the beauty of it
1974        // is that it doesn't matter
1975        match pat.kind {
1976            TyPatKind::Range(begin, end) => {
1977                self.print_const_arg(begin);
1978                self.word("..=");
1979                self.print_const_arg(end);
1980            }
1981            TyPatKind::NotNull => {
1982                self.word_space("not");
1983                self.word("null");
1984            }
1985            TyPatKind::Or(patterns) => {
1986                self.popen();
1987                let mut first = true;
1988                for pat in patterns {
1989                    if first {
1990                        first = false;
1991                    } else {
1992                        self.word(" | ");
1993                    }
1994                    self.print_ty_pat(pat);
1995                }
1996                self.pclose();
1997            }
1998            TyPatKind::Err(_) => {
1999                self.popen();
2000                self.word("/*ERROR*/");
2001                self.pclose();
2002            }
2003        }
2004        self.ann.post(self, AnnNode::TyPat(pat))
2005    }
2006
2007    fn print_pat(&mut self, pat: &hir::Pat<'_>) {
2008        self.maybe_print_comment(pat.span.lo());
2009        self.ann.pre(self, AnnNode::Pat(pat));
2010        // Pat isn't normalized, but the beauty of it is that it doesn't matter.
2011        match pat.kind {
2012            // Printing `_` isn't ideal for a missing pattern, but it's easy and good enough.
2013            // E.g. `fn(u32)` gets printed as `fn(_: u32)`.
2014            PatKind::Missing => self.word("_"),
2015            PatKind::Wild => self.word("_"),
2016            PatKind::Never => self.word("!"),
2017            PatKind::Binding(BindingMode(by_ref, mutbl), _, ident, sub) => {
2018                if mutbl.is_mut() {
2019                    self.word_nbsp("mut");
2020                }
2021                if let ByRef::Yes(pinnedness, rmutbl) = by_ref {
2022                    self.word_nbsp("ref");
2023                    if pinnedness.is_pinned() {
2024                        self.word_nbsp("pin");
2025                    }
2026                    if rmutbl.is_mut() {
2027                        self.word_nbsp("mut");
2028                    } else if pinnedness.is_pinned() {
2029                        self.word_nbsp("const");
2030                    }
2031                }
2032                self.print_ident(ident);
2033                if let Some(p) = sub {
2034                    self.word("@");
2035                    self.print_pat(p);
2036                }
2037            }
2038            PatKind::TupleStruct(ref qpath, elts, ddpos) => {
2039                self.print_qpath(qpath, true);
2040                self.popen();
2041                if let Some(ddpos) = ddpos.as_opt_usize() {
2042                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2043                    if ddpos != 0 {
2044                        self.word_space(",");
2045                    }
2046                    self.word("..");
2047                    if ddpos != elts.len() {
2048                        self.word(",");
2049                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2050                    }
2051                } else {
2052                    self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2053                }
2054                self.pclose();
2055            }
2056            PatKind::Struct(ref qpath, fields, etc) => {
2057                self.print_qpath(qpath, true);
2058                self.nbsp();
2059                self.word("{");
2060                let empty = fields.is_empty() && etc.is_none();
2061                if !empty {
2062                    self.space();
2063                }
2064                self.commasep_cmnt(Consistent, fields, |s, f| s.print_patfield(f), |f| f.pat.span);
2065                if etc.is_some() {
2066                    if !fields.is_empty() {
2067                        self.word_space(",");
2068                    }
2069                    self.word("..");
2070                }
2071                if !empty {
2072                    self.space();
2073                }
2074                self.word("}");
2075            }
2076            PatKind::Or(pats) => {
2077                self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
2078            }
2079            PatKind::Tuple(elts, ddpos) => {
2080                self.popen();
2081                if let Some(ddpos) = ddpos.as_opt_usize() {
2082                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2083                    if ddpos != 0 {
2084                        self.word_space(",");
2085                    }
2086                    self.word("..");
2087                    if ddpos != elts.len() {
2088                        self.word(",");
2089                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2090                    }
2091                } else {
2092                    self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2093                    if elts.len() == 1 {
2094                        self.word(",");
2095                    }
2096                }
2097                self.pclose();
2098            }
2099            PatKind::Deref(inner) => {
2100                self.word("deref!");
2101                self.popen();
2102                self.print_pat(inner);
2103                self.pclose();
2104            }
2105            PatKind::Ref(inner, pinned, mutbl) => {
2106                let is_range_inner = #[allow(non_exhaustive_omitted_patterns)] match inner.kind {
    PatKind::Range(..) => true,
    _ => false,
}matches!(inner.kind, PatKind::Range(..));
2107                self.word("&");
2108                if pinned.is_pinned() {
2109                    self.word("pin ");
2110                    if mutbl.is_not() {
2111                        self.word("const ");
2112                    }
2113                }
2114                self.word(mutbl.prefix_str());
2115                if is_range_inner {
2116                    self.popen();
2117                }
2118                self.print_pat(inner);
2119                if is_range_inner {
2120                    self.pclose();
2121                }
2122            }
2123            PatKind::Expr(e) => self.print_pat_expr(e),
2124            PatKind::Range(begin, end, end_kind) => {
2125                if let Some(expr) = begin {
2126                    self.print_pat_expr(expr);
2127                }
2128                match end_kind {
2129                    RangeEnd::Included => self.word("..."),
2130                    RangeEnd::Excluded => self.word(".."),
2131                }
2132                if let Some(expr) = end {
2133                    self.print_pat_expr(expr);
2134                }
2135            }
2136            PatKind::Slice(before, slice, after) => {
2137                self.word("[");
2138                self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
2139                if let Some(p) = slice {
2140                    if !before.is_empty() {
2141                        self.word_space(",");
2142                    }
2143                    if let PatKind::Wild = p.kind {
2144                        // Print nothing.
2145                    } else {
2146                        self.print_pat(p);
2147                    }
2148                    self.word("..");
2149                    if !after.is_empty() {
2150                        self.word_space(",");
2151                    }
2152                }
2153                self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
2154                self.word("]");
2155            }
2156            PatKind::Guard(inner, cond) => {
2157                self.print_pat(inner);
2158                self.space();
2159                self.word_space("if");
2160                self.print_expr(cond);
2161            }
2162            PatKind::Err(_) => {
2163                self.popen();
2164                self.word("/*ERROR*/");
2165                self.pclose();
2166            }
2167        }
2168        self.ann.post(self, AnnNode::Pat(pat))
2169    }
2170
2171    fn print_patfield(&mut self, field: &hir::PatField<'_>) {
2172        if self.attrs(field.hir_id).is_empty() {
2173            self.space();
2174        }
2175        let cb = self.cbox(INDENT_UNIT);
2176        self.print_attrs(self.attrs(field.hir_id));
2177        if !field.is_shorthand {
2178            self.print_ident(field.ident);
2179            self.word_nbsp(":");
2180        }
2181        self.print_pat(field.pat);
2182        self.end(cb);
2183    }
2184
2185    fn print_param(&mut self, arg: &hir::Param<'_>) {
2186        self.print_attrs(self.attrs(arg.hir_id));
2187        self.print_pat(arg.pat);
2188    }
2189
2190    fn print_implicit_self(&mut self, implicit_self_kind: &hir::ImplicitSelfKind) {
2191        match implicit_self_kind {
2192            ImplicitSelfKind::Imm => {
2193                self.word("self");
2194            }
2195            ImplicitSelfKind::Mut => {
2196                self.print_mutability(hir::Mutability::Mut, false);
2197                self.word("self");
2198            }
2199            ImplicitSelfKind::RefImm => {
2200                self.word("&");
2201                self.word("self");
2202            }
2203            ImplicitSelfKind::RefMut => {
2204                self.word("&");
2205                self.print_mutability(hir::Mutability::Mut, false);
2206                self.word("self");
2207            }
2208            ImplicitSelfKind::None => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2209        }
2210    }
2211
2212    fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2213        // I have no idea why this check is necessary, but here it
2214        // is :(
2215        if self.attrs(arm.hir_id).is_empty() {
2216            self.space();
2217        }
2218        let cb = self.cbox(INDENT_UNIT);
2219        self.ann.pre(self, AnnNode::Arm(arm));
2220        let ib = self.ibox(0);
2221        self.print_attrs(self.attrs(arm.hir_id));
2222        self.print_pat(arm.pat);
2223        self.space();
2224        if let Some(ref g) = arm.guard {
2225            self.word_space("if");
2226            self.print_expr(g);
2227            self.space();
2228        }
2229        self.word_space("=>");
2230
2231        match arm.body.kind {
2232            hir::ExprKind::Block(blk, opt_label) => {
2233                if let Some(label) = opt_label {
2234                    self.print_ident(label.ident);
2235                    self.word_space(":");
2236                }
2237                self.print_block_unclosed(blk, ib);
2238
2239                // If it is a user-provided unsafe block, print a comma after it
2240                if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2241                {
2242                    self.word(",");
2243                }
2244            }
2245            _ => {
2246                self.end(ib);
2247                self.print_expr(arm.body);
2248                self.word(",");
2249            }
2250        }
2251        self.ann.post(self, AnnNode::Arm(arm));
2252        self.end(cb)
2253    }
2254
2255    fn print_fn(
2256        &mut self,
2257        header: hir::FnHeader,
2258        name: Option<Symbol>,
2259        generics: &hir::Generics<'_>,
2260        decl: &hir::FnDecl<'_>,
2261        arg_idents: &[Option<Ident>],
2262        body_id: Option<hir::BodyId>,
2263    ) {
2264        self.print_fn_header_info(header);
2265
2266        if let Some(name) = name {
2267            self.nbsp();
2268            self.print_name(name);
2269        }
2270        self.print_generic_params(generics.params);
2271
2272        self.popen();
2273        // Make sure we aren't supplied *both* `arg_idents` and `body_id`.
2274        if !(arg_idents.is_empty() || body_id.is_none()) {
    ::core::panicking::panic("assertion failed: arg_idents.is_empty() || body_id.is_none()")
};assert!(arg_idents.is_empty() || body_id.is_none());
2275        let mut i = 0;
2276        let mut print_arg = |s: &mut Self, ty: Option<&hir::Ty<'_>>| {
2277            if Some(i) == decl.splatted().map(usize::from) {
2278                s.word("#[rustc_splat]");
2279            }
2280            if i == 0 && decl.implicit_self().has_implicit_self() {
2281                s.print_implicit_self(&decl.implicit_self());
2282            } else {
2283                if let Some(arg_ident) = arg_idents.get(i) {
2284                    if let Some(arg_ident) = arg_ident {
2285                        s.word(arg_ident.to_string());
2286                        s.word(":");
2287                        s.space();
2288                    }
2289                } else if let Some(body_id) = body_id {
2290                    s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2291                    s.word(":");
2292                    s.space();
2293                }
2294                if let Some(ty) = ty {
2295                    s.print_type(ty);
2296                }
2297            }
2298            i += 1;
2299        };
2300        self.commasep(Inconsistent, decl.inputs, |s, ty| {
2301            let ib = s.ibox(INDENT_UNIT);
2302            print_arg(s, Some(ty));
2303            s.end(ib);
2304        });
2305        if decl.c_variadic() {
2306            if !decl.inputs.is_empty() {
2307                self.word(", ");
2308            }
2309            print_arg(self, None);
2310            self.word("...");
2311        }
2312        self.pclose();
2313
2314        self.print_fn_output(decl);
2315        self.print_where_clause(generics)
2316    }
2317
2318    fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2319        self.word("|");
2320        let mut i = 0;
2321        self.commasep(Inconsistent, decl.inputs, |s, ty| {
2322            let ib = s.ibox(INDENT_UNIT);
2323
2324            s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2325            i += 1;
2326
2327            if let hir::TyKind::Infer(()) = ty.kind {
2328                // Print nothing.
2329            } else {
2330                s.word(":");
2331                s.space();
2332                s.print_type(ty);
2333            }
2334            s.end(ib);
2335        });
2336        self.word("|");
2337
2338        match decl.output {
2339            hir::FnRetTy::Return(ty) => {
2340                self.space_if_not_bol();
2341                self.word_space("->");
2342                self.print_type(ty);
2343                self.maybe_print_comment(ty.span.lo());
2344            }
2345            hir::FnRetTy::DefaultReturn(..) => {}
2346        }
2347    }
2348
2349    fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2350        match capture_clause {
2351            hir::CaptureBy::Value { .. } => self.word_space("move"),
2352            hir::CaptureBy::Use { .. } => self.word_space("use"),
2353            hir::CaptureBy::Ref => {}
2354        }
2355    }
2356
2357    fn print_closure_binder(
2358        &mut self,
2359        binder: hir::ClosureBinder,
2360        generic_params: &[GenericParam<'_>],
2361    ) {
2362        let generic_params = generic_params
2363            .iter()
2364            .filter(|p| {
2365                #[allow(non_exhaustive_omitted_patterns)] match p {
    GenericParam {
        kind: GenericParamKind::Lifetime {
            kind: LifetimeParamKind::Explicit
            }, .. } => true,
    _ => false,
}matches!(
2366                    p,
2367                    GenericParam {
2368                        kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2369                        ..
2370                    }
2371                )
2372            })
2373            .collect::<Vec<_>>();
2374
2375        match binder {
2376            hir::ClosureBinder::Default => {}
2377            // We need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional
2378            // restrictions.
2379            hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2380            hir::ClosureBinder::For { .. } => {
2381                self.word("for");
2382                self.word("<");
2383
2384                self.commasep(Inconsistent, &generic_params, |s, param| {
2385                    s.print_generic_param(param)
2386                });
2387
2388                self.word(">");
2389                self.nbsp();
2390            }
2391        }
2392    }
2393
2394    fn print_bounds<'b>(
2395        &mut self,
2396        prefix: &'static str,
2397        bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2398    ) {
2399        let mut first = true;
2400        for bound in bounds {
2401            if first {
2402                self.word(prefix);
2403            }
2404            if !(first && prefix.is_empty()) {
2405                self.nbsp();
2406            }
2407            if first {
2408                first = false;
2409            } else {
2410                self.word_space("+");
2411            }
2412
2413            match bound {
2414                GenericBound::Trait(tref) => {
2415                    self.print_poly_trait_ref(tref);
2416                }
2417                GenericBound::Outlives(lt) => {
2418                    self.print_lifetime(lt);
2419                }
2420                GenericBound::Use(args, _) => {
2421                    self.word("use <");
2422
2423                    self.commasep(Inconsistent, *args, |s, arg| {
2424                        s.print_precise_capturing_arg(*arg)
2425                    });
2426
2427                    self.word(">");
2428                }
2429            }
2430        }
2431    }
2432
2433    fn print_precise_capturing_arg(&mut self, arg: PreciseCapturingArg<'_>) {
2434        match arg {
2435            PreciseCapturingArg::Lifetime(lt) => self.print_lifetime(lt),
2436            PreciseCapturingArg::Param(arg) => self.print_ident(arg.ident),
2437        }
2438    }
2439
2440    fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2441        let is_lifetime_elided = |generic_param: &GenericParam<'_>| {
2442            #[allow(non_exhaustive_omitted_patterns)] match generic_param.kind {
    GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) } => true,
    _ => false,
}matches!(
2443                generic_param.kind,
2444                GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) }
2445            )
2446        };
2447
2448        // We don't want to show elided lifetimes as they are compiler-inserted and not
2449        // expressible in surface level Rust.
2450        if !generic_params.is_empty() && !generic_params.iter().all(is_lifetime_elided) {
2451            self.word("<");
2452
2453            self.commasep(
2454                Inconsistent,
2455                generic_params.iter().filter(|gp| !is_lifetime_elided(gp)),
2456                |s, param| s.print_generic_param(param),
2457            );
2458
2459            self.word(">");
2460        }
2461    }
2462
2463    fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2464        if let GenericParamKind::Const { .. } = param.kind {
2465            self.word_space("const");
2466        }
2467
2468        self.print_ident(param.name.ident());
2469
2470        match param.kind {
2471            GenericParamKind::Lifetime { .. } => {}
2472            GenericParamKind::Type { default, .. } => {
2473                if let Some(default) = default {
2474                    self.space();
2475                    self.word_space("=");
2476                    self.print_type(default);
2477                }
2478            }
2479            GenericParamKind::Const { ty, ref default } => {
2480                self.word_space(":");
2481                self.print_type(ty);
2482                if let Some(default) = default {
2483                    self.space();
2484                    self.word_space("=");
2485                    self.print_const_arg(default);
2486                }
2487            }
2488        }
2489    }
2490
2491    fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2492        self.print_ident(lifetime.ident)
2493    }
2494
2495    fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2496        if generics.predicates.is_empty() {
2497            return;
2498        }
2499
2500        self.space();
2501        self.word_space("where");
2502
2503        for (i, predicate) in generics.predicates.iter().enumerate() {
2504            if i != 0 {
2505                self.word_space(",");
2506            }
2507            self.print_where_predicate(predicate);
2508        }
2509    }
2510
2511    fn print_where_predicate(&mut self, predicate: &hir::WherePredicate<'_>) {
2512        self.print_attrs(self.attrs(predicate.hir_id));
2513        match *predicate.kind {
2514            hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2515                bound_generic_params,
2516                bounded_ty,
2517                bounds,
2518                ..
2519            }) => {
2520                self.print_formal_generic_params(bound_generic_params);
2521                self.print_type(bounded_ty);
2522                self.print_bounds(":", bounds);
2523            }
2524            hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2525                lifetime,
2526                bounds,
2527                ..
2528            }) => {
2529                self.print_lifetime(lifetime);
2530                self.word(":");
2531
2532                for (i, bound) in bounds.iter().enumerate() {
2533                    match bound {
2534                        GenericBound::Outlives(lt) => {
2535                            self.print_lifetime(lt);
2536                        }
2537                        _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected bound on lifetime param: {0:?}",
            bound));
}panic!("unexpected bound on lifetime param: {bound:?}"),
2538                    }
2539
2540                    if i != 0 {
2541                        self.word(":");
2542                    }
2543                }
2544            }
2545        }
2546    }
2547
2548    fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2549        match mutbl {
2550            hir::Mutability::Mut => self.word_nbsp("mut"),
2551            hir::Mutability::Not => {
2552                if print_const {
2553                    self.word_nbsp("const")
2554                }
2555            }
2556        }
2557    }
2558
2559    fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2560        self.print_mutability(mt.mutbl, print_const);
2561        self.print_type(mt.ty);
2562    }
2563
2564    fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2565        match decl.output {
2566            hir::FnRetTy::Return(ty) => {
2567                self.space_if_not_bol();
2568                let ib = self.ibox(INDENT_UNIT);
2569                self.word_space("->");
2570                self.print_type(ty);
2571                self.end(ib);
2572
2573                if let hir::FnRetTy::Return(output) = decl.output {
2574                    self.maybe_print_comment(output.span.lo());
2575                }
2576            }
2577            hir::FnRetTy::DefaultReturn(..) => {}
2578        }
2579    }
2580
2581    fn print_ty_fn(
2582        &mut self,
2583        abi: ExternAbi,
2584        safety: hir::Safety,
2585        decl: &hir::FnDecl<'_>,
2586        name: Option<Symbol>,
2587        generic_params: &[hir::GenericParam<'_>],
2588        arg_idents: &[Option<Ident>],
2589    ) {
2590        let ib = self.ibox(INDENT_UNIT);
2591        self.print_formal_generic_params(generic_params);
2592        let generics = hir::Generics::empty();
2593        self.print_fn(
2594            hir::FnHeader {
2595                safety: safety.into(),
2596                abi,
2597                constness: hir::Constness::NotConst,
2598                asyncness: hir::IsAsync::NotAsync,
2599            },
2600            name,
2601            generics,
2602            decl,
2603            arg_idents,
2604            None,
2605        );
2606        self.end(ib);
2607    }
2608
2609    fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2610        self.print_constness(header.constness);
2611
2612        let safety = match header.safety {
2613            hir::HeaderSafety::SafeTargetFeatures => {
2614                self.word_nbsp("#[target_feature]");
2615                hir::Safety::Safe
2616            }
2617            hir::HeaderSafety::Normal(safety) => safety,
2618        };
2619
2620        match header.asyncness {
2621            hir::IsAsync::NotAsync => {}
2622            hir::IsAsync::Async(_) => self.word_nbsp("async"),
2623        }
2624
2625        self.print_safety(safety);
2626
2627        if header.abi != ExternAbi::Rust {
2628            self.word_nbsp("extern");
2629            self.word_nbsp(header.abi.to_string());
2630        }
2631
2632        self.word("fn")
2633    }
2634
2635    fn print_constness(&mut self, s: hir::Constness) {
2636        match s {
2637            hir::Constness::NotConst => {}
2638            hir::Constness::Const { always: false } => self.word_nbsp("const"),
2639            hir::Constness::Const { always: true } => { /* printed as an attribute */ }
2640        }
2641    }
2642
2643    fn print_safety(&mut self, s: hir::Safety) {
2644        match s {
2645            hir::Safety::Safe => {}
2646            hir::Safety::Unsafe => self.word_nbsp("unsafe"),
2647        }
2648    }
2649
2650    fn print_is_auto(&mut self, s: hir::IsAuto) {
2651        match s {
2652            hir::IsAuto::Yes => self.word_nbsp("auto"),
2653            hir::IsAuto::No => {}
2654        }
2655    }
2656
2657    fn print_restriction<S: Into<std::borrow::Cow<'static, str>>>(
2658        &mut self,
2659        k: &hir::RestrictionKind<'_>,
2660        prefix: S,
2661    ) {
2662        match k {
2663            hir::RestrictionKind::Unrestricted => {}
2664            hir::RestrictionKind::Restricted(path) => {
2665                self.word(prefix.into());
2666                self.word_nbsp("(in");
2667                self.print_path(path, false);
2668                self.word_nbsp(")");
2669            }
2670        }
2671    }
2672
2673    fn print_mut_restriction(&mut self, r: &hir::MutRestriction<'_>) {
2674        self.print_restriction(&r.kind, "mut");
2675    }
2676
2677    fn print_impl_restriction(&mut self, r: &hir::ImplRestriction<'_>) {
2678        self.print_restriction(&r.kind, "impl");
2679    }
2680}
2681
2682/// Does this expression require a semicolon to be treated
2683/// as a statement? The negation of this: 'can this expression
2684/// be used as a statement without a semicolon' -- is used
2685/// as an early-bail-out in the parser so that, for instance,
2686///     if true {...} else {...}
2687///      |x| 5
2688/// isn't parsed as (if true {...} else {...} | x) | 5
2689//
2690// Duplicated from `parse::classify`, but adapted for the HIR.
2691fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2692    !#[allow(non_exhaustive_omitted_patterns)] match e.kind {
    hir::ExprKind::If(..) | hir::ExprKind::Match(..) |
        hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => true,
    _ => false,
}matches!(
2693        e.kind,
2694        hir::ExprKind::If(..)
2695            | hir::ExprKind::Match(..)
2696            | hir::ExprKind::Block(..)
2697            | hir::ExprKind::Loop(..)
2698    )
2699}
2700
2701/// This statement requires a semicolon after it.
2702/// note that in one case (stmt_semi), we've already
2703/// seen the semicolon, and thus don't need another.
2704fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2705    match *stmt {
2706        hir::StmtKind::Let(_) => true,
2707        hir::StmtKind::Item(_) => false,
2708        hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2709        hir::StmtKind::Semi(..) => false,
2710    }
2711}
2712
2713/// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2714/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2715/// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2716fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2717    match value.kind {
2718        hir::ExprKind::Struct(..) => true,
2719
2720        hir::ExprKind::Assign(lhs, rhs, _)
2721        | hir::ExprKind::AssignOp(_, lhs, rhs)
2722        | hir::ExprKind::Binary(_, lhs, rhs) => {
2723            // `X { y: 1 } + X { y: 2 }`
2724            contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2725        }
2726        hir::ExprKind::Unary(_, x)
2727        | hir::ExprKind::Cast(x, _)
2728        | hir::ExprKind::Type(x, _)
2729        | hir::ExprKind::Field(x, _)
2730        | hir::ExprKind::Index(x, _, _) => {
2731            // `&X { y: 1 }, X { y: 1 }.y`
2732            contains_exterior_struct_lit(x)
2733        }
2734
2735        hir::ExprKind::MethodCall(_, receiver, ..) => {
2736            // `X { y: 1 }.bar(...)`
2737            contains_exterior_struct_lit(receiver)
2738        }
2739
2740        _ => false,
2741    }
2742}