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