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