rustc_hir_pretty/
lib.rs

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