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