rustc_ast_pretty/pprust/state/
expr.rs

1use std::fmt::Write;
2
3use ast::{ForLoopKind, MatchKind};
4use itertools::{Itertools, Position};
5use rustc_ast::ptr::P;
6use rustc_ast::util::classify;
7use rustc_ast::util::literal::escape_byte_str_symbol;
8use rustc_ast::util::parser::{self, ExprPrecedence, Fixity};
9use rustc_ast::{
10    self as ast, BinOpKind, BlockCheckMode, FormatAlignment, FormatArgPosition, FormatArgsPiece,
11    FormatCount, FormatDebugHex, FormatSign, FormatTrait, YieldKind, token,
12};
13
14use crate::pp::Breaks::Inconsistent;
15use crate::pprust::state::fixup::FixupContext;
16use crate::pprust::state::{AnnNode, INDENT_UNIT, PrintState, State};
17
18impl<'a> State<'a> {
19    fn print_else(&mut self, els: Option<&ast::Expr>) {
20        if let Some(_else) = els {
21            match &_else.kind {
22                // Another `else if` block.
23                ast::ExprKind::If(i, then, e) => {
24                    let cb = self.cbox(0);
25                    let ib = self.ibox(0);
26                    self.word(" else if ");
27                    self.print_expr_as_cond(i);
28                    self.space();
29                    self.print_block(then, cb, ib);
30                    self.print_else(e.as_deref())
31                }
32                // Final `else` block.
33                ast::ExprKind::Block(b, None) => {
34                    let cb = self.cbox(0);
35                    let ib = self.ibox(0);
36                    self.word(" else ");
37                    self.print_block(b, cb, ib)
38                }
39                // Constraints would be great here!
40                _ => {
41                    panic!("print_if saw if with weird alternative");
42                }
43            }
44        }
45    }
46
47    fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
48        let cb = self.cbox(0);
49        let ib = self.ibox(0);
50        self.word_nbsp("if");
51        self.print_expr_as_cond(test);
52        self.space();
53        self.print_block(blk, cb, ib);
54        self.print_else(elseopt)
55    }
56
57    fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
58        self.popen();
59        self.commasep_exprs(Inconsistent, args);
60        self.pclose()
61    }
62
63    /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
64    /// `if cond { ... }`.
65    fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
66        self.print_expr_cond_paren(expr, Self::cond_needs_par(expr), FixupContext::new_cond())
67    }
68
69    /// Does `expr` need parentheses when printed in a condition position?
70    ///
71    /// These cases need parens due to the parse error observed in #26461: `if return {}`
72    /// parses as the erroneous construct `if (return {})`, not `if (return) {}`.
73    fn cond_needs_par(expr: &ast::Expr) -> bool {
74        match expr.kind {
75            ast::ExprKind::Break(..)
76            | ast::ExprKind::Closure(..)
77            | ast::ExprKind::Ret(..)
78            | ast::ExprKind::Yeet(..) => true,
79            _ => parser::contains_exterior_struct_lit(expr),
80        }
81    }
82
83    /// Prints `expr` or `(expr)` when `needs_par` holds.
84    pub(super) fn print_expr_cond_paren(
85        &mut self,
86        expr: &ast::Expr,
87        needs_par: bool,
88        mut fixup: FixupContext,
89    ) {
90        if needs_par {
91            self.popen();
92
93            // If we are surrounding the whole cond in parentheses, such as:
94            //
95            //     if (return Struct {}) {}
96            //
97            // then there is no need for parenthesizing the individual struct
98            // expressions within. On the other hand if the whole cond is not
99            // parenthesized, then print_expr must parenthesize exterior struct
100            // literals.
101            //
102            //     if x == (Struct {}) {}
103            //
104            fixup = FixupContext::default();
105        }
106
107        self.print_expr(expr, fixup);
108
109        if needs_par {
110            self.pclose();
111        }
112    }
113
114    fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
115        let ib = self.ibox(INDENT_UNIT);
116        self.word("[");
117        self.commasep_exprs(Inconsistent, exprs);
118        self.word("]");
119        self.end(ib);
120    }
121
122    pub(super) fn print_expr_anon_const(
123        &mut self,
124        expr: &ast::AnonConst,
125        attrs: &[ast::Attribute],
126    ) {
127        let ib = self.ibox(INDENT_UNIT);
128        self.word("const");
129        self.nbsp();
130        if let ast::ExprKind::Block(block, None) = &expr.value.kind {
131            let cb = self.cbox(0);
132            let ib = self.ibox(0);
133            self.print_block_with_attrs(block, attrs, cb, ib);
134        } else {
135            self.print_expr(&expr.value, FixupContext::default());
136        }
137        self.end(ib);
138    }
139
140    fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
141        let ib = self.ibox(INDENT_UNIT);
142        self.word("[");
143        self.print_expr(element, FixupContext::default());
144        self.word_space(";");
145        self.print_expr(&count.value, FixupContext::default());
146        self.word("]");
147        self.end(ib);
148    }
149
150    fn print_expr_struct(
151        &mut self,
152        qself: &Option<P<ast::QSelf>>,
153        path: &ast::Path,
154        fields: &[ast::ExprField],
155        rest: &ast::StructRest,
156    ) {
157        if let Some(qself) = qself {
158            self.print_qpath(path, qself, true);
159        } else {
160            self.print_path(path, true, 0);
161        }
162        self.nbsp();
163        self.word("{");
164        let has_rest = match rest {
165            ast::StructRest::Base(_) | ast::StructRest::Rest(_) => true,
166            ast::StructRest::None => false,
167        };
168        if fields.is_empty() && !has_rest {
169            self.word("}");
170            return;
171        }
172        let cb = self.cbox(0);
173        for (pos, field) in fields.iter().with_position() {
174            let is_first = matches!(pos, Position::First | Position::Only);
175            let is_last = matches!(pos, Position::Last | Position::Only);
176            self.maybe_print_comment(field.span.hi());
177            self.print_outer_attributes(&field.attrs);
178            if is_first {
179                self.space_if_not_bol();
180            }
181            if !field.is_shorthand {
182                self.print_ident(field.ident);
183                self.word_nbsp(":");
184            }
185            self.print_expr(&field.expr, FixupContext::default());
186            if !is_last || has_rest {
187                self.word_space(",");
188            } else {
189                self.trailing_comma_or_space();
190            }
191        }
192        if has_rest {
193            if fields.is_empty() {
194                self.space();
195            }
196            self.word("..");
197            if let ast::StructRest::Base(expr) = rest {
198                self.print_expr(expr, FixupContext::default());
199            }
200            self.space();
201        }
202        self.offset(-INDENT_UNIT);
203        self.end(cb);
204        self.word("}");
205    }
206
207    fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
208        self.popen();
209        self.commasep_exprs(Inconsistent, exprs);
210        if exprs.len() == 1 {
211            self.word(",");
212        }
213        self.pclose()
214    }
215
216    fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>], fixup: FixupContext) {
217        // Independent of parenthesization related to precedence, we must
218        // parenthesize `func` if this is a statement context in which without
219        // parentheses, a statement boundary would occur inside `func` or
220        // immediately after `func`.
221        //
222        // Suppose `func` represents `match () { _ => f }`. We must produce:
223        //
224        //     (match () { _ => f })();
225        //
226        // instead of:
227        //
228        //     match () { _ => f } ();
229        //
230        // because the latter is valid syntax but with the incorrect meaning.
231        // It's a match-expression followed by tuple-expression, not a function
232        // call.
233        let func_fixup = fixup.leftmost_subexpression_with_operator(true);
234
235        let needs_paren = match func.kind {
236            // In order to call a named field, needs parens: `(self.fun)()`
237            // But not for an unnamed field: `self.0()`
238            ast::ExprKind::Field(_, name) => !name.is_numeric(),
239            _ => func_fixup.precedence(func) < ExprPrecedence::Unambiguous,
240        };
241
242        self.print_expr_cond_paren(func, needs_paren, func_fixup);
243        self.print_call_post(args)
244    }
245
246    fn print_expr_method_call(
247        &mut self,
248        segment: &ast::PathSegment,
249        receiver: &ast::Expr,
250        base_args: &[P<ast::Expr>],
251        fixup: FixupContext,
252    ) {
253        // The fixup here is different than in `print_expr_call` because
254        // statement boundaries never occur in front of a `.` (or `?`) token.
255        //
256        // Needs parens:
257        //
258        //     (loop { break x; })();
259        //
260        // Does not need parens:
261        //
262        //     loop { break x; }.method();
263        //
264        self.print_expr_cond_paren(
265            receiver,
266            receiver.precedence() < ExprPrecedence::Unambiguous,
267            fixup.leftmost_subexpression_with_dot(),
268        );
269
270        self.word(".");
271        self.print_ident(segment.ident);
272        if let Some(args) = &segment.args {
273            self.print_generic_args(args, true);
274        }
275        self.print_call_post(base_args)
276    }
277
278    fn print_expr_binary(
279        &mut self,
280        op: ast::BinOpKind,
281        lhs: &ast::Expr,
282        rhs: &ast::Expr,
283        fixup: FixupContext,
284    ) {
285        let operator_can_begin_expr = match op {
286            | BinOpKind::Sub     // -x
287            | BinOpKind::Mul     // *x
288            | BinOpKind::And     // &&x
289            | BinOpKind::Or      // || x
290            | BinOpKind::BitAnd  // &x
291            | BinOpKind::BitOr   // |x| x
292            | BinOpKind::Shl     // <<T as Trait>::Type as Trait>::CONST
293            | BinOpKind::Lt      // <T as Trait>::CONST
294              => true,
295            _ => false,
296        };
297
298        let left_fixup = fixup.leftmost_subexpression_with_operator(operator_can_begin_expr);
299
300        let binop_prec = op.precedence();
301        let left_prec = left_fixup.precedence(lhs);
302        let right_prec = fixup.precedence(rhs);
303
304        let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
305            Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
306            Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
307            Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
308        };
309
310        match (&lhs.kind, op) {
311            // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
312            // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
313            // of `(x as i32) < ...`. We need to convince it _not_ to do that.
314            (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
315                left_needs_paren = true;
316            }
317            // We are given `(let _ = a) OP b`.
318            //
319            // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
320            //   as the parser will interpret this as `(let _ = a) OP b`.
321            //
322            // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
323            //   parens are required since the parser would interpret `let a = b < c` as
324            //   `let a = (b < c)`. To achieve this, we force parens.
325            (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(binop_prec) => {
326                left_needs_paren = true;
327            }
328            _ => {}
329        }
330
331        self.print_expr_cond_paren(lhs, left_needs_paren, left_fixup);
332        self.space();
333        self.word_space(op.as_str());
334        self.print_expr_cond_paren(rhs, right_needs_paren, fixup.rightmost_subexpression());
335    }
336
337    fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr, fixup: FixupContext) {
338        self.word(op.as_str());
339        self.print_expr_cond_paren(
340            expr,
341            fixup.precedence(expr) < ExprPrecedence::Prefix,
342            fixup.rightmost_subexpression(),
343        );
344    }
345
346    fn print_expr_addr_of(
347        &mut self,
348        kind: ast::BorrowKind,
349        mutability: ast::Mutability,
350        expr: &ast::Expr,
351        fixup: FixupContext,
352    ) {
353        self.word("&");
354        match kind {
355            ast::BorrowKind::Ref => self.print_mutability(mutability, false),
356            ast::BorrowKind::Raw => {
357                self.word_nbsp("raw");
358                self.print_mutability(mutability, true);
359            }
360        }
361        self.print_expr_cond_paren(
362            expr,
363            fixup.precedence(expr) < ExprPrecedence::Prefix,
364            fixup.rightmost_subexpression(),
365        );
366    }
367
368    pub(super) fn print_expr(&mut self, expr: &ast::Expr, fixup: FixupContext) {
369        self.print_expr_outer_attr_style(expr, true, fixup)
370    }
371
372    pub(super) fn print_expr_outer_attr_style(
373        &mut self,
374        expr: &ast::Expr,
375        is_inline: bool,
376        mut fixup: FixupContext,
377    ) {
378        self.maybe_print_comment(expr.span.lo());
379
380        let attrs = &expr.attrs;
381        if is_inline {
382            self.print_outer_attributes_inline(attrs);
383        } else {
384            self.print_outer_attributes(attrs);
385        }
386
387        let ib = self.ibox(INDENT_UNIT);
388
389        // The Match subexpression in `match x {} - 1` must be parenthesized if
390        // it is the leftmost subexpression in a statement:
391        //
392        //     (match x {}) - 1;
393        //
394        // But not otherwise:
395        //
396        //     let _ = match x {} - 1;
397        //
398        // Same applies to a small set of other expression kinds which eagerly
399        // terminate a statement which opens with them.
400        let needs_par = fixup.would_cause_statement_boundary(expr);
401        if needs_par {
402            self.popen();
403            fixup = FixupContext::default();
404        }
405
406        self.ann.pre(self, AnnNode::Expr(expr));
407
408        match &expr.kind {
409            ast::ExprKind::Array(exprs) => {
410                self.print_expr_vec(exprs);
411            }
412            ast::ExprKind::ConstBlock(anon_const) => {
413                self.print_expr_anon_const(anon_const, attrs);
414            }
415            ast::ExprKind::Repeat(element, count) => {
416                self.print_expr_repeat(element, count);
417            }
418            ast::ExprKind::Struct(se) => {
419                self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
420            }
421            ast::ExprKind::Tup(exprs) => {
422                self.print_expr_tup(exprs);
423            }
424            ast::ExprKind::Call(func, args) => {
425                self.print_expr_call(func, args, fixup);
426            }
427            ast::ExprKind::MethodCall(box ast::MethodCall { seg, receiver, args, .. }) => {
428                self.print_expr_method_call(seg, receiver, args, fixup);
429            }
430            ast::ExprKind::Binary(op, lhs, rhs) => {
431                self.print_expr_binary(op.node, lhs, rhs, fixup);
432            }
433            ast::ExprKind::Unary(op, expr) => {
434                self.print_expr_unary(*op, expr, fixup);
435            }
436            ast::ExprKind::AddrOf(k, m, expr) => {
437                self.print_expr_addr_of(*k, *m, expr, fixup);
438            }
439            ast::ExprKind::Lit(token_lit) => {
440                self.print_token_literal(*token_lit, expr.span);
441            }
442            ast::ExprKind::IncludedBytes(bytes) => {
443                let lit = token::Lit::new(token::ByteStr, escape_byte_str_symbol(bytes), None);
444                self.print_token_literal(lit, expr.span)
445            }
446            ast::ExprKind::Cast(expr, ty) => {
447                self.print_expr_cond_paren(
448                    expr,
449                    expr.precedence() < ExprPrecedence::Cast,
450                    fixup.leftmost_subexpression(),
451                );
452                self.space();
453                self.word_space("as");
454                self.print_type(ty);
455            }
456            ast::ExprKind::Type(expr, ty) => {
457                self.word("builtin # type_ascribe");
458                self.popen();
459                let ib = self.ibox(0);
460                self.print_expr(expr, FixupContext::default());
461
462                self.word(",");
463                self.space_if_not_bol();
464                self.print_type(ty);
465
466                self.end(ib);
467                self.pclose();
468            }
469            ast::ExprKind::Let(pat, scrutinee, _, _) => {
470                self.print_let(pat, scrutinee, fixup);
471            }
472            ast::ExprKind::If(test, blk, elseopt) => self.print_if(test, blk, elseopt.as_deref()),
473            ast::ExprKind::While(test, blk, opt_label) => {
474                if let Some(label) = opt_label {
475                    self.print_ident(label.ident);
476                    self.word_space(":");
477                }
478                let cb = self.cbox(0);
479                let ib = self.ibox(0);
480                self.word_nbsp("while");
481                self.print_expr_as_cond(test);
482                self.space();
483                self.print_block_with_attrs(blk, attrs, cb, ib);
484            }
485            ast::ExprKind::ForLoop { pat, iter, body, label, kind } => {
486                if let Some(label) = label {
487                    self.print_ident(label.ident);
488                    self.word_space(":");
489                }
490                let cb = self.cbox(0);
491                let ib = self.ibox(0);
492                self.word_nbsp("for");
493                if kind == &ForLoopKind::ForAwait {
494                    self.word_nbsp("await");
495                }
496                self.print_pat(pat);
497                self.space();
498                self.word_space("in");
499                self.print_expr_as_cond(iter);
500                self.space();
501                self.print_block_with_attrs(body, attrs, cb, ib);
502            }
503            ast::ExprKind::Loop(blk, opt_label, _) => {
504                let cb = self.cbox(0);
505                let ib = self.ibox(0);
506                if let Some(label) = opt_label {
507                    self.print_ident(label.ident);
508                    self.word_space(":");
509                }
510                self.word_nbsp("loop");
511                self.print_block_with_attrs(blk, attrs, cb, ib);
512            }
513            ast::ExprKind::Match(expr, arms, match_kind) => {
514                let cb = self.cbox(0);
515                let ib = self.ibox(0);
516
517                match match_kind {
518                    MatchKind::Prefix => {
519                        self.word_nbsp("match");
520                        self.print_expr_as_cond(expr);
521                        self.space();
522                    }
523                    MatchKind::Postfix => {
524                        self.print_expr_cond_paren(
525                            expr,
526                            expr.precedence() < ExprPrecedence::Unambiguous,
527                            fixup.leftmost_subexpression_with_dot(),
528                        );
529                        self.word_nbsp(".match");
530                    }
531                }
532
533                self.bopen(ib);
534                self.print_inner_attributes_no_trailing_hardbreak(attrs);
535                for arm in arms {
536                    self.print_arm(arm);
537                }
538                let empty = attrs.is_empty() && arms.is_empty();
539                self.bclose(expr.span, empty, cb);
540            }
541            ast::ExprKind::Closure(box ast::Closure {
542                binder,
543                capture_clause,
544                constness,
545                coroutine_kind,
546                movability,
547                fn_decl,
548                body,
549                fn_decl_span: _,
550                fn_arg_span: _,
551            }) => {
552                self.print_closure_binder(binder);
553                self.print_constness(*constness);
554                self.print_movability(*movability);
555                coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind));
556                self.print_capture_clause(*capture_clause);
557
558                self.print_fn_params_and_ret(fn_decl, true);
559                self.space();
560                self.print_expr(body, FixupContext::default());
561            }
562            ast::ExprKind::Block(blk, opt_label) => {
563                if let Some(label) = opt_label {
564                    self.print_ident(label.ident);
565                    self.word_space(":");
566                }
567                // containing cbox, will be closed by print-block at }
568                let cb = self.cbox(0);
569                // head-box, will be closed by print-block after {
570                let ib = self.ibox(0);
571                self.print_block_with_attrs(blk, attrs, cb, ib);
572            }
573            ast::ExprKind::Gen(capture_clause, blk, kind, _decl_span) => {
574                self.word_nbsp(kind.modifier());
575                self.print_capture_clause(*capture_clause);
576                // cbox/ibox in analogy to the `ExprKind::Block` arm above
577                let cb = self.cbox(0);
578                let ib = self.ibox(0);
579                self.print_block_with_attrs(blk, attrs, cb, ib);
580            }
581            ast::ExprKind::Await(expr, _) => {
582                self.print_expr_cond_paren(
583                    expr,
584                    expr.precedence() < ExprPrecedence::Unambiguous,
585                    fixup.leftmost_subexpression_with_dot(),
586                );
587                self.word(".await");
588            }
589            ast::ExprKind::Use(expr, _) => {
590                self.print_expr_cond_paren(
591                    expr,
592                    expr.precedence() < ExprPrecedence::Unambiguous,
593                    fixup,
594                );
595                self.word(".use");
596            }
597            ast::ExprKind::Assign(lhs, rhs, _) => {
598                self.print_expr_cond_paren(
599                    lhs,
600                    // Ranges are allowed on the right-hand side of assignment,
601                    // but not the left. `(a..b) = c` needs parentheses.
602                    lhs.precedence() <= ExprPrecedence::Range,
603                    fixup.leftmost_subexpression(),
604                );
605                self.space();
606                self.word_space("=");
607                self.print_expr_cond_paren(
608                    rhs,
609                    fixup.precedence(rhs) < ExprPrecedence::Assign,
610                    fixup.rightmost_subexpression(),
611                );
612            }
613            ast::ExprKind::AssignOp(op, lhs, rhs) => {
614                self.print_expr_cond_paren(
615                    lhs,
616                    lhs.precedence() <= ExprPrecedence::Range,
617                    fixup.leftmost_subexpression(),
618                );
619                self.space();
620                self.word_space(op.node.as_str());
621                self.print_expr_cond_paren(
622                    rhs,
623                    fixup.precedence(rhs) < ExprPrecedence::Assign,
624                    fixup.rightmost_subexpression(),
625                );
626            }
627            ast::ExprKind::Field(expr, ident) => {
628                self.print_expr_cond_paren(
629                    expr,
630                    expr.precedence() < ExprPrecedence::Unambiguous,
631                    fixup.leftmost_subexpression_with_dot(),
632                );
633                self.word(".");
634                self.print_ident(*ident);
635            }
636            ast::ExprKind::Index(expr, index, _) => {
637                let expr_fixup = fixup.leftmost_subexpression_with_operator(true);
638                self.print_expr_cond_paren(
639                    expr,
640                    expr_fixup.precedence(expr) < ExprPrecedence::Unambiguous,
641                    expr_fixup,
642                );
643                self.word("[");
644                self.print_expr(index, FixupContext::default());
645                self.word("]");
646            }
647            ast::ExprKind::Range(start, end, limits) => {
648                // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
649                // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
650                // Here we use a fake precedence value so that any child with lower precedence than
651                // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
652                let fake_prec = ExprPrecedence::LOr;
653                if let Some(e) = start {
654                    let start_fixup = fixup.leftmost_subexpression_with_operator(true);
655                    self.print_expr_cond_paren(
656                        e,
657                        start_fixup.precedence(e) < fake_prec,
658                        start_fixup,
659                    );
660                }
661                match limits {
662                    ast::RangeLimits::HalfOpen => self.word(".."),
663                    ast::RangeLimits::Closed => self.word("..="),
664                }
665                if let Some(e) = end {
666                    self.print_expr_cond_paren(
667                        e,
668                        fixup.precedence(e) < fake_prec,
669                        fixup.rightmost_subexpression(),
670                    );
671                }
672            }
673            ast::ExprKind::Underscore => self.word("_"),
674            ast::ExprKind::Path(None, path) => self.print_path(path, true, 0),
675            ast::ExprKind::Path(Some(qself), path) => self.print_qpath(path, qself, true),
676            ast::ExprKind::Break(opt_label, opt_expr) => {
677                self.word("break");
678                if let Some(label) = opt_label {
679                    self.space();
680                    self.print_ident(label.ident);
681                }
682                if let Some(expr) = opt_expr {
683                    self.space();
684                    self.print_expr_cond_paren(
685                        expr,
686                        // Parenthesize `break 'inner: loop { break 'inner 1 } + 1`
687                        //                     ^---------------------------------^
688                        opt_label.is_none() && classify::leading_labeled_expr(expr),
689                        fixup.rightmost_subexpression(),
690                    );
691                }
692            }
693            ast::ExprKind::Continue(opt_label) => {
694                self.word("continue");
695                if let Some(label) = opt_label {
696                    self.space();
697                    self.print_ident(label.ident);
698                }
699            }
700            ast::ExprKind::Ret(result) => {
701                self.word("return");
702                if let Some(expr) = result {
703                    self.word(" ");
704                    self.print_expr(expr, fixup.rightmost_subexpression());
705                }
706            }
707            ast::ExprKind::Yeet(result) => {
708                self.word("do");
709                self.word(" ");
710                self.word("yeet");
711                if let Some(expr) = result {
712                    self.word(" ");
713                    self.print_expr(expr, fixup.rightmost_subexpression());
714                }
715            }
716            ast::ExprKind::Become(result) => {
717                self.word("become");
718                self.word(" ");
719                self.print_expr(result, fixup.rightmost_subexpression());
720            }
721            ast::ExprKind::InlineAsm(a) => {
722                // FIXME: Print `builtin # asm` once macro `asm` uses `builtin_syntax`.
723                self.word("asm!");
724                self.print_inline_asm(a);
725            }
726            ast::ExprKind::FormatArgs(fmt) => {
727                // FIXME: Print `builtin # format_args` once macro `format_args` uses `builtin_syntax`.
728                self.word("format_args!");
729                self.popen();
730                let ib = self.ibox(0);
731                self.word(reconstruct_format_args_template_string(&fmt.template));
732                for arg in fmt.arguments.all_args() {
733                    self.word_space(",");
734                    self.print_expr(&arg.expr, FixupContext::default());
735                }
736                self.end(ib);
737                self.pclose();
738            }
739            ast::ExprKind::OffsetOf(container, fields) => {
740                self.word("builtin # offset_of");
741                self.popen();
742                let ib = self.ibox(0);
743                self.print_type(container);
744                self.word(",");
745                self.space();
746
747                if let Some((&first, rest)) = fields.split_first() {
748                    self.print_ident(first);
749
750                    for &field in rest {
751                        self.word(".");
752                        self.print_ident(field);
753                    }
754                }
755                self.end(ib);
756                self.pclose();
757            }
758            ast::ExprKind::MacCall(m) => self.print_mac(m),
759            ast::ExprKind::Paren(e) => {
760                self.popen();
761                self.print_expr(e, FixupContext::default());
762                self.pclose();
763            }
764            ast::ExprKind::Yield(YieldKind::Prefix(e)) => {
765                self.word("yield");
766
767                if let Some(expr) = e {
768                    self.space();
769                    self.print_expr(expr, fixup.rightmost_subexpression());
770                }
771            }
772            ast::ExprKind::Yield(YieldKind::Postfix(e)) => {
773                self.print_expr_cond_paren(
774                    e,
775                    e.precedence() < ExprPrecedence::Unambiguous,
776                    fixup.leftmost_subexpression_with_dot(),
777                );
778                self.word(".yield");
779            }
780            ast::ExprKind::Try(e) => {
781                self.print_expr_cond_paren(
782                    e,
783                    e.precedence() < ExprPrecedence::Unambiguous,
784                    fixup.leftmost_subexpression_with_dot(),
785                );
786                self.word("?")
787            }
788            ast::ExprKind::TryBlock(blk) => {
789                let cb = self.cbox(0);
790                let ib = self.ibox(0);
791                self.word_nbsp("try");
792                self.print_block_with_attrs(blk, attrs, cb, ib)
793            }
794            ast::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
795                self.word("builtin # ");
796                match kind {
797                    ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder"),
798                    ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder"),
799                }
800                self.popen();
801                let ib = self.ibox(0);
802                self.print_expr(expr, FixupContext::default());
803
804                if let Some(ty) = ty {
805                    self.word(",");
806                    self.space();
807                    self.print_type(ty);
808                }
809
810                self.end(ib);
811                self.pclose();
812            }
813            ast::ExprKind::Err(_) => {
814                self.popen();
815                self.word("/*ERROR*/");
816                self.pclose()
817            }
818            ast::ExprKind::Dummy => {
819                self.popen();
820                self.word("/*DUMMY*/");
821                self.pclose();
822            }
823        }
824
825        self.ann.post(self, AnnNode::Expr(expr));
826
827        if needs_par {
828            self.pclose();
829        }
830
831        self.end(ib);
832    }
833
834    fn print_arm(&mut self, arm: &ast::Arm) {
835        // Note, I have no idea why this check is necessary, but here it is.
836        if arm.attrs.is_empty() {
837            self.space();
838        }
839        let cb = self.cbox(INDENT_UNIT);
840        let ib = self.ibox(0);
841        self.maybe_print_comment(arm.pat.span.lo());
842        self.print_outer_attributes(&arm.attrs);
843        self.print_pat(&arm.pat);
844        self.space();
845        if let Some(e) = &arm.guard {
846            self.word_space("if");
847            self.print_expr(e, FixupContext::default());
848            self.space();
849        }
850
851        if let Some(body) = &arm.body {
852            self.word_space("=>");
853
854            match &body.kind {
855                ast::ExprKind::Block(blk, opt_label) => {
856                    if let Some(label) = opt_label {
857                        self.print_ident(label.ident);
858                        self.word_space(":");
859                    }
860
861                    self.print_block_unclosed_indent(blk, ib);
862
863                    // If it is a user-provided unsafe block, print a comma after it.
864                    if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
865                        self.word(",");
866                    }
867                }
868                _ => {
869                    self.end(ib);
870                    self.print_expr(body, FixupContext::new_match_arm());
871                    self.word(",");
872                }
873            }
874        } else {
875            self.end(ib);
876            self.word(",");
877        }
878        self.end(cb);
879    }
880
881    fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
882        match binder {
883            ast::ClosureBinder::NotPresent => {}
884            ast::ClosureBinder::For { generic_params, .. } => {
885                self.print_formal_generic_params(generic_params)
886            }
887        }
888    }
889
890    fn print_movability(&mut self, movability: ast::Movability) {
891        match movability {
892            ast::Movability::Static => self.word_space("static"),
893            ast::Movability::Movable => {}
894        }
895    }
896
897    fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
898        match capture_clause {
899            ast::CaptureBy::Value { .. } => self.word_space("move"),
900            ast::CaptureBy::Use { .. } => self.word_space("use"),
901            ast::CaptureBy::Ref => {}
902        }
903    }
904}
905
906fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String {
907    let mut template = "\"".to_string();
908    for piece in pieces {
909        match piece {
910            FormatArgsPiece::Literal(s) => {
911                for c in s.as_str().chars() {
912                    template.extend(c.escape_debug());
913                    if let '{' | '}' = c {
914                        template.push(c);
915                    }
916                }
917            }
918            FormatArgsPiece::Placeholder(p) => {
919                template.push('{');
920                let (Ok(n) | Err(n)) = p.argument.index;
921                write!(template, "{n}").unwrap();
922                if p.format_options != Default::default() || p.format_trait != FormatTrait::Display
923                {
924                    template.push(':');
925                }
926                if let Some(fill) = p.format_options.fill {
927                    template.push(fill);
928                }
929                match p.format_options.alignment {
930                    Some(FormatAlignment::Left) => template.push('<'),
931                    Some(FormatAlignment::Right) => template.push('>'),
932                    Some(FormatAlignment::Center) => template.push('^'),
933                    None => {}
934                }
935                match p.format_options.sign {
936                    Some(FormatSign::Plus) => template.push('+'),
937                    Some(FormatSign::Minus) => template.push('-'),
938                    None => {}
939                }
940                if p.format_options.alternate {
941                    template.push('#');
942                }
943                if p.format_options.zero_pad {
944                    template.push('0');
945                }
946                if let Some(width) = &p.format_options.width {
947                    match width {
948                        FormatCount::Literal(n) => write!(template, "{n}").unwrap(),
949                        FormatCount::Argument(FormatArgPosition {
950                            index: Ok(n) | Err(n), ..
951                        }) => {
952                            write!(template, "{n}$").unwrap();
953                        }
954                    }
955                }
956                if let Some(precision) = &p.format_options.precision {
957                    template.push('.');
958                    match precision {
959                        FormatCount::Literal(n) => write!(template, "{n}").unwrap(),
960                        FormatCount::Argument(FormatArgPosition {
961                            index: Ok(n) | Err(n), ..
962                        }) => {
963                            write!(template, "{n}$").unwrap();
964                        }
965                    }
966                }
967                match p.format_options.debug_hex {
968                    Some(FormatDebugHex::Lower) => template.push('x'),
969                    Some(FormatDebugHex::Upper) => template.push('X'),
970                    None => {}
971                }
972                template.push_str(match p.format_trait {
973                    FormatTrait::Display => "",
974                    FormatTrait::Debug => "?",
975                    FormatTrait::LowerExp => "e",
976                    FormatTrait::UpperExp => "E",
977                    FormatTrait::Octal => "o",
978                    FormatTrait::Pointer => "p",
979                    FormatTrait::Binary => "b",
980                    FormatTrait::LowerHex => "x",
981                    FormatTrait::UpperHex => "X",
982                });
983                template.push('}');
984            }
985        }
986    }
987    template.push('"');
988    template
989}