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