rustc_hir_pretty/
lib.rs

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