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