Skip to main content

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