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_marker,
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_marker
599                    .map(|coroutine_marker| self.print_coroutine_marker(coroutine_marker));
600                self.print_capture_clause(*capture_clause);
601
602                self.print_fn_params_and_ret(fn_decl, true);
603                self.space();
604                self.print_expr(body, FixupContext::default());
605            }
606            ast::ExprKind::Block(blk, opt_label) => {
607                if let Some(label) = opt_label {
608                    self.print_ident(label.ident);
609                    self.word_space(":");
610                }
611                // containing cbox, will be closed by print-block at }
612                let cb = self.cbox(0);
613                // head-box, will be closed by print-block after {
614                let ib = self.ibox(0);
615                self.print_block_with_attrs(blk, attrs, cb, ib);
616            }
617            ast::ExprKind::Gen(capture_clause, blk, kind, _decl_span) => {
618                self.word_nbsp(kind.as_str());
619                self.print_capture_clause(*capture_clause);
620                // cbox/ibox in analogy to the `ExprKind::Block` arm above
621                let cb = self.cbox(0);
622                let ib = self.ibox(0);
623                self.print_block_with_attrs(blk, attrs, cb, ib);
624            }
625            ast::ExprKind::Await(expr, _) => {
626                self.print_expr_cond_paren(
627                    expr,
628                    expr.precedence() < ExprPrecedence::Unambiguous,
629                    fixup.leftmost_subexpression_with_dot(),
630                );
631                self.word(".await");
632            }
633            ast::ExprKind::Move(expr, _) => {
634                self.word("move(");
635                self.print_expr(expr, FixupContext::default());
636                self.word(")");
637            }
638            ast::ExprKind::Use(expr, _) => {
639                self.print_expr_cond_paren(
640                    expr,
641                    expr.precedence() < ExprPrecedence::Unambiguous,
642                    fixup,
643                );
644                self.word(".use");
645            }
646            ast::ExprKind::Assign(lhs, rhs, _) => {
647                self.print_expr_cond_paren(
648                    lhs,
649                    // Ranges are allowed on the right-hand side of assignment,
650                    // but not the left. `(a..b) = c` needs parentheses.
651                    lhs.precedence() <= ExprPrecedence::Range,
652                    fixup.leftmost_subexpression(),
653                );
654                self.space();
655                self.word_space("=");
656                self.print_expr_cond_paren(
657                    rhs,
658                    fixup.precedence(rhs) < ExprPrecedence::Assign,
659                    fixup.rightmost_subexpression(),
660                );
661            }
662            ast::ExprKind::AssignOp(op, lhs, rhs) => {
663                self.print_expr_cond_paren(
664                    lhs,
665                    lhs.precedence() <= ExprPrecedence::Range,
666                    fixup.leftmost_subexpression(),
667                );
668                self.space();
669                self.word_space(op.node.as_str());
670                self.print_expr_cond_paren(
671                    rhs,
672                    fixup.precedence(rhs) < ExprPrecedence::Assign,
673                    fixup.rightmost_subexpression(),
674                );
675            }
676            ast::ExprKind::Field(expr, ident) => {
677                let needs_paren = expr.precedence() < ExprPrecedence::Unambiguous;
678                self.print_expr_cond_paren(
679                    expr,
680                    needs_paren,
681                    fixup.leftmost_subexpression_with_dot(),
682                );
683                if !needs_paren && expr_ends_with_dot(expr) {
684                    self.word(" ");
685                }
686                self.word(".");
687                self.print_ident(*ident);
688            }
689            ast::ExprKind::Index(expr, index, _) => {
690                let expr_fixup = fixup.leftmost_subexpression_with_operator(true);
691                self.print_expr_cond_paren(
692                    expr,
693                    expr_fixup.precedence(expr) < ExprPrecedence::Unambiguous
694                        || classify::expr_is_complete(expr),
695                    expr_fixup,
696                );
697                self.word("[");
698                self.print_expr(index, FixupContext::default());
699                self.word("]");
700            }
701            ast::ExprKind::Range(start, end, limits) => {
702                // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
703                // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
704                // Here we use a fake precedence value so that any child with lower precedence than
705                // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
706                let fake_prec = ExprPrecedence::LOr;
707                if let Some(e) = start {
708                    let start_fixup = fixup.leftmost_subexpression_with_operator(true);
709                    let needs_paren = start_fixup.precedence(e) < fake_prec;
710                    self.print_expr_cond_paren(e, needs_paren, start_fixup);
711                    // If the start expression is a float literal ending with
712                    // `.`, we need a space before `..` or `..=` so that the
713                    // dots don't merge. E.g. `0. ..45.` must not become
714                    // `0...45.`.
715                    if !needs_paren && expr_ends_with_dot(e) {
716                        self.word(" ");
717                    }
718                }
719                match limits {
720                    ast::RangeLimits::HalfOpen => self.word(".."),
721                    ast::RangeLimits::Closed => self.word("..="),
722                }
723                if let Some(e) = end {
724                    self.print_expr_cond_paren(
725                        e,
726                        fixup.precedence(e) < fake_prec,
727                        fixup.rightmost_subexpression(),
728                    );
729                }
730            }
731            ast::ExprKind::Underscore => self.word("_"),
732            ast::ExprKind::Path(None, path) => self.print_path(path, true, 0),
733            ast::ExprKind::Path(Some(qself), path) => self.print_qpath(path, qself, true),
734            ast::ExprKind::Break(opt_label, opt_expr) => {
735                self.word("break");
736                if let Some(label) = opt_label {
737                    self.space();
738                    self.print_ident(label.ident);
739                }
740                if let Some(expr) = opt_expr {
741                    self.space();
742                    self.print_expr_cond_paren(
743                        expr,
744                        // Parenthesize `break 'inner: loop { break 'inner 1 } + 1`
745                        //                     ^---------------------------------^
746                        opt_label.is_none() && classify::leading_labeled_expr(expr),
747                        fixup.rightmost_subexpression(),
748                    );
749                }
750            }
751            ast::ExprKind::Continue(opt_label) => {
752                self.word("continue");
753                if let Some(label) = opt_label {
754                    self.space();
755                    self.print_ident(label.ident);
756                }
757            }
758            ast::ExprKind::Ret(result) => {
759                self.word("return");
760                if let Some(expr) = result {
761                    self.word(" ");
762                    self.print_expr(expr, fixup.rightmost_subexpression());
763                }
764            }
765            ast::ExprKind::Yeet(result) => {
766                self.word("do");
767                self.word(" ");
768                self.word("yeet");
769                if let Some(expr) = result {
770                    self.word(" ");
771                    self.print_expr(expr, fixup.rightmost_subexpression());
772                }
773            }
774            ast::ExprKind::Become(result) => {
775                self.word("become");
776                self.word(" ");
777                self.print_expr(result, fixup.rightmost_subexpression());
778            }
779            ast::ExprKind::InlineAsm(a) => {
780                // FIXME: Print `builtin # asm` once macro `asm` uses `builtin_syntax`.
781                self.word(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}!", a.asm_macro.macro_name()))
    })format!("{}!", a.asm_macro.macro_name()));
782                self.print_inline_asm(a);
783            }
784            ast::ExprKind::FormatArgs(fmt) => {
785                // FIXME: Print `builtin # format_args` once macro `format_args` uses `builtin_syntax`.
786                self.word("format_args!");
787                self.popen();
788                let ib = self.ibox(0);
789                self.word(reconstruct_format_args_template_string(&fmt.template));
790                for arg in fmt.arguments.all_args() {
791                    self.word_space(",");
792                    self.print_expr(&arg.expr, FixupContext::default());
793                }
794                self.end(ib);
795                self.pclose();
796            }
797            ast::ExprKind::OffsetOf(container, fields) => {
798                self.word("builtin # offset_of");
799                self.popen();
800                let ib = self.ibox(0);
801                self.print_type(container);
802                self.word(",");
803                self.space();
804
805                if let Some((&first, rest)) = fields.split_first() {
806                    self.print_ident(first);
807
808                    for &field in rest {
809                        self.word(".");
810                        self.print_ident(field);
811                    }
812                }
813                self.end(ib);
814                self.pclose();
815            }
816            ast::ExprKind::MacCall(m) => self.print_mac(m),
817            ast::ExprKind::Paren(e) => {
818                self.popen();
819                self.print_expr(e, FixupContext::default());
820                self.pclose();
821            }
822            ast::ExprKind::Yield(YieldKind::Prefix(e)) => {
823                self.word("yield");
824
825                if let Some(expr) = e {
826                    self.space();
827                    self.print_expr(expr, fixup.rightmost_subexpression());
828                }
829            }
830            ast::ExprKind::Yield(YieldKind::Postfix(e)) => {
831                self.print_expr_cond_paren(
832                    e,
833                    e.precedence() < ExprPrecedence::Unambiguous,
834                    fixup.leftmost_subexpression_with_dot(),
835                );
836                self.word(".yield");
837            }
838            ast::ExprKind::Try(e) => {
839                self.print_expr_cond_paren(
840                    e,
841                    e.precedence() < ExprPrecedence::Unambiguous,
842                    fixup.leftmost_subexpression_with_dot(),
843                );
844                self.word("?")
845            }
846            ast::ExprKind::TryBlock(blk, opt_ty) => {
847                let cb = self.cbox(0);
848                let ib = self.ibox(0);
849                self.word_nbsp("try");
850                if let Some(ty) = opt_ty {
851                    self.word_nbsp("bikeshed");
852                    self.print_type(ty);
853                    self.space();
854                }
855                self.print_block_with_attrs(blk, attrs, cb, ib)
856            }
857            ast::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
858                self.word("builtin # ");
859                match kind {
860                    ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder"),
861                    ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder"),
862                }
863                self.popen();
864                let ib = self.ibox(0);
865                self.print_expr(expr, FixupContext::default());
866
867                if let Some(ty) = ty {
868                    self.word(",");
869                    self.space();
870                    self.print_type(ty);
871                }
872
873                self.end(ib);
874                self.pclose();
875            }
876            ast::ExprKind::Err(_) => {
877                self.popen();
878                self.word("/*ERROR*/");
879                self.pclose()
880            }
881            ast::ExprKind::Dummy => {
882                self.popen();
883                self.word("/*DUMMY*/");
884                self.pclose();
885            }
886            ast::ExprKind::DirectConstArg(expr) => {
887                self.word_nbsp("core::direct_const_arg!");
888                self.popen();
889                self.print_expr(expr, FixupContext::default());
890                self.pclose()
891            }
892        }
893
894        self.ann.post(self, AnnNode::Expr(expr));
895
896        if needs_par {
897            self.pclose();
898        }
899
900        self.end(ib);
901    }
902
903    fn print_arm(&mut self, arm: &ast::Arm) {
904        // Note, I have no idea why this check is necessary, but here it is.
905        if arm.attrs.is_empty() {
906            self.space();
907        }
908        let cb = self.cbox(INDENT_UNIT);
909        let ib = self.ibox(0);
910        self.maybe_print_comment(arm.pat.span.lo());
911        self.print_outer_attributes(&arm.attrs);
912        self.print_pat(&arm.pat);
913        self.space();
914        if let Some(guard) = &arm.guard {
915            self.word_space("if");
916            self.print_expr(&guard.cond, FixupContext::default());
917            self.space();
918        }
919
920        if let Some(body) = &arm.body {
921            self.word_space("=>");
922
923            match &body.kind {
924                ast::ExprKind::Block(blk, opt_label) => {
925                    if let Some(label) = opt_label {
926                        self.print_ident(label.ident);
927                        self.word_space(":");
928                    }
929
930                    self.print_block_unclosed_indent(blk, ib);
931
932                    // If it is a user-provided unsafe block, print a comma after it.
933                    if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
934                        self.word(",");
935                    }
936                }
937                _ => {
938                    self.end(ib);
939                    self.print_expr(body, FixupContext::new_match_arm());
940                    self.word(",");
941                }
942            }
943        } else {
944            self.end(ib);
945            self.word(",");
946        }
947        self.end(cb);
948    }
949
950    fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
951        match binder {
952            ast::ClosureBinder::NotPresent => {}
953            ast::ClosureBinder::For { generic_params, .. } => {
954                self.print_formal_generic_params(generic_params)
955            }
956        }
957    }
958
959    fn print_movability(&mut self, movability: ast::Movability) {
960        match movability {
961            ast::Movability::Static => self.word_space("static"),
962            ast::Movability::Movable => {}
963        }
964    }
965
966    fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
967        match capture_clause {
968            ast::CaptureBy::Value { .. } => self.word_space("move"),
969            ast::CaptureBy::Use { .. } => self.word_space("use"),
970            ast::CaptureBy::Ref => {}
971        }
972    }
973}
974
975fn reconstruct_format_args_template_string(pieces: &[FormatArgsPiece]) -> String {
976    let mut template = "\"".to_string();
977    for piece in pieces {
978        match piece {
979            FormatArgsPiece::Literal(s) => {
980                for c in s.as_str().chars() {
981                    template.extend(c.escape_debug());
982                    if let '{' | '}' = c {
983                        template.push(c);
984                    }
985                }
986            }
987            FormatArgsPiece::Placeholder(p) => {
988                template.push('{');
989                let (Ok(n) | Err(n)) = p.argument.index;
990                template.write_fmt(format_args!("{0}", n))write!(template, "{n}").unwrap();
991                if p.format_options != Default::default() || p.format_trait != FormatTrait::Display
992                {
993                    template.push(':');
994                }
995                if let Some(fill) = p.format_options.fill {
996                    template.push(fill);
997                }
998                match p.format_options.alignment {
999                    Some(FormatAlignment::Left) => template.push('<'),
1000                    Some(FormatAlignment::Right) => template.push('>'),
1001                    Some(FormatAlignment::Center) => template.push('^'),
1002                    None => {}
1003                }
1004                match p.format_options.sign {
1005                    Some(FormatSign::Plus) => template.push('+'),
1006                    Some(FormatSign::Minus) => template.push('-'),
1007                    None => {}
1008                }
1009                if p.format_options.alternate {
1010                    template.push('#');
1011                }
1012                if p.format_options.zero_pad {
1013                    template.push('0');
1014                }
1015                if let Some(width) = &p.format_options.width {
1016                    match width {
1017                        FormatCount::Literal(n) => template.write_fmt(format_args!("{0}", n))write!(template, "{n}").unwrap(),
1018                        FormatCount::Argument(FormatArgPosition {
1019                            index: Ok(n) | Err(n), ..
1020                        }) => {
1021                            template.write_fmt(format_args!("{0}$", n))write!(template, "{n}$").unwrap();
1022                        }
1023                    }
1024                }
1025                if let Some(precision) = &p.format_options.precision {
1026                    template.push('.');
1027                    match precision {
1028                        FormatCount::Literal(n) => template.write_fmt(format_args!("{0}", n))write!(template, "{n}").unwrap(),
1029                        FormatCount::Argument(FormatArgPosition {
1030                            index: Ok(n) | Err(n), ..
1031                        }) => {
1032                            template.write_fmt(format_args!("{0}$", n))write!(template, "{n}$").unwrap();
1033                        }
1034                    }
1035                }
1036                match p.format_options.debug_hex {
1037                    Some(FormatDebugHex::Lower) => template.push('x'),
1038                    Some(FormatDebugHex::Upper) => template.push('X'),
1039                    None => {}
1040                }
1041                template.push_str(match p.format_trait {
1042                    FormatTrait::Display => "",
1043                    FormatTrait::Debug => "?",
1044                    FormatTrait::LowerExp => "e",
1045                    FormatTrait::UpperExp => "E",
1046                    FormatTrait::Octal => "o",
1047                    FormatTrait::Pointer => "p",
1048                    FormatTrait::Binary => "b",
1049                    FormatTrait::LowerHex => "x",
1050                    FormatTrait::UpperHex => "X",
1051                });
1052                template.push('}');
1053            }
1054        }
1055    }
1056    template.push('"');
1057    template
1058}
1059
1060/// Returns `true` if the printed representation of this expression ends with
1061/// a `.` character — specifically, an unsuffixed float literal like `0.` or
1062/// `45.`. This is used to insert whitespace before range operators (`..`,
1063/// `..=`) so that the dots don't merge (e.g. `0. ..45.` instead of `0...45.`).
1064fn expr_ends_with_dot(expr: &ast::Expr) -> bool {
1065    match &expr.kind {
1066        ast::ExprKind::Lit(token_lit) => {
1067            token_lit.kind == token::Float
1068                && token_lit.suffix.is_none()
1069                && token_lit.symbol.as_str().ends_with('.')
1070        }
1071        _ => false,
1072    }
1073}