Skip to main content

rustc_hir_pretty/
lib.rs

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