rustc_ast_pretty/pprust/state/
expr.rs

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