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