Skip to main content

rustc_ast_pretty/pprust/state/
expr.rs

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