Skip to main content

rustc_hir_pretty/
lib.rs

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