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        let needs_par = {
390            // The Match subexpression in `match x {} - 1` must be parenthesized
391            // if it is the leftmost subexpression in a statement:
392            //
393            //     (match x {}) - 1;
394            //
395            // But not otherwise:
396            //
397            //     let _ = match x {} - 1;
398            //
399            // Same applies to a small set of other expression kinds which
400            // eagerly terminate a statement which opens with them.
401            fixup.would_cause_statement_boundary(expr)
402        } || {
403            // If a binary operation ends up with an attribute, such as
404            // resulting from the following macro expansion, then parentheses
405            // are required so that the attribute encompasses the right
406            // subexpression and not just the left one.
407            //
408            //     #![feature(stmt_expr_attributes)]
409            //
410            //     macro_rules! add_attr {
411            //         ($e:expr) => { #[attr] $e };
412            //     }
413            //
414            //     let _ = add_attr!(1 + 1);
415            //
416            // We must pretty-print `#[attr] (1 + 1)` not `#[attr] 1 + 1`.
417            !attrs.is_empty()
418                && matches!(
419                    expr.kind,
420                    ast::ExprKind::Binary(..)
421                        | ast::ExprKind::Cast(..)
422                        | ast::ExprKind::Assign(..)
423                        | ast::ExprKind::AssignOp(..)
424                        | ast::ExprKind::Range(..)
425                )
426        };
427        if needs_par {
428            self.popen();
429            fixup = FixupContext::default();
430        }
431
432        self.ann.pre(self, AnnNode::Expr(expr));
433
434        match &expr.kind {
435            ast::ExprKind::Array(exprs) => {
436                self.print_expr_vec(exprs);
437            }
438            ast::ExprKind::ConstBlock(anon_const) => {
439                self.print_expr_anon_const(anon_const, attrs);
440            }
441            ast::ExprKind::Repeat(element, count) => {
442                self.print_expr_repeat(element, count);
443            }
444            ast::ExprKind::Struct(se) => {
445                self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
446            }
447            ast::ExprKind::Tup(exprs) => {
448                self.print_expr_tup(exprs);
449            }
450            ast::ExprKind::Call(func, args) => {
451                self.print_expr_call(func, args, fixup);
452            }
453            ast::ExprKind::MethodCall(box ast::MethodCall { seg, receiver, args, .. }) => {
454                self.print_expr_method_call(seg, receiver, args, fixup);
455            }
456            ast::ExprKind::Binary(op, lhs, rhs) => {
457                self.print_expr_binary(op.node, lhs, rhs, fixup);
458            }
459            ast::ExprKind::Unary(op, expr) => {
460                self.print_expr_unary(*op, expr, fixup);
461            }
462            ast::ExprKind::AddrOf(k, m, expr) => {
463                self.print_expr_addr_of(*k, *m, expr, fixup);
464            }
465            ast::ExprKind::Lit(token_lit) => {
466                self.print_token_literal(*token_lit, expr.span);
467            }
468            ast::ExprKind::IncludedBytes(bytes) => {
469                let lit = token::Lit::new(token::ByteStr, escape_byte_str_symbol(bytes), None);
470                self.print_token_literal(lit, expr.span)
471            }
472            ast::ExprKind::Cast(expr, ty) => {
473                self.print_expr_cond_paren(
474                    expr,
475                    expr.precedence() < ExprPrecedence::Cast,
476                    fixup.leftmost_subexpression(),
477                );
478                self.space();
479                self.word_space("as");
480                self.print_type(ty);
481            }
482            ast::ExprKind::Type(expr, ty) => {
483                self.word("builtin # type_ascribe");
484                self.popen();
485                let ib = self.ibox(0);
486                self.print_expr(expr, FixupContext::default());
487
488                self.word(",");
489                self.space_if_not_bol();
490                self.print_type(ty);
491
492                self.end(ib);
493                self.pclose();
494            }
495            ast::ExprKind::Let(pat, scrutinee, _, _) => {
496                self.print_let(pat, scrutinee, fixup);
497            }
498            ast::ExprKind::If(test, blk, elseopt) => self.print_if(test, blk, elseopt.as_deref()),
499            ast::ExprKind::While(test, blk, opt_label) => {
500                if let Some(label) = opt_label {
501                    self.print_ident(label.ident);
502                    self.word_space(":");
503                }
504                let cb = self.cbox(0);
505                let ib = self.ibox(0);
506                self.word_nbsp("while");
507                self.print_expr_as_cond(test);
508                self.space();
509                self.print_block_with_attrs(blk, attrs, cb, ib);
510            }
511            ast::ExprKind::ForLoop { pat, iter, body, label, kind } => {
512                if let Some(label) = label {
513                    self.print_ident(label.ident);
514                    self.word_space(":");
515                }
516                let cb = self.cbox(0);
517                let ib = self.ibox(0);
518                self.word_nbsp("for");
519                if kind == &ForLoopKind::ForAwait {
520                    self.word_nbsp("await");
521                }
522                self.print_pat(pat);
523                self.space();
524                self.word_space("in");
525                self.print_expr_as_cond(iter);
526                self.space();
527                self.print_block_with_attrs(body, attrs, cb, ib);
528            }
529            ast::ExprKind::Loop(blk, opt_label, _) => {
530                let cb = self.cbox(0);
531                let ib = self.ibox(0);
532                if let Some(label) = opt_label {
533                    self.print_ident(label.ident);
534                    self.word_space(":");
535                }
536                self.word_nbsp("loop");
537                self.print_block_with_attrs(blk, attrs, cb, ib);
538            }
539            ast::ExprKind::Match(expr, arms, match_kind) => {
540                let cb = self.cbox(0);
541                let ib = self.ibox(0);
542
543                match match_kind {
544                    MatchKind::Prefix => {
545                        self.word_nbsp("match");
546                        self.print_expr_as_cond(expr);
547                        self.space();
548                    }
549                    MatchKind::Postfix => {
550                        self.print_expr_cond_paren(
551                            expr,
552                            expr.precedence() < ExprPrecedence::Unambiguous,
553                            fixup.leftmost_subexpression_with_dot(),
554                        );
555                        self.word_nbsp(".match");
556                    }
557                }
558
559                self.bopen(ib);
560                self.print_inner_attributes_no_trailing_hardbreak(attrs);
561                for arm in arms {
562                    self.print_arm(arm);
563                }
564                let empty = attrs.is_empty() && arms.is_empty();
565                self.bclose(expr.span, empty, cb);
566            }
567            ast::ExprKind::Closure(box ast::Closure {
568                binder,
569                capture_clause,
570                constness,
571                coroutine_kind,
572                movability,
573                fn_decl,
574                body,
575                fn_decl_span: _,
576                fn_arg_span: _,
577            }) => {
578                self.print_closure_binder(binder);
579                self.print_constness(*constness);
580                self.print_movability(*movability);
581                coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind));
582                self.print_capture_clause(*capture_clause);
583
584                self.print_fn_params_and_ret(fn_decl, true);
585                self.space();
586                self.print_expr(body, FixupContext::default());
587            }
588            ast::ExprKind::Block(blk, opt_label) => {
589                if let Some(label) = opt_label {
590                    self.print_ident(label.ident);
591                    self.word_space(":");
592                }
593                // containing cbox, will be closed by print-block at }
594                let cb = self.cbox(0);
595                // head-box, will be closed by print-block after {
596                let ib = self.ibox(0);
597                self.print_block_with_attrs(blk, attrs, cb, ib);
598            }
599            ast::ExprKind::Gen(capture_clause, blk, kind, _decl_span) => {
600                self.word_nbsp(kind.modifier());
601                self.print_capture_clause(*capture_clause);
602                // cbox/ibox in analogy to the `ExprKind::Block` arm above
603                let cb = self.cbox(0);
604                let ib = self.ibox(0);
605                self.print_block_with_attrs(blk, attrs, cb, ib);
606            }
607            ast::ExprKind::Await(expr, _) => {
608                self.print_expr_cond_paren(
609                    expr,
610                    expr.precedence() < ExprPrecedence::Unambiguous,
611                    fixup.leftmost_subexpression_with_dot(),
612                );
613                self.word(".await");
614            }
615            ast::ExprKind::Use(expr, _) => {
616                self.print_expr_cond_paren(
617                    expr,
618                    expr.precedence() < ExprPrecedence::Unambiguous,
619                    fixup,
620                );
621                self.word(".use");
622            }
623            ast::ExprKind::Assign(lhs, rhs, _) => {
624                self.print_expr_cond_paren(
625                    lhs,
626                    // Ranges are allowed on the right-hand side of assignment,
627                    // but not the left. `(a..b) = c` needs parentheses.
628                    lhs.precedence() <= ExprPrecedence::Range,
629                    fixup.leftmost_subexpression(),
630                );
631                self.space();
632                self.word_space("=");
633                self.print_expr_cond_paren(
634                    rhs,
635                    fixup.precedence(rhs) < ExprPrecedence::Assign,
636                    fixup.rightmost_subexpression(),
637                );
638            }
639            ast::ExprKind::AssignOp(op, lhs, rhs) => {
640                self.print_expr_cond_paren(
641                    lhs,
642                    lhs.precedence() <= ExprPrecedence::Range,
643                    fixup.leftmost_subexpression(),
644                );
645                self.space();
646                self.word_space(op.node.as_str());
647                self.print_expr_cond_paren(
648                    rhs,
649                    fixup.precedence(rhs) < ExprPrecedence::Assign,
650                    fixup.rightmost_subexpression(),
651                );
652            }
653            ast::ExprKind::Field(expr, ident) => {
654                self.print_expr_cond_paren(
655                    expr,
656                    expr.precedence() < ExprPrecedence::Unambiguous,
657                    fixup.leftmost_subexpression_with_dot(),
658                );
659                self.word(".");
660                self.print_ident(*ident);
661            }
662            ast::ExprKind::Index(expr, index, _) => {
663                let expr_fixup = fixup.leftmost_subexpression_with_operator(true);
664                self.print_expr_cond_paren(
665                    expr,
666                    expr_fixup.precedence(expr) < ExprPrecedence::Unambiguous,
667                    expr_fixup,
668                );
669                self.word("[");
670                self.print_expr(index, FixupContext::default());
671                self.word("]");
672            }
673            ast::ExprKind::Range(start, end, limits) => {
674                // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
675                // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
676                // Here we use a fake precedence value so that any child with lower precedence than
677                // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
678                let fake_prec = ExprPrecedence::LOr;
679                if let Some(e) = start {
680                    let start_fixup = fixup.leftmost_subexpression_with_operator(true);
681                    self.print_expr_cond_paren(
682                        e,
683                        start_fixup.precedence(e) < fake_prec,
684                        start_fixup,
685                    );
686                }
687                match limits {
688                    ast::RangeLimits::HalfOpen => self.word(".."),
689                    ast::RangeLimits::Closed => self.word("..="),
690                }
691                if let Some(e) = end {
692                    self.print_expr_cond_paren(
693                        e,
694                        fixup.precedence(e) < fake_prec,
695                        fixup.rightmost_subexpression(),
696                    );
697                }
698            }
699            ast::ExprKind::Underscore => self.word("_"),
700            ast::ExprKind::Path(None, path) => self.print_path(path, true, 0),
701            ast::ExprKind::Path(Some(qself), path) => self.print_qpath(path, qself, true),
702            ast::ExprKind::Break(opt_label, opt_expr) => {
703                self.word("break");
704                if let Some(label) = opt_label {
705                    self.space();
706                    self.print_ident(label.ident);
707                }
708                if let Some(expr) = opt_expr {
709                    self.space();
710                    self.print_expr_cond_paren(
711                        expr,
712                        // Parenthesize `break 'inner: loop { break 'inner 1 } + 1`
713                        //                     ^---------------------------------^
714                        opt_label.is_none() && classify::leading_labeled_expr(expr),
715                        fixup.rightmost_subexpression(),
716                    );
717                }
718            }
719            ast::ExprKind::Continue(opt_label) => {
720                self.word("continue");
721                if let Some(label) = opt_label {
722                    self.space();
723                    self.print_ident(label.ident);
724                }
725            }
726            ast::ExprKind::Ret(result) => {
727                self.word("return");
728                if let Some(expr) = result {
729                    self.word(" ");
730                    self.print_expr(expr, fixup.rightmost_subexpression());
731                }
732            }
733            ast::ExprKind::Yeet(result) => {
734                self.word("do");
735                self.word(" ");
736                self.word("yeet");
737                if let Some(expr) = result {
738                    self.word(" ");
739                    self.print_expr(expr, fixup.rightmost_subexpression());
740                }
741            }
742            ast::ExprKind::Become(result) => {
743                self.word("become");
744                self.word(" ");
745                self.print_expr(result, fixup.rightmost_subexpression());
746            }
747            ast::ExprKind::InlineAsm(a) => {
748                // FIXME: Print `builtin # asm` once macro `asm` uses `builtin_syntax`.
749                self.word("asm!");
750                self.print_inline_asm(a);
751            }
752            ast::ExprKind::FormatArgs(fmt) => {
753                // FIXME: Print `builtin # format_args` once macro `format_args` uses `builtin_syntax`.
754                self.word("format_args!");
755                self.popen();
756                let ib = self.ibox(0);
757                self.word(reconstruct_format_args_template_string(&fmt.template));
758                for arg in fmt.arguments.all_args() {
759                    self.word_space(",");
760                    self.print_expr(&arg.expr, FixupContext::default());
761                }
762                self.end(ib);
763                self.pclose();
764            }
765            ast::ExprKind::OffsetOf(container, fields) => {
766                self.word("builtin # offset_of");
767                self.popen();
768                let ib = self.ibox(0);
769                self.print_type(container);
770                self.word(",");
771                self.space();
772
773                if let Some((&first, rest)) = fields.split_first() {
774                    self.print_ident(first);
775
776                    for &field in rest {
777                        self.word(".");
778                        self.print_ident(field);
779                    }
780                }
781                self.end(ib);
782                self.pclose();
783            }
784            ast::ExprKind::MacCall(m) => self.print_mac(m),
785            ast::ExprKind::Paren(e) => {
786                self.popen();
787                self.print_expr(e, FixupContext::default());
788                self.pclose();
789            }
790            ast::ExprKind::Yield(YieldKind::Prefix(e)) => {
791                self.word("yield");
792
793                if let Some(expr) = e {
794                    self.space();
795                    self.print_expr(expr, fixup.rightmost_subexpression());
796                }
797            }
798            ast::ExprKind::Yield(YieldKind::Postfix(e)) => {
799                self.print_expr_cond_paren(
800                    e,
801                    e.precedence() < ExprPrecedence::Unambiguous,
802                    fixup.leftmost_subexpression_with_dot(),
803                );
804                self.word(".yield");
805            }
806            ast::ExprKind::Try(e) => {
807                self.print_expr_cond_paren(
808                    e,
809                    e.precedence() < ExprPrecedence::Unambiguous,
810                    fixup.leftmost_subexpression_with_dot(),
811                );
812                self.word("?")
813            }
814            ast::ExprKind::TryBlock(blk) => {
815                let cb = self.cbox(0);
816                let ib = self.ibox(0);
817                self.word_nbsp("try");
818                self.print_block_with_attrs(blk, attrs, cb, ib)
819            }
820            ast::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
821                self.word("builtin # ");
822                match kind {
823                    ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder"),
824                    ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder"),
825                }
826                self.popen();
827                let ib = self.ibox(0);
828                self.print_expr(expr, FixupContext::default());
829
830                if let Some(ty) = ty {
831                    self.word(",");
832                    self.space();
833                    self.print_type(ty);
834                }
835
836                self.end(ib);
837                self.pclose();
838            }
839            ast::ExprKind::Err(_) => {
840                self.popen();
841                self.word("/*ERROR*/");
842                self.pclose()
843            }
844            ast::ExprKind::Dummy => {
845                self.popen();
846                self.word("/*DUMMY*/");
847                self.pclose();
848            }
849        }
850
851        self.ann.post(self, AnnNode::Expr(expr));
852
853        if needs_par {
854            self.pclose();
855        }
856
857        self.end(ib);
858    }
859
860    fn print_arm(&mut self, arm: &ast::Arm) {
861        // Note, I have no idea why this check is necessary, but here it is.
862        if arm.attrs.is_empty() {
863            self.space();
864        }
865        let cb = self.cbox(INDENT_UNIT);
866        let ib = self.ibox(0);
867        self.maybe_print_comment(arm.pat.span.lo());
868        self.print_outer_attributes(&arm.attrs);
869        self.print_pat(&arm.pat);
870        self.space();
871        if let Some(e) = &arm.guard {
872            self.word_space("if");
873            self.print_expr(e, FixupContext::default());
874            self.space();
875        }
876
877        if let Some(body) = &arm.body {
878            self.word_space("=>");
879
880            match &body.kind {
881                ast::ExprKind::Block(blk, opt_label) => {
882                    if let Some(label) = opt_label {
883                        self.print_ident(label.ident);
884                        self.word_space(":");
885                    }
886
887                    self.print_block_unclosed_indent(blk, ib);
888
889                    // If it is a user-provided unsafe block, print a comma after it.
890                    if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
891                        self.word(",");
892                    }
893                }
894                _ => {
895                    self.end(ib);
896                    self.print_expr(body, FixupContext::new_match_arm());
897                    self.word(",");
898                }
899            }
900        } else {
901            self.end(ib);
902            self.word(",");
903        }
904        self.end(cb);
905    }
906
907    fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
908        match binder {
909            ast::ClosureBinder::NotPresent => {}
910            ast::ClosureBinder::For { generic_params, .. } => {
911                self.print_formal_generic_params(generic_params)
912            }
913        }
914    }
915
916    fn print_movability(&mut self, movability: ast::Movability) {
917        match movability {
918            ast::Movability::Static => self.word_space("static"),
919            ast::Movability::Movable => {}
920        }
921    }
922
923    fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
924        match capture_clause {
925            ast::CaptureBy::Value { .. } => self.word_space("move"),
926            ast::CaptureBy::Use { .. } => self.word_space("use"),
927            ast::CaptureBy::Ref => {}
928        }
929    }
930}
931
932fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String {
933    let mut template = "\"".to_string();
934    for piece in pieces {
935        match piece {
936            FormatArgsPiece::Literal(s) => {
937                for c in s.as_str().chars() {
938                    template.extend(c.escape_debug());
939                    if let '{' | '}' = c {
940                        template.push(c);
941                    }
942                }
943            }
944            FormatArgsPiece::Placeholder(p) => {
945                template.push('{');
946                let (Ok(n) | Err(n)) = p.argument.index;
947                write!(template, "{n}").unwrap();
948                if p.format_options != Default::default() || p.format_trait != FormatTrait::Display
949                {
950                    template.push(':');
951                }
952                if let Some(fill) = p.format_options.fill {
953                    template.push(fill);
954                }
955                match p.format_options.alignment {
956                    Some(FormatAlignment::Left) => template.push('<'),
957                    Some(FormatAlignment::Right) => template.push('>'),
958                    Some(FormatAlignment::Center) => template.push('^'),
959                    None => {}
960                }
961                match p.format_options.sign {
962                    Some(FormatSign::Plus) => template.push('+'),
963                    Some(FormatSign::Minus) => template.push('-'),
964                    None => {}
965                }
966                if p.format_options.alternate {
967                    template.push('#');
968                }
969                if p.format_options.zero_pad {
970                    template.push('0');
971                }
972                if let Some(width) = &p.format_options.width {
973                    match width {
974                        FormatCount::Literal(n) => write!(template, "{n}").unwrap(),
975                        FormatCount::Argument(FormatArgPosition {
976                            index: Ok(n) | Err(n), ..
977                        }) => {
978                            write!(template, "{n}$").unwrap();
979                        }
980                    }
981                }
982                if let Some(precision) = &p.format_options.precision {
983                    template.push('.');
984                    match precision {
985                        FormatCount::Literal(n) => write!(template, "{n}").unwrap(),
986                        FormatCount::Argument(FormatArgPosition {
987                            index: Ok(n) | Err(n), ..
988                        }) => {
989                            write!(template, "{n}$").unwrap();
990                        }
991                    }
992                }
993                match p.format_options.debug_hex {
994                    Some(FormatDebugHex::Lower) => template.push('x'),
995                    Some(FormatDebugHex::Upper) => template.push('X'),
996                    None => {}
997                }
998                template.push_str(match p.format_trait {
999                    FormatTrait::Display => "",
1000                    FormatTrait::Debug => "?",
1001                    FormatTrait::LowerExp => "e",
1002                    FormatTrait::UpperExp => "E",
1003                    FormatTrait::Octal => "o",
1004                    FormatTrait::Pointer => "p",
1005                    FormatTrait::Binary => "b",
1006                    FormatTrait::LowerHex => "x",
1007                    FormatTrait::UpperHex => "X",
1008                });
1009                template.push('}');
1010            }
1011        }
1012    }
1013    template.push('"');
1014    template
1015}