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