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