rustc_hir_pretty/
lib.rs

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