Skip to main content

rustfmt_nightly/
expr.rs

1use std::borrow::Cow;
2use std::cmp::min;
3
4use itertools::Itertools;
5use rustc_ast::token::{Delimiter, Lit, LitKind};
6use rustc_ast::{ForLoopKind, MatchKind, ast, token};
7use rustc_span::{BytePos, Span};
8use tracing::debug;
9
10use crate::chains::rewrite_chain;
11use crate::closures;
12use crate::comment::{
13    CharClasses, FindUncommented, combine_strs_with_missing_comments, contains_comment,
14    recover_comment_removed, rewrite_comment, rewrite_missing_comment,
15};
16use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, StyleEdition};
17use crate::config::{FloatLiteralTrailingZero, lists::*};
18use crate::lists::{
19    ListFormatting, Separator, definitive_tactic, itemize_list, shape_for_tactic,
20    struct_lit_formatting, struct_lit_shape, struct_lit_tactic, write_list,
21};
22use crate::macros::{MacroPosition, rewrite_macro};
23use crate::matches::rewrite_match;
24use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
25use crate::pairs::{PairParts, rewrite_all_pairs, rewrite_pair};
26use crate::range::rewrite_range;
27use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
28use crate::shape::{Indent, Shape};
29use crate::source_map::{LineRangeUtils, SpanUtils};
30use crate::spanned::Spanned;
31use crate::stmt;
32use crate::string::{StringFormat, rewrite_string};
33use crate::types::{PathContext, rewrite_path};
34use crate::utils::{
35    colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with,
36    inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
37    semicolon_for_expr, unicode_str_width, wrap_str,
38};
39use crate::vertical::rewrite_with_alignment;
40use crate::visitor::FmtVisitor;
41
42impl Rewrite for ast::Expr {
43    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
44        self.rewrite_result(context, shape).ok()
45    }
46
47    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
48        format_expr(self, ExprType::SubExpression, context, shape)
49    }
50}
51
52#[derive(Copy, Clone, PartialEq)]
53pub(crate) enum ExprType {
54    Statement,
55    SubExpression,
56}
57
58pub(crate) fn lit_ends_in_dot(lit: &Lit, context: &RewriteContext<'_>) -> bool {
59    match lit.kind {
60        LitKind::Float => float_lit_ends_in_dot(
61            lit.symbol.as_str(),
62            lit.suffix.as_ref().map(|s| s.as_str()),
63            context.config.float_literal_trailing_zero(),
64        ),
65        _ => false,
66    }
67}
68
69pub(crate) fn float_lit_ends_in_dot(
70    symbol: &str,
71    suffix: Option<&str>,
72    float_literal_trailing_zero: FloatLiteralTrailingZero,
73) -> bool {
74    match float_literal_trailing_zero {
75        FloatLiteralTrailingZero::Preserve => symbol.ends_with('.') && suffix.is_none(),
76        FloatLiteralTrailingZero::IfNoPostfix | FloatLiteralTrailingZero::Always => false,
77        FloatLiteralTrailingZero::Never => {
78            let float_parts = parse_float_symbol(symbol).unwrap();
79            let has_postfix = float_parts.exponent.is_some() || suffix.is_some();
80            let fractional_part_zero = float_parts.is_fractional_part_zero();
81            !has_postfix && fractional_part_zero
82        }
83    }
84}
85
86pub(crate) fn format_expr(
87    expr: &ast::Expr,
88    expr_type: ExprType,
89    context: &RewriteContext<'_>,
90    shape: Shape,
91) -> RewriteResult {
92    skip_out_of_file_lines_range_err!(context, expr.span);
93
94    if contains_skip(&*expr.attrs) {
95        return Ok(context.snippet(expr.span()).to_owned());
96    }
97    let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
98        shape.sub_width(1, expr.span)?
99    } else {
100        shape
101    };
102
103    let expr_rw = match expr.kind {
104        ast::ExprKind::Array(ref expr_vec) => rewrite_array(
105            "",
106            expr_vec.iter(),
107            expr.span,
108            context,
109            shape,
110            choose_separator_tactic(context, expr.span),
111            None,
112        ),
113        ast::ExprKind::Lit(token_lit) => {
114            if let Ok(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
115                Ok(expr_rw)
116            } else {
117                if let LitKind::StrRaw(_) = token_lit.kind {
118                    Ok(context.snippet(expr.span).trim().into())
119                } else {
120                    Err(RewriteError::Unknown)
121                }
122            }
123        }
124        ast::ExprKind::Call(ref callee, ref args) => {
125            let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
126            let callee_str = callee.rewrite_result(context, shape)?;
127            rewrite_call(context, &callee_str, args, inner_span, shape)
128        }
129        ast::ExprKind::Move(ref subexpr, move_kw_span) => {
130            let inner_span = mk_sp(move_kw_span.hi(), expr.span.hi());
131            rewrite_call(
132                context,
133                "move",
134                std::slice::from_ref(subexpr),
135                inner_span,
136                shape,
137            )
138        }
139        ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
140        ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
141            // FIXME: format comments between operands and operator
142            rewrite_all_pairs(expr, shape, context).or_else(|_| {
143                rewrite_pair(
144                    &**lhs,
145                    &**rhs,
146                    PairParts::infix(&format!(" {} ", context.snippet(op.span))),
147                    context,
148                    shape,
149                    context.config.binop_separator(),
150                )
151            })
152        }
153        ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
154        ast::ExprKind::Struct(ref struct_expr) => {
155            let ast::StructExpr {
156                qself,
157                fields,
158                path,
159                rest,
160            } = &**struct_expr;
161            rewrite_struct_lit(
162                context,
163                path,
164                qself,
165                fields,
166                rest,
167                &expr.attrs,
168                expr.span,
169                shape,
170            )
171        }
172        ast::ExprKind::Tup(ref items) => {
173            rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
174        }
175        ast::ExprKind::Let(ref pat, ref expr, _span, _) => rewrite_let(context, shape, pat, expr),
176        ast::ExprKind::If(..)
177        | ast::ExprKind::ForLoop { .. }
178        | ast::ExprKind::Loop(..)
179        | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
180            .unknown_error()
181            .and_then(|control_flow| control_flow.rewrite_result(context, shape)),
182        ast::ExprKind::ConstBlock(ref anon_const) => {
183            let rewrite = match anon_const.value.kind {
184                ast::ExprKind::Block(ref block, opt_label) => {
185                    // Inner attributes are associated with the `ast::ExprKind::ConstBlock` node,
186                    // not the `ast::Block` node we're about to rewrite. To prevent dropping inner
187                    // attributes call `rewrite_block` directly.
188                    // See https://github.com/rust-lang/rustfmt/issues/6158
189                    rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)?
190                }
191                _ => anon_const.rewrite_result(context, shape)?,
192            };
193            Ok(format!("const {}", rewrite))
194        }
195        ast::ExprKind::Block(ref block, opt_label) => {
196            match expr_type {
197                ExprType::Statement => {
198                    if is_unsafe_block(block) {
199                        rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
200                    } else if let Some(rw) =
201                        rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
202                    {
203                        // Rewrite block without trying to put it in a single line.
204                        Ok(rw)
205                    } else {
206                        let prefix = block_prefix(context, block, shape)?;
207
208                        rewrite_block_with_visitor(
209                            context,
210                            &prefix,
211                            block,
212                            Some(&expr.attrs),
213                            opt_label,
214                            shape,
215                            true,
216                        )
217                    }
218                }
219                ExprType::SubExpression => {
220                    rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
221                }
222            }
223        }
224        ast::ExprKind::Match(ref cond, ref arms, kind) => {
225            rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs, kind)
226        }
227        ast::ExprKind::Path(ref qself, ref path) => {
228            rewrite_path(context, PathContext::Expr, qself, path, shape)
229        }
230        ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
231            rewrite_assignment(context, lhs, rhs, None, shape)
232        }
233        ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
234            rewrite_assignment(context, lhs, rhs, Some(op), shape)
235        }
236        ast::ExprKind::Continue(ref opt_label) => {
237            let id_str = match *opt_label {
238                Some(label) => {
239                    // Ident lose the `r#` prefix in raw labels, so use the original snippet
240                    let label_name = context.snippet(label.ident.span);
241                    format!(" {}", label_name)
242                }
243                None => String::new(),
244            };
245            Ok(format!("continue{id_str}"))
246        }
247        ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
248            let id_str = match *opt_label {
249                Some(label) => {
250                    // Ident lose the `r#` prefix in raw labels, so use the original snippet
251                    let label_name = context.snippet(label.ident.span);
252                    format!(" {}", label_name)
253                }
254                None => String::new(),
255            };
256
257            if let Some(ref expr) = *opt_expr {
258                rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape)
259            } else {
260                Ok(format!("break{id_str}"))
261            }
262        }
263        ast::ExprKind::Yield(ast::YieldKind::Prefix(ref opt_expr)) => {
264            if let Some(ref expr) = *opt_expr {
265                rewrite_unary_prefix(context, "yield ", &**expr, shape)
266            } else {
267                Ok("yield".to_string())
268            }
269        }
270        ast::ExprKind::Closure(ref cl) => closures::rewrite_closure(
271            &cl.binder,
272            cl.constness,
273            cl.capture_clause,
274            &cl.coroutine_kind,
275            cl.movability,
276            &cl.fn_decl,
277            &cl.body,
278            expr.span,
279            context,
280            shape,
281        ),
282        ast::ExprKind::Try(..)
283        | ast::ExprKind::Field(..)
284        | ast::ExprKind::MethodCall(..)
285        | ast::ExprKind::Await(_, _)
286        | ast::ExprKind::Use(_, _)
287        | ast::ExprKind::Yield(ast::YieldKind::Postfix(_)) => rewrite_chain(expr, context, shape),
288        ast::ExprKind::MacCall(ref mac) => {
289            rewrite_macro(mac, context, shape, MacroPosition::Expression).or_else(|_| {
290                wrap_str(
291                    context.snippet(expr.span).to_owned(),
292                    context.config.max_width(),
293                    shape,
294                )
295                .max_width_error(shape.width, expr.span)
296            })
297        }
298        ast::ExprKind::Ret(None) => Ok("return".to_owned()),
299        ast::ExprKind::Ret(Some(ref expr)) => {
300            rewrite_unary_prefix(context, "return ", &**expr, shape)
301        }
302        ast::ExprKind::Become(ref expr) => rewrite_unary_prefix(context, "become ", &**expr, shape),
303        ast::ExprKind::Yeet(None) => Ok("do yeet".to_owned()),
304        ast::ExprKind::Yeet(Some(ref expr)) => {
305            rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
306        }
307        ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
308            rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
309        }
310        ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
311            &**expr,
312            &**ty,
313            PairParts::infix(" as "),
314            context,
315            shape,
316            SeparatorPlace::Front,
317        ),
318        ast::ExprKind::Index(ref expr, ref index, _) => {
319            rewrite_index(&**expr, &**index, context, shape)
320        }
321        ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
322            &**expr,
323            &*repeats.value,
324            PairParts::new("[", "; ", "]"),
325            context,
326            shape,
327            SeparatorPlace::Back,
328        ),
329        ast::ExprKind::Range(ref lhs, ref rhs, limits) => rewrite_range(
330            context,
331            shape,
332            lhs.as_deref(),
333            rhs.as_deref(),
334            limits.as_str(),
335        ),
336        // We do not format these expressions yet, but they should still
337        // satisfy our width restrictions.
338        // Style Guide RFC for InlineAsm variant pending
339        // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
340        ast::ExprKind::InlineAsm(..) => Ok(context.snippet(expr.span).to_owned()),
341        ast::ExprKind::TryBlock(ref block, None) => {
342            if let rw @ Ok(_) =
343                rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
344            {
345                rw
346            } else {
347                // FIXME: 9 sounds like `"do catch ".len()`, so may predate the rename
348                // 9 = `try `
349                let budget = shape.width.saturating_sub(9);
350                Ok(format!(
351                    "{}{}",
352                    "try ",
353                    rewrite_block(
354                        block,
355                        Some(&expr.attrs),
356                        None,
357                        context,
358                        Shape::legacy(budget, shape.indent)
359                    )?
360                ))
361            }
362        }
363        ast::ExprKind::TryBlock(ref block, Some(ref ty)) => {
364            let keyword = "try bikeshed ";
365            // 2 = " {".len()
366            let ty_shape = shape
367                .shrink_left(keyword.len(), expr.span)
368                .and_then(|shape| shape.sub_width(2, expr.span))?;
369
370            let ty_str = ty.rewrite_result(context, ty_shape)?;
371            let prefix = format!("{keyword}{ty_str} ");
372            if let rw @ Ok(_) =
373                rewrite_single_line_block(context, &prefix, block, Some(&expr.attrs), None, shape)
374            {
375                rw
376            } else {
377                let budget = shape.width.saturating_sub(prefix.len());
378                Ok(format!(
379                    "{prefix}{}",
380                    rewrite_block(
381                        block,
382                        Some(&expr.attrs),
383                        None,
384                        context,
385                        Shape::legacy(budget, shape.indent)
386                    )?
387                ))
388            }
389        }
390        ast::ExprKind::Gen(capture_by, ref block, ref kind, _) => {
391            let mover = if matches!(capture_by, ast::CaptureBy::Value { .. }) {
392                "move "
393            } else {
394                ""
395            };
396            if let rw @ Ok(_) = rewrite_single_line_block(
397                context,
398                format!("{kind} {mover}").as_str(),
399                block,
400                Some(&expr.attrs),
401                None,
402                shape,
403            ) {
404                rw
405            } else {
406                // 6 = `async `
407                let budget = shape.width.saturating_sub(6);
408                Ok(format!(
409                    "{kind} {mover}{}",
410                    rewrite_block(
411                        block,
412                        Some(&expr.attrs),
413                        None,
414                        context,
415                        Shape::legacy(budget, shape.indent)
416                    )?
417                ))
418            }
419        }
420        ast::ExprKind::Underscore => Ok("_".to_owned()),
421        ast::ExprKind::FormatArgs(..)
422        | ast::ExprKind::Type(..)
423        | ast::ExprKind::IncludedBytes(..)
424        | ast::ExprKind::OffsetOf(..)
425        | ast::ExprKind::UnsafeBinderCast(..)
426        | ast::ExprKind::DirectConstArg(..) => {
427            // These don't normally occur in the AST because macros aren't expanded. However,
428            // rustfmt tries to parse macro arguments when formatting macros, so it's not totally
429            // impossible for rustfmt to come across one of these nodes when formatting a file.
430            // Also, rustfmt might get passed the output from `-Zunpretty=expanded`.
431            Err(RewriteError::Unknown)
432        }
433        ast::ExprKind::Err(_) | ast::ExprKind::Dummy => Err(RewriteError::Unknown),
434    };
435
436    expr_rw
437        .map(|expr_str| recover_comment_removed(expr_str, expr.span, context))
438        .and_then(|expr_str| {
439            let attrs = outer_attributes(&expr.attrs);
440            let attrs_str = attrs.rewrite_result(context, shape)?;
441            let span = mk_sp(
442                attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
443                expr.span.lo(),
444            );
445            combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
446        })
447}
448
449pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
450    name: &'a str,
451    exprs: impl Iterator<Item = &'a T>,
452    span: Span,
453    context: &'a RewriteContext<'_>,
454    shape: Shape,
455    force_separator_tactic: Option<SeparatorTactic>,
456    delim_token: Option<Delimiter>,
457) -> RewriteResult {
458    overflow::rewrite_with_square_brackets(
459        context,
460        name,
461        exprs,
462        shape,
463        span,
464        force_separator_tactic,
465        delim_token,
466    )
467}
468
469fn rewrite_empty_block(
470    context: &RewriteContext<'_>,
471    block: &ast::Block,
472    attrs: Option<&[ast::Attribute]>,
473    label: Option<ast::Label>,
474    prefix: &str,
475    shape: Shape,
476) -> Option<String> {
477    if block_has_statements(block) {
478        return None;
479    }
480
481    let label_str = rewrite_label(context, label);
482    if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
483        return None;
484    }
485
486    if !block_contains_comment(context, block) && shape.width >= 2 {
487        return Some(format!("{prefix}{label_str}{{}}"));
488    }
489
490    // If a block contains only a single-line comment, then leave it on one line.
491    let user_str = context.snippet(block.span);
492    let user_str = user_str.trim();
493    if user_str.starts_with('{') && user_str.ends_with('}') {
494        let comment_str = user_str[1..user_str.len() - 1].trim();
495        if block.stmts.is_empty()
496            && !comment_str.contains('\n')
497            && !comment_str.starts_with("//")
498            && comment_str.len() + 4 <= shape.width
499        {
500            return Some(format!("{prefix}{label_str}{{ {comment_str} }}"));
501        }
502    }
503
504    None
505}
506
507fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> RewriteResult {
508    Ok(match block.rules {
509        ast::BlockCheckMode::Unsafe(..) => {
510            let snippet = context.snippet(block.span);
511            let open_pos = snippet.find_uncommented("{").unknown_error()?;
512            // Extract comment between unsafe and block start.
513            let trimmed = &snippet[6..open_pos].trim();
514
515            if !trimmed.is_empty() {
516                // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
517                let budget = shape
518                    .width
519                    .checked_sub(9)
520                    .max_width_error(shape.width, block.span)?;
521                format!(
522                    "unsafe {} ",
523                    rewrite_comment(
524                        trimmed,
525                        true,
526                        Shape::legacy(budget, shape.indent + 7),
527                        context.config,
528                    )?
529                )
530            } else {
531                "unsafe ".to_owned()
532            }
533        }
534        ast::BlockCheckMode::Default => String::new(),
535    })
536}
537
538fn rewrite_single_line_block(
539    context: &RewriteContext<'_>,
540    prefix: &str,
541    block: &ast::Block,
542    attrs: Option<&[ast::Attribute]>,
543    label: Option<ast::Label>,
544    shape: Shape,
545) -> RewriteResult {
546    if let Some(block_expr) = stmt::Stmt::from_simple_block(context, block, attrs) {
547        let expr_shape = shape.offset_left(last_line_width(prefix), block_expr.span())?;
548        let expr_str = block_expr.rewrite_result(context, expr_shape)?;
549        let label_str = rewrite_label(context, label);
550        let result = format!("{prefix}{label_str}{{ {expr_str} }}");
551        if result.len() <= shape.width && !result.contains('\n') {
552            return Ok(result);
553        }
554    }
555    Err(RewriteError::Unknown)
556}
557
558pub(crate) fn rewrite_block_with_visitor(
559    context: &RewriteContext<'_>,
560    prefix: &str,
561    block: &ast::Block,
562    attrs: Option<&[ast::Attribute]>,
563    label: Option<ast::Label>,
564    shape: Shape,
565    has_braces: bool,
566) -> RewriteResult {
567    if let Some(rw_str) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
568        return Ok(rw_str);
569    }
570
571    let mut visitor = FmtVisitor::from_context(context);
572    visitor.block_indent = shape.indent;
573    visitor.is_if_else_block = context.is_if_else_block();
574    visitor.is_loop_block = context.is_loop_block();
575    match (block.rules, label) {
576        (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
577            let snippet = context.snippet(block.span);
578            let open_pos = snippet.find_uncommented("{").unknown_error()?;
579            visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
580        }
581        (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
582    }
583
584    let inner_attrs = attrs.map(inner_attributes);
585    let label_str = rewrite_label(context, label);
586    visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
587    let visitor_context = visitor.get_context();
588    context
589        .skipped_range
590        .borrow_mut()
591        .append(&mut visitor_context.skipped_range.borrow_mut());
592    Ok(format!("{}{}{}", prefix, label_str, visitor.buffer))
593}
594
595impl Rewrite for ast::Block {
596    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
597        self.rewrite_result(context, shape).ok()
598    }
599
600    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
601        rewrite_block(self, None, None, context, shape)
602    }
603}
604
605fn rewrite_block(
606    block: &ast::Block,
607    attrs: Option<&[ast::Attribute]>,
608    label: Option<ast::Label>,
609    context: &RewriteContext<'_>,
610    shape: Shape,
611) -> RewriteResult {
612    rewrite_block_inner(block, attrs, label, true, context, shape)
613}
614
615fn rewrite_block_inner(
616    block: &ast::Block,
617    attrs: Option<&[ast::Attribute]>,
618    label: Option<ast::Label>,
619    allow_single_line: bool,
620    context: &RewriteContext<'_>,
621    shape: Shape,
622) -> RewriteResult {
623    let prefix = block_prefix(context, block, shape)?;
624
625    // shape.width is used only for the single line case: either the empty block `{}`,
626    // or an unsafe expression `unsafe { e }`.
627    if let Some(rw_str) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
628        return Ok(rw_str);
629    }
630
631    let result_str =
632        rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true)?;
633    if allow_single_line && result_str.lines().count() <= 3 {
634        if let rw @ Ok(_) = rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
635        {
636            return rw;
637        }
638    }
639    Ok(result_str)
640}
641
642/// Rewrite the divergent block of a `let-else` statement.
643pub(crate) fn rewrite_let_else_block(
644    block: &ast::Block,
645    allow_single_line: bool,
646    context: &RewriteContext<'_>,
647    shape: Shape,
648) -> RewriteResult {
649    rewrite_block_inner(block, None, None, allow_single_line, context, shape)
650}
651
652// Rewrite condition if the given expression has one.
653pub(crate) fn rewrite_cond(
654    context: &RewriteContext<'_>,
655    expr: &ast::Expr,
656    shape: Shape,
657) -> Option<String> {
658    match expr.kind {
659        ast::ExprKind::Match(ref cond, _, MatchKind::Prefix) => {
660            // `match `cond` {`
661            let cond_shape = match context.config.indent_style() {
662                IndentStyle::Visual => shape.shrink_left_opt(6).and_then(|s| s.sub_width_opt(2))?,
663                IndentStyle::Block => shape.offset_left_opt(8)?,
664            };
665            cond.rewrite(context, cond_shape)
666        }
667        _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
668            let alt_block_sep =
669                String::from("\n") + &shape.indent.block_only().to_string(context.config);
670            control_flow
671                .rewrite_cond(context, shape, &alt_block_sep)
672                .ok()
673                .map(|rw| rw.0)
674        }),
675    }
676}
677
678// Abstraction over control flow expressions
679#[derive(Debug)]
680struct ControlFlow<'a> {
681    cond: Option<&'a ast::Expr>,
682    block: &'a ast::Block,
683    else_block: Option<&'a ast::Expr>,
684    label: Option<ast::Label>,
685    pat: Option<&'a ast::Pat>,
686    keyword: &'a str,
687    matcher: &'a str,
688    connector: &'a str,
689    allow_single_line: bool,
690    // HACK: `true` if this is an `if` expression in an `else if`.
691    nested_if: bool,
692    is_loop: bool,
693    span: Span,
694}
695
696fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
697    match expr.kind {
698        ast::ExprKind::Let(ref pat, ref cond, _, _) => (Some(pat), cond),
699        _ => (None, expr),
700    }
701}
702
703// FIXME: Refactor this.
704fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
705    match expr.kind {
706        ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
707            let (pat, cond) = extract_pats_and_cond(cond);
708            Some(ControlFlow::new_if(
709                cond,
710                pat,
711                if_block,
712                else_block.as_ref().map(|e| &**e),
713                expr_type == ExprType::SubExpression,
714                false,
715                expr.span,
716            ))
717        }
718        ast::ExprKind::ForLoop(ref f) => Some(ControlFlow::new_for(
719            &f.pat, &f.iter, &f.body, f.label, expr.span, f.kind,
720        )),
721        ast::ExprKind::Loop(ref block, label, _) => {
722            Some(ControlFlow::new_loop(block, label, expr.span))
723        }
724        ast::ExprKind::While(ref cond, ref block, label) => {
725            let (pat, cond) = extract_pats_and_cond(cond);
726            Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
727        }
728        _ => None,
729    }
730}
731
732fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
733    pat.map_or("", |_| "let")
734}
735
736impl<'a> ControlFlow<'a> {
737    fn new_if(
738        cond: &'a ast::Expr,
739        pat: Option<&'a ast::Pat>,
740        block: &'a ast::Block,
741        else_block: Option<&'a ast::Expr>,
742        allow_single_line: bool,
743        nested_if: bool,
744        span: Span,
745    ) -> ControlFlow<'a> {
746        let matcher = choose_matcher(pat);
747        ControlFlow {
748            cond: Some(cond),
749            block,
750            else_block,
751            label: None,
752            pat,
753            keyword: "if",
754            matcher,
755            connector: " =",
756            allow_single_line,
757            nested_if,
758            is_loop: false,
759            span,
760        }
761    }
762
763    fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
764        ControlFlow {
765            cond: None,
766            block,
767            else_block: None,
768            label,
769            pat: None,
770            keyword: "loop",
771            matcher: "",
772            connector: "",
773            allow_single_line: false,
774            nested_if: false,
775            is_loop: true,
776            span,
777        }
778    }
779
780    fn new_while(
781        pat: Option<&'a ast::Pat>,
782        cond: &'a ast::Expr,
783        block: &'a ast::Block,
784        label: Option<ast::Label>,
785        span: Span,
786    ) -> ControlFlow<'a> {
787        let matcher = choose_matcher(pat);
788        ControlFlow {
789            cond: Some(cond),
790            block,
791            else_block: None,
792            label,
793            pat,
794            keyword: "while",
795            matcher,
796            connector: " =",
797            allow_single_line: false,
798            nested_if: false,
799            is_loop: true,
800            span,
801        }
802    }
803
804    fn new_for(
805        pat: &'a ast::Pat,
806        cond: &'a ast::Expr,
807        block: &'a ast::Block,
808        label: Option<ast::Label>,
809        span: Span,
810        kind: ForLoopKind,
811    ) -> ControlFlow<'a> {
812        ControlFlow {
813            cond: Some(cond),
814            block,
815            else_block: None,
816            label,
817            pat: Some(pat),
818            keyword: match kind {
819                ForLoopKind::For => "for",
820                ForLoopKind::ForAwait => "for await",
821            },
822            matcher: "",
823            connector: " in",
824            allow_single_line: false,
825            nested_if: false,
826            is_loop: true,
827            span,
828        }
829    }
830
831    fn rewrite_single_line(
832        &self,
833        pat_expr_str: &str,
834        context: &RewriteContext<'_>,
835        width: usize,
836    ) -> Option<String> {
837        assert!(self.allow_single_line);
838        let else_block = self.else_block?;
839        let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
840
841        if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
842            let (if_expr, else_expr) = match (
843                stmt::Stmt::from_simple_block(context, self.block, None),
844                stmt::Stmt::from_simple_block(context, else_node, None),
845                pat_expr_str.contains('\n'),
846            ) {
847                (Some(if_expr), Some(else_expr), false) => (if_expr, else_expr),
848                _ => return None,
849            };
850
851            let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
852            let if_str = if_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
853
854            let new_width = new_width.checked_sub(if_str.len())?;
855            let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
856
857            if if_str.contains('\n') || else_str.contains('\n') {
858                return None;
859            }
860
861            let result = format!(
862                "{} {} {{ {} }} else {{ {} }}",
863                self.keyword, pat_expr_str, if_str, else_str
864            );
865
866            if result.len() <= width {
867                return Some(result);
868            }
869        }
870
871        None
872    }
873}
874
875/// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
876/// shape's indent.
877fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
878    let mut leading_whitespaces = 0;
879    for c in pat_str.chars().rev() {
880        match c {
881            '\n' => break,
882            _ if c.is_whitespace() => leading_whitespaces += 1,
883            _ => leading_whitespaces = 0,
884        }
885    }
886    leading_whitespaces > start_column
887}
888
889impl<'a> ControlFlow<'a> {
890    fn rewrite_pat_expr(
891        &self,
892        context: &RewriteContext<'_>,
893        expr: &ast::Expr,
894        shape: Shape,
895        offset: usize,
896    ) -> RewriteResult {
897        debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
898
899        let cond_shape = shape.offset_left(offset, expr.span)?;
900        if let Some(pat) = self.pat {
901            let matcher = if self.matcher.is_empty() {
902                self.matcher.to_owned()
903            } else {
904                format!("{} ", self.matcher)
905            };
906            let pat_shape = cond_shape
907                .offset_left(matcher.len(), pat.span)?
908                .sub_width(self.connector.len(), pat.span)?;
909            let pat_string = pat.rewrite_result(context, pat_shape)?;
910            let comments_lo = context
911                .snippet_provider
912                .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
913            let comments_span = mk_sp(comments_lo, expr.span.lo());
914            return rewrite_assign_rhs_with_comments(
915                context,
916                &format!("{}{}{}", matcher, pat_string, self.connector),
917                expr,
918                cond_shape,
919                &RhsAssignKind::Expr(&expr.kind, expr.span),
920                RhsTactics::Default,
921                comments_span,
922                true,
923            );
924        }
925
926        let expr_rw = expr.rewrite_result(context, cond_shape);
927        // The expression may (partially) fit on the current line.
928        // We do not allow splitting between `if` and condition.
929        if self.keyword == "if" || expr_rw.is_ok() {
930            return expr_rw;
931        }
932
933        // The expression won't fit on the current line, jump to next.
934        let nested_shape = shape
935            .block_indent(context.config.tab_spaces())
936            .with_max_width(context.config);
937        let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
938        expr.rewrite_result(context, nested_shape)
939            .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
940    }
941
942    fn rewrite_cond(
943        &self,
944        context: &RewriteContext<'_>,
945        shape: Shape,
946        alt_block_sep: &str,
947    ) -> Result<(String, usize), RewriteError> {
948        // Do not take the rhs overhead from the upper expressions into account
949        // when rewriting pattern.
950        let new_width = context.budget(shape.used_width());
951        let fresh_shape = Shape {
952            width: new_width,
953            ..shape
954        };
955        let constr_shape = if self.nested_if {
956            // We are part of an if-elseif-else chain. Our constraints are tightened.
957            // 7 = "} else " .len()
958            fresh_shape.offset_left(7, self.span)?
959        } else {
960            fresh_shape
961        };
962
963        let label_string = rewrite_label(context, self.label);
964        // 1 = space after keyword.
965        let offset = self.keyword.len() + label_string.len() + 1;
966
967        let pat_expr_string = match self.cond {
968            Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
969            None => String::new(),
970        };
971
972        let brace_overhead =
973            if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
974                // 2 = ` {`
975                2
976            } else {
977                0
978            };
979        let one_line_budget = context
980            .config
981            .max_width()
982            .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
983        let force_newline_brace = (pat_expr_string.contains('\n')
984            || pat_expr_string.len() > one_line_budget)
985            && (!last_line_extendable(&pat_expr_string)
986                || last_line_offsetted(shape.used_width(), &pat_expr_string));
987
988        // Try to format if-else on single line.
989        if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
990            let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
991
992            if let Some(cond_str) = trial {
993                if cond_str.len() <= context.config.single_line_if_else_max_width() {
994                    return Ok((cond_str, 0));
995                }
996            }
997        }
998
999        let cond_span = if let Some(cond) = self.cond {
1000            cond.span
1001        } else {
1002            mk_sp(self.block.span.lo(), self.block.span.lo())
1003        };
1004
1005        // `for event in event`
1006        // Do not include label in the span.
1007        let lo = self
1008            .label
1009            .map_or(self.span.lo(), |label| label.ident.span.hi());
1010        let between_kwd_cond = mk_sp(
1011            context
1012                .snippet_provider
1013                .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1014            if self.pat.is_none() {
1015                cond_span.lo()
1016            } else if self.matcher.is_empty() {
1017                self.pat.unwrap().span.lo()
1018            } else {
1019                context
1020                    .snippet_provider
1021                    .span_before(self.span, self.matcher.trim())
1022            },
1023        );
1024
1025        let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1026
1027        let after_cond_comment =
1028            extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1029
1030        let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1031            ""
1032        } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1033            || force_newline_brace
1034        {
1035            alt_block_sep
1036        } else {
1037            " "
1038        };
1039
1040        let used_width = if pat_expr_string.contains('\n') {
1041            last_line_width(&pat_expr_string)
1042        } else {
1043            // 2 = spaces after keyword and condition.
1044            label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1045        };
1046
1047        Ok((
1048            format!(
1049                "{}{}{}{}{}",
1050                label_string,
1051                self.keyword,
1052                between_kwd_cond_comment.as_ref().map_or(
1053                    if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1054                        ""
1055                    } else {
1056                        " "
1057                    },
1058                    |s| &**s,
1059                ),
1060                pat_expr_string,
1061                after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1062            ),
1063            used_width,
1064        ))
1065    }
1066}
1067
1068/// Rewrite the `else` keyword with surrounding comments.
1069///
1070/// force_newline_else: whether or not to rewrite the `else` keyword on a newline.
1071/// is_last: true if this is an `else` and `false` if this is an `else if` block.
1072/// context: rewrite context
1073/// span: Span between the end of the last expression and the start of the else block,
1074///       which contains the `else` keyword
1075/// shape: Shape
1076pub(crate) fn rewrite_else_kw_with_comments(
1077    force_newline_else: bool,
1078    is_last: bool,
1079    context: &RewriteContext<'_>,
1080    span: Span,
1081    shape: Shape,
1082) -> String {
1083    let else_kw_lo = context.snippet_provider.span_before(span, "else");
1084    let before_else_kw = mk_sp(span.lo(), else_kw_lo);
1085    let before_else_kw_comment = extract_comment(before_else_kw, context, shape);
1086
1087    let else_kw_hi = context.snippet_provider.span_after(span, "else");
1088    let after_else_kw = mk_sp(else_kw_hi, span.hi());
1089    let after_else_kw_comment = extract_comment(after_else_kw, context, shape);
1090
1091    let newline_sep = &shape.indent.to_string_with_newline(context.config);
1092    let before_sep = match context.config.control_brace_style() {
1093        _ if force_newline_else => newline_sep.as_ref(),
1094        ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1095            newline_sep.as_ref()
1096        }
1097        ControlBraceStyle::AlwaysSameLine => " ",
1098    };
1099    let after_sep = match context.config.control_brace_style() {
1100        ControlBraceStyle::AlwaysNextLine if is_last => newline_sep.as_ref(),
1101        _ => " ",
1102    };
1103
1104    format!(
1105        "{}else{}",
1106        before_else_kw_comment.as_ref().map_or(before_sep, |s| &**s),
1107        after_else_kw_comment.as_ref().map_or(after_sep, |s| &**s),
1108    )
1109}
1110
1111impl<'a> Rewrite for ControlFlow<'a> {
1112    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1113        self.rewrite_result(context, shape).ok()
1114    }
1115
1116    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1117        debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1118
1119        let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1120        let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1121        // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1122        if used_width == 0 {
1123            return Ok(cond_str);
1124        }
1125
1126        let block_width = shape.width.saturating_sub(used_width);
1127        // This is used only for the empty block case: `{}`. So, we use 1 if we know
1128        // we should avoid the single line case.
1129        let block_width = if self.else_block.is_some() || self.nested_if {
1130            min(1, block_width)
1131        } else {
1132            block_width
1133        };
1134        let block_shape = Shape {
1135            width: block_width,
1136            ..shape
1137        };
1138        let block_str = {
1139            let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1140            let old_is_loop = context.is_loop_block.replace(self.is_loop);
1141            let result =
1142                rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1143            context.is_loop_block.replace(old_is_loop);
1144            context.is_if_else_block.replace(old_val);
1145            result?
1146        };
1147
1148        let mut result = format!("{cond_str}{block_str}");
1149
1150        if let Some(else_block) = self.else_block {
1151            let shape = Shape::indented(shape.indent, context.config);
1152            let mut last_in_chain = false;
1153            let rewrite = match else_block.kind {
1154                // If the else expression is another if-else expression, prevent it
1155                // from being formatted on a single line.
1156                // Note how we're passing the original shape, as the
1157                // cost of "else" should not cascade.
1158                ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1159                    let (pats, cond) = extract_pats_and_cond(cond);
1160                    ControlFlow::new_if(
1161                        cond,
1162                        pats,
1163                        if_block,
1164                        next_else_block.as_ref().map(|e| &**e),
1165                        false,
1166                        true,
1167                        mk_sp(else_block.span.lo(), self.span.hi()),
1168                    )
1169                    .rewrite_result(context, shape)
1170                }
1171                _ => {
1172                    last_in_chain = true;
1173                    // When rewriting a block, the width is only used for single line
1174                    // blocks, passing 1 lets us avoid that.
1175                    let else_shape = Shape {
1176                        width: min(1, shape.width),
1177                        ..shape
1178                    };
1179                    format_expr(else_block, ExprType::Statement, context, else_shape)
1180                }
1181            };
1182
1183            let else_kw = rewrite_else_kw_with_comments(
1184                false,
1185                last_in_chain,
1186                context,
1187                self.block.span.between(else_block.span),
1188                shape,
1189            );
1190            result.push_str(&else_kw);
1191            result.push_str(&rewrite?);
1192        }
1193
1194        Ok(result)
1195    }
1196}
1197
1198fn rewrite_label(context: &RewriteContext<'_>, opt_label: Option<ast::Label>) -> Cow<'static, str> {
1199    match opt_label {
1200        Some(label) => Cow::from(format!("{}: ", context.snippet(label.ident.span))),
1201        None => Cow::from(""),
1202    }
1203}
1204
1205fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1206    match rewrite_missing_comment(span, shape, context) {
1207        Ok(ref comment) if !comment.is_empty() => Some(format!(
1208            "{indent}{comment}{indent}",
1209            indent = shape.indent.to_string_with_newline(context.config)
1210        )),
1211        _ => None,
1212    }
1213}
1214
1215pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1216    contains_comment(context.snippet(block.span))
1217}
1218
1219// Checks that a block contains no statements, an expression and no comments or
1220// attributes.
1221// FIXME: incorrectly returns false when comment is contained completely within
1222// the expression.
1223pub(crate) fn is_simple_block(
1224    context: &RewriteContext<'_>,
1225    block: &ast::Block,
1226    attrs: Option<&[ast::Attribute]>,
1227) -> bool {
1228    block.stmts.len() == 1
1229        && stmt_is_expr(&block.stmts[0])
1230        && !block_contains_comment(context, block)
1231        && attrs.map_or(true, |a| a.is_empty())
1232}
1233
1234/// Checks whether a block contains at most one statement or expression, and no
1235/// comments or attributes.
1236pub(crate) fn is_simple_block_stmt(
1237    context: &RewriteContext<'_>,
1238    block: &ast::Block,
1239    attrs: Option<&[ast::Attribute]>,
1240) -> bool {
1241    block.stmts.len() <= 1
1242        && !block_contains_comment(context, block)
1243        && attrs.map_or(true, |a| a.is_empty())
1244}
1245
1246fn block_has_statements(block: &ast::Block) -> bool {
1247    block
1248        .stmts
1249        .iter()
1250        .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1251}
1252
1253/// Checks whether a block contains no statements, expressions, comments, or
1254/// inner attributes.
1255pub(crate) fn is_empty_block(
1256    context: &RewriteContext<'_>,
1257    block: &ast::Block,
1258    attrs: Option<&[ast::Attribute]>,
1259) -> bool {
1260    !block_has_statements(block)
1261        && !block_contains_comment(context, block)
1262        && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1263}
1264
1265pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1266    matches!(stmt.kind, ast::StmtKind::Expr(..))
1267}
1268
1269pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1270    matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1271}
1272
1273pub(crate) fn rewrite_literal(
1274    context: &RewriteContext<'_>,
1275    token_lit: token::Lit,
1276    span: Span,
1277    shape: Shape,
1278) -> RewriteResult {
1279    match token_lit.kind {
1280        token::LitKind::Str => rewrite_string_lit(context, span, shape),
1281        token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape),
1282        token::LitKind::Float => rewrite_float_lit(context, token_lit, span, shape),
1283        _ => wrap_str(
1284            context.snippet(span).to_owned(),
1285            context.config.max_width(),
1286            shape,
1287        )
1288        .max_width_error(shape.width, span),
1289    }
1290}
1291
1292fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> RewriteResult {
1293    let string_lit = context.snippet(span);
1294
1295    if !context.config.format_strings() {
1296        if string_lit
1297            .lines()
1298            .dropping_back(1)
1299            .all(|line| line.ends_with('\\'))
1300            && context.config.style_edition() >= StyleEdition::Edition2024
1301        {
1302            return Ok(string_lit.to_owned());
1303        } else {
1304            return wrap_str(string_lit.to_owned(), context.config.max_width(), shape)
1305                .max_width_error(shape.width, span);
1306        }
1307    }
1308
1309    // Remove the quote characters.
1310    let str_lit = &string_lit[1..string_lit.len() - 1];
1311
1312    rewrite_string(
1313        str_lit,
1314        &StringFormat::new(shape.visual_indent(0), context.config),
1315        shape.width.saturating_sub(2),
1316    )
1317    .max_width_error(shape.width, span)
1318}
1319
1320fn rewrite_int_lit(
1321    context: &RewriteContext<'_>,
1322    token_lit: token::Lit,
1323    span: Span,
1324    shape: Shape,
1325) -> RewriteResult {
1326    if token_lit.is_semantic_float() {
1327        return rewrite_float_lit(context, token_lit, span, shape);
1328    }
1329
1330    let symbol = token_lit.symbol.as_str();
1331
1332    if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1333        let hex_lit = match context.config.hex_literal_case() {
1334            HexLiteralCase::Preserve => None,
1335            HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1336            HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1337        };
1338        if let Some(hex_lit) = hex_lit {
1339            return wrap_str(
1340                format!(
1341                    "0x{}{}",
1342                    hex_lit,
1343                    token_lit.suffix.as_ref().map_or("", |s| s.as_str())
1344                ),
1345                context.config.max_width(),
1346                shape,
1347            )
1348            .max_width_error(shape.width, span);
1349        }
1350    }
1351
1352    wrap_str(
1353        context.snippet(span).to_owned(),
1354        context.config.max_width(),
1355        shape,
1356    )
1357    .max_width_error(shape.width, span)
1358}
1359
1360fn rewrite_float_lit(
1361    context: &RewriteContext<'_>,
1362    token_lit: token::Lit,
1363    span: Span,
1364    shape: Shape,
1365) -> RewriteResult {
1366    if matches!(
1367        context.config.float_literal_trailing_zero(),
1368        FloatLiteralTrailingZero::Preserve
1369    ) {
1370        return wrap_str(
1371            context.snippet(span).to_owned(),
1372            context.config.max_width(),
1373            shape,
1374        )
1375        .max_width_error(shape.width, span);
1376    }
1377
1378    let symbol = token_lit.symbol.as_str();
1379    let suffix = token_lit.suffix.as_ref().map(|s| s.as_str());
1380
1381    let float_parts = parse_float_symbol(symbol).unwrap();
1382    let FloatSymbolParts {
1383        integer_part,
1384        fractional_part,
1385        exponent,
1386    } = float_parts;
1387
1388    let has_postfix = exponent.is_some() || suffix.is_some();
1389    let fractional_part_nonzero = !float_parts.is_fractional_part_zero();
1390
1391    let (include_period, include_fractional_part) =
1392        match context.config.float_literal_trailing_zero() {
1393            FloatLiteralTrailingZero::Preserve => unreachable!("handled above"),
1394            FloatLiteralTrailingZero::Always => (true, true),
1395            FloatLiteralTrailingZero::IfNoPostfix => (
1396                fractional_part_nonzero || !has_postfix,
1397                fractional_part_nonzero || !has_postfix,
1398            ),
1399            FloatLiteralTrailingZero::Never => (
1400                fractional_part_nonzero || !has_postfix,
1401                fractional_part_nonzero,
1402            ),
1403        };
1404
1405    let period = if include_period { "." } else { "" };
1406    let fractional_part = if include_fractional_part {
1407        fractional_part.unwrap_or("0")
1408    } else {
1409        ""
1410    };
1411    wrap_str(
1412        format!(
1413            "{}{}{}{}{}",
1414            integer_part,
1415            period,
1416            fractional_part,
1417            exponent.unwrap_or(""),
1418            suffix.unwrap_or(""),
1419        ),
1420        context.config.max_width(),
1421        shape,
1422    )
1423    .max_width_error(shape.width, span)
1424}
1425
1426fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1427    if context.inside_macro() {
1428        if span_ends_with_comma(context, span) {
1429            Some(SeparatorTactic::Always)
1430        } else {
1431            Some(SeparatorTactic::Never)
1432        }
1433    } else {
1434        None
1435    }
1436}
1437
1438pub(crate) fn rewrite_call(
1439    context: &RewriteContext<'_>,
1440    callee: &str,
1441    args: &[Box<ast::Expr>],
1442    span: Span,
1443    shape: Shape,
1444) -> RewriteResult {
1445    overflow::rewrite_with_parens(
1446        context,
1447        callee,
1448        args.iter(),
1449        shape,
1450        span,
1451        context.config.fn_call_width(),
1452        choose_separator_tactic(context, span),
1453    )
1454}
1455
1456pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1457    match expr.kind {
1458        ast::ExprKind::Lit(..) => true,
1459        ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1460        ast::ExprKind::AddrOf(_, _, ref expr)
1461        | ast::ExprKind::Cast(ref expr, _)
1462        | ast::ExprKind::Field(ref expr, _)
1463        | ast::ExprKind::Try(ref expr)
1464        | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1465        ast::ExprKind::Index(ref lhs, ref rhs, _) => is_simple_expr(lhs) && is_simple_expr(rhs),
1466        ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1467            is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1468        }
1469        _ => false,
1470    }
1471}
1472
1473pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1474    lists.iter().all(OverflowableItem::is_simple)
1475}
1476
1477pub(crate) fn can_be_overflowed_expr(
1478    context: &RewriteContext<'_>,
1479    expr: &ast::Expr,
1480    args_len: usize,
1481) -> bool {
1482    match expr.kind {
1483        _ if !expr.attrs.is_empty() => false,
1484        ast::ExprKind::Match(..) => {
1485            (context.use_block_indent() && args_len == 1)
1486                || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1487                || context.config.overflow_delimited_expr()
1488        }
1489        ast::ExprKind::If(..)
1490        | ast::ExprKind::ForLoop { .. }
1491        | ast::ExprKind::Loop(..)
1492        | ast::ExprKind::While(..) => {
1493            context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1494        }
1495
1496        // Handle always block-like expressions
1497        ast::ExprKind::Gen(..)
1498        | ast::ExprKind::Block(..)
1499        | ast::ExprKind::Closure(..)
1500        | ast::ExprKind::TryBlock(..) => true,
1501
1502        // Handle `[]` and `{}`-like expressions
1503        ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1504            context.config.overflow_delimited_expr()
1505                || (context.use_block_indent() && args_len == 1)
1506        }
1507        ast::ExprKind::MacCall(ref mac) => {
1508            match (mac.args.delim, context.config.overflow_delimited_expr()) {
1509                (Delimiter::Bracket, true) | (Delimiter::Brace, true) => true,
1510                _ => context.use_block_indent() && args_len == 1,
1511            }
1512        }
1513
1514        // Handle parenthetical expressions
1515        ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1516            context.use_block_indent() && args_len == 1
1517        }
1518
1519        // Handle unary-like expressions
1520        ast::ExprKind::AddrOf(_, _, ref expr)
1521        | ast::ExprKind::Try(ref expr)
1522        | ast::ExprKind::Unary(_, ref expr)
1523        | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1524        _ => false,
1525    }
1526}
1527
1528pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1529    match expr.kind {
1530        ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1531        ast::ExprKind::AddrOf(_, _, ref expr)
1532        | ast::ExprKind::Try(ref expr)
1533        | ast::ExprKind::Unary(_, ref expr)
1534        | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1535        _ => false,
1536    }
1537}
1538
1539/// Returns `true` if a function call or a method call represented by the given span ends with a
1540/// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1541/// comma from macro can potentially break the code.
1542pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1543    let mut result: bool = Default::default();
1544    let mut prev_char: char = Default::default();
1545    let closing_delimiters = &[')', '}', ']'];
1546
1547    for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1548        match c {
1549            _ if kind.is_comment() || c.is_whitespace() => continue,
1550            c if closing_delimiters.contains(&c) => {
1551                result &= !closing_delimiters.contains(&prev_char);
1552            }
1553            ',' => result = true,
1554            _ => result = false,
1555        }
1556        prev_char = c;
1557    }
1558
1559    result
1560}
1561
1562pub(crate) fn rewrite_paren(
1563    context: &RewriteContext<'_>,
1564    mut subexpr: &ast::Expr,
1565    shape: Shape,
1566    mut span: Span,
1567) -> RewriteResult {
1568    debug!("rewrite_paren, shape: {:?}", shape);
1569
1570    // Extract comments within parens.
1571    let mut pre_span;
1572    let mut post_span;
1573    let mut pre_comment;
1574    let mut post_comment;
1575    let remove_nested_parens = context.config.remove_nested_parens();
1576    loop {
1577        // 1 = "(" or ")"
1578        pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span().lo());
1579        post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1580        pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1581        post_comment = rewrite_missing_comment(post_span, shape, context)?;
1582
1583        // Remove nested parens if there are no comments.
1584        if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1585            if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1586                span = subexpr.span;
1587                subexpr = subsubexpr;
1588                continue;
1589            }
1590        }
1591
1592        break;
1593    }
1594
1595    // 1 = `(` and `)`
1596    let sub_shape = shape.offset_left(1, span)?.sub_width(1, span)?;
1597    let subexpr_str = subexpr.rewrite_result(context, sub_shape)?;
1598    let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1599    if fits_single_line {
1600        Ok(format!("({pre_comment}{subexpr_str}{post_comment})"))
1601    } else {
1602        rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1603    }
1604}
1605
1606fn rewrite_paren_in_multi_line(
1607    context: &RewriteContext<'_>,
1608    subexpr: &ast::Expr,
1609    shape: Shape,
1610    pre_span: Span,
1611    post_span: Span,
1612) -> RewriteResult {
1613    let nested_indent = shape.indent.block_indent(context.config);
1614    let nested_shape = Shape::indented(nested_indent, context.config);
1615    let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1616    let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1617    let subexpr_str = subexpr.rewrite_result(context, nested_shape)?;
1618
1619    let mut result = String::with_capacity(subexpr_str.len() * 2);
1620    result.push('(');
1621    if !pre_comment.is_empty() {
1622        result.push_str(&nested_indent.to_string_with_newline(context.config));
1623        result.push_str(&pre_comment);
1624    }
1625    result.push_str(&nested_indent.to_string_with_newline(context.config));
1626    result.push_str(&subexpr_str);
1627    if !post_comment.is_empty() {
1628        result.push_str(&nested_indent.to_string_with_newline(context.config));
1629        result.push_str(&post_comment);
1630    }
1631    result.push_str(&shape.indent.to_string_with_newline(context.config));
1632    result.push(')');
1633
1634    Ok(result)
1635}
1636
1637fn rewrite_index(
1638    expr: &ast::Expr,
1639    index: &ast::Expr,
1640    context: &RewriteContext<'_>,
1641    shape: Shape,
1642) -> RewriteResult {
1643    let expr_str = expr.rewrite_result(context, shape)?;
1644
1645    let offset = last_line_width(&expr_str) + 1;
1646    let rhs_overhead = shape.rhs_overhead(context.config);
1647    let index_shape = if expr_str.contains('\n') {
1648        Shape::legacy(context.config.max_width(), shape.indent)
1649            .offset_left(offset, index.span())
1650            .and_then(|shape| shape.sub_width(1 + rhs_overhead, index.span()))
1651    } else {
1652        match context.config.indent_style() {
1653            IndentStyle::Block => shape
1654                .offset_left(offset, index.span())
1655                .and_then(|shape| shape.sub_width(1, index.span())),
1656            IndentStyle::Visual => shape
1657                .visual_indent(offset)
1658                .sub_width(offset + 1, index.span()),
1659        }
1660    };
1661    let orig_index_rw = index_shape
1662        .map_err(RewriteError::from)
1663        .and_then(|s| index.rewrite_result(context, s));
1664
1665    // Return if index fits in a single line.
1666    match orig_index_rw {
1667        Ok(ref index_str) if !index_str.contains('\n') => {
1668            return Ok(format!("{expr_str}[{index_str}]"));
1669        }
1670        _ => (),
1671    }
1672
1673    // Try putting index on the next line and see if it fits in a single line.
1674    let indent = shape.indent.block_indent(context.config);
1675    let index_shape = Shape::indented(indent, context.config)
1676        .offset_left(1, index.span())?
1677        .sub_width(1 + rhs_overhead, index.span())?;
1678    let new_index_rw = index.rewrite_result(context, index_shape);
1679    match (orig_index_rw, new_index_rw) {
1680        (_, Ok(ref new_index_str)) if !new_index_str.contains('\n') => Ok(format!(
1681            "{}{}[{}]",
1682            expr_str,
1683            indent.to_string_with_newline(context.config),
1684            new_index_str,
1685        )),
1686        (Err(_), Ok(ref new_index_str)) => Ok(format!(
1687            "{}{}[{}]",
1688            expr_str,
1689            indent.to_string_with_newline(context.config),
1690            new_index_str,
1691        )),
1692        (Ok(ref index_str), _) => Ok(format!("{expr_str}[{index_str}]")),
1693        // When both orig_index_rw and new_index_rw result in errors, we currently propagate the
1694        // error from the second attempt since it is more generous with width constraints.
1695        // This decision is somewhat arbitrary and is open to change.
1696        (Err(_), Err(new_index_rw_err)) => Err(new_index_rw_err),
1697    }
1698}
1699
1700fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1701    !has_base && fields.iter().all(|field| !field.is_shorthand)
1702}
1703
1704fn rewrite_struct_lit<'a>(
1705    context: &RewriteContext<'_>,
1706    path: &ast::Path,
1707    qself: &Option<Box<ast::QSelf>>,
1708    fields: &'a [ast::ExprField],
1709    struct_rest: &ast::StructRest,
1710    attrs: &[ast::Attribute],
1711    span: Span,
1712    shape: Shape,
1713) -> RewriteResult {
1714    debug!("rewrite_struct_lit: shape {:?}", shape);
1715
1716    enum StructLitField<'a> {
1717        Regular(&'a ast::ExprField),
1718        Base(&'a ast::Expr),
1719        Rest(Span),
1720    }
1721
1722    // 2 = " {".len()
1723    let path_shape = shape.sub_width(2, span)?;
1724    let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1725
1726    let has_base_or_rest = match struct_rest {
1727        ast::StructRest::None if fields.is_empty() => return Ok(format!("{path_str} {{}}")),
1728        ast::StructRest::Rest(_) if fields.is_empty() => {
1729            return Ok(format!("{path_str} {{ .. }}"));
1730        }
1731        ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1732        _ => false,
1733    };
1734
1735    // Foo { a: Foo } - indent is +3, width is -5.
1736    let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2, span)?;
1737
1738    let one_line_width = h_shape.map_or(0, |shape| shape.width);
1739    let body_lo = context.snippet_provider.span_after(span, "{");
1740    let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1741        && context.config.struct_field_align_threshold() > 0
1742    {
1743        rewrite_with_alignment(
1744            fields,
1745            context,
1746            v_shape,
1747            mk_sp(body_lo, span.hi()),
1748            one_line_width,
1749        )
1750        .unknown_error()?
1751    } else {
1752        let field_iter = fields.iter().map(StructLitField::Regular).chain(
1753            match struct_rest {
1754                ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1755                ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1756                ast::StructRest::None | ast::StructRest::NoneWithError(_) => None,
1757            }
1758            .into_iter(),
1759        );
1760
1761        let span_lo = |item: &StructLitField<'_>| match *item {
1762            StructLitField::Regular(field) => field.span().lo(),
1763            StructLitField::Base(expr) => {
1764                let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1765                let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1766                let pos = snippet.find_uncommented("..").unwrap();
1767                last_field_hi + BytePos(pos as u32)
1768            }
1769            StructLitField::Rest(span) => span.lo(),
1770        };
1771        let span_hi = |item: &StructLitField<'_>| match *item {
1772            StructLitField::Regular(field) => field.span().hi(),
1773            StructLitField::Base(expr) => expr.span.hi(),
1774            StructLitField::Rest(span) => span.hi(),
1775        };
1776        let rewrite = |item: &StructLitField<'_>| match *item {
1777            StructLitField::Regular(field) => {
1778                // The 1 taken from the v_budget is for the comma.
1779                rewrite_field(context, field, v_shape.sub_width(1, span)?, 0)
1780            }
1781            StructLitField::Base(expr) => {
1782                // 2 = ..
1783                expr.rewrite_result(context, v_shape.offset_left(2, span)?)
1784                    .map(|s| format!("..{}", s))
1785            }
1786            StructLitField::Rest(_) => Ok("..".to_owned()),
1787        };
1788
1789        let items = itemize_list(
1790            context.snippet_provider,
1791            field_iter,
1792            "}",
1793            ",",
1794            span_lo,
1795            span_hi,
1796            rewrite,
1797            body_lo,
1798            span.hi(),
1799            false,
1800        );
1801        let item_vec = items.collect::<Vec<_>>();
1802
1803        let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1804        let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1805
1806        let ends_with_comma = span_ends_with_comma(context, span);
1807        let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1808
1809        let fmt = struct_lit_formatting(
1810            nested_shape,
1811            tactic,
1812            context,
1813            force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1814        );
1815
1816        write_list(&item_vec, &fmt)?
1817    };
1818
1819    let fields_str =
1820        wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1821    Ok(format!("{path_str} {{{fields_str}}}"))
1822
1823    // FIXME if context.config.indent_style() == Visual, but we run out
1824    // of space, we should fall back to BlockIndent.
1825}
1826
1827pub(crate) fn wrap_struct_field(
1828    context: &RewriteContext<'_>,
1829    attrs: &[ast::Attribute],
1830    fields_str: &str,
1831    shape: Shape,
1832    nested_shape: Shape,
1833    one_line_width: usize,
1834) -> RewriteResult {
1835    let should_vertical = context.config.indent_style() == IndentStyle::Block
1836        && (fields_str.contains('\n')
1837            || !context.config.struct_lit_single_line()
1838            || fields_str.len() > one_line_width);
1839
1840    let inner_attrs = &inner_attributes(attrs);
1841    if inner_attrs.is_empty() {
1842        if should_vertical {
1843            Ok(format!(
1844                "{}{}{}",
1845                nested_shape.indent.to_string_with_newline(context.config),
1846                fields_str,
1847                shape.indent.to_string_with_newline(context.config)
1848            ))
1849        } else {
1850            // One liner or visual indent.
1851            Ok(format!(" {fields_str} "))
1852        }
1853    } else {
1854        Ok(format!(
1855            "{}{}{}{}{}",
1856            nested_shape.indent.to_string_with_newline(context.config),
1857            inner_attrs.rewrite_result(context, shape)?,
1858            nested_shape.indent.to_string_with_newline(context.config),
1859            fields_str,
1860            shape.indent.to_string_with_newline(context.config)
1861        ))
1862    }
1863}
1864
1865pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1866    colon_spaces(config)
1867}
1868
1869pub(crate) fn rewrite_field(
1870    context: &RewriteContext<'_>,
1871    field: &ast::ExprField,
1872    shape: Shape,
1873    prefix_max_width: usize,
1874) -> RewriteResult {
1875    if contains_skip(&field.attrs) {
1876        return Ok(context.snippet(field.span()).to_owned());
1877    }
1878    let mut attrs_str = field.attrs.rewrite_result(context, shape)?;
1879    if !attrs_str.is_empty() {
1880        attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1881    };
1882    let name = context.snippet(field.ident.span);
1883    if field.is_shorthand {
1884        Ok(attrs_str + name)
1885    } else {
1886        let mut separator = String::from(struct_lit_field_separator(context.config));
1887        for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1888            separator.push(' ');
1889        }
1890        let overhead = name.len() + separator.len();
1891        let expr_shape = shape.offset_left(overhead, field.span)?;
1892        let expr = field.expr.rewrite_result(context, expr_shape);
1893        let is_lit = matches!(field.expr.kind, ast::ExprKind::Lit(_));
1894        match expr {
1895            Ok(ref e)
1896                if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() =>
1897            {
1898                Ok(attrs_str + name)
1899            }
1900            Ok(e) => Ok(format!("{attrs_str}{name}{separator}{e}")),
1901            Err(_) => {
1902                let expr_offset = shape.indent.block_indent(context.config);
1903                let expr = field
1904                    .expr
1905                    .rewrite_result(context, Shape::indented(expr_offset, context.config));
1906                expr.map(|s| {
1907                    format!(
1908                        "{}{}:\n{}{}",
1909                        attrs_str,
1910                        name,
1911                        expr_offset.to_string(context.config),
1912                        s
1913                    )
1914                })
1915            }
1916        }
1917    }
1918}
1919
1920fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1921    context: &RewriteContext<'_>,
1922    mut items: impl Iterator<Item = &'a T>,
1923    span: Span,
1924    shape: Shape,
1925    is_singleton_tuple: bool,
1926) -> RewriteResult {
1927    // In case of length 1, need a trailing comma
1928    debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1929    if is_singleton_tuple {
1930        // 3 = "(" + ",)"
1931        let nested_shape = shape.sub_width(3, span)?.visual_indent(1);
1932        return items
1933            .next()
1934            .unwrap()
1935            .rewrite_result(context, nested_shape)
1936            .map(|s| format!("({},)", s));
1937    }
1938
1939    let list_lo = context.snippet_provider.span_after(span, "(");
1940    let nested_shape = shape.sub_width(2, span)?.visual_indent(1);
1941    let items = itemize_list(
1942        context.snippet_provider,
1943        items,
1944        ")",
1945        ",",
1946        |item| item.span().lo(),
1947        |item| item.span().hi(),
1948        |item| item.rewrite_result(context, nested_shape),
1949        list_lo,
1950        span.hi() - BytePos(1),
1951        false,
1952    );
1953    let item_vec: Vec<_> = items.collect();
1954    let tactic = definitive_tactic(
1955        &item_vec,
1956        ListTactic::HorizontalVertical,
1957        Separator::Comma,
1958        nested_shape.width,
1959    );
1960    let fmt = ListFormatting::new(nested_shape, context.config)
1961        .tactic(tactic)
1962        .ends_with_newline(false);
1963    let list_str = write_list(&item_vec, &fmt)?;
1964
1965    Ok(format!("({list_str})"))
1966}
1967
1968fn rewrite_let(
1969    context: &RewriteContext<'_>,
1970    shape: Shape,
1971    pat: &ast::Pat,
1972    expr: &ast::Expr,
1973) -> RewriteResult {
1974    let mut result = "let ".to_owned();
1975
1976    // TODO(ytmimi) comments could appear between `let` and the `pat`
1977
1978    // 4 = "let ".len()
1979    let mut pat_shape = shape.offset_left(4, pat.span)?;
1980    if context.config.style_edition() >= StyleEdition::Edition2027 {
1981        // 2 for the length of " ="
1982        pat_shape = pat_shape.sub_width(2, pat.span)?;
1983    }
1984    let pat_str = pat.rewrite_result(context, pat_shape)?;
1985    result.push_str(&pat_str);
1986
1987    // TODO(ytmimi) comments could appear between `pat` and `=`
1988    result.push_str(" =");
1989
1990    let comments_lo = context
1991        .snippet_provider
1992        .span_after(expr.span.with_lo(pat.span.hi()), "=");
1993    let comments_span = mk_sp(comments_lo, expr.span.lo());
1994    rewrite_assign_rhs_with_comments(
1995        context,
1996        result,
1997        expr,
1998        shape,
1999        &RhsAssignKind::Expr(&expr.kind, expr.span),
2000        RhsTactics::Default,
2001        comments_span,
2002        true,
2003    )
2004}
2005
2006pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
2007    context: &'a RewriteContext<'_>,
2008    items: impl Iterator<Item = &'a T>,
2009    span: Span,
2010    shape: Shape,
2011    is_singleton_tuple: bool,
2012) -> RewriteResult {
2013    debug!("rewrite_tuple {:?}", shape);
2014    if context.use_block_indent() {
2015        // We use the same rule as function calls for rewriting tuples.
2016        let force_tactic = if context.inside_macro() {
2017            if span_ends_with_comma(context, span) {
2018                Some(SeparatorTactic::Always)
2019            } else {
2020                Some(SeparatorTactic::Never)
2021            }
2022        } else if is_singleton_tuple {
2023            Some(SeparatorTactic::Always)
2024        } else {
2025            None
2026        };
2027        overflow::rewrite_with_parens(
2028            context,
2029            "",
2030            items,
2031            shape,
2032            span,
2033            context.config.fn_call_width(),
2034            force_tactic,
2035        )
2036    } else {
2037        rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
2038    }
2039}
2040
2041pub(crate) fn rewrite_unary_prefix<R: Rewrite + Spanned>(
2042    context: &RewriteContext<'_>,
2043    prefix: &str,
2044    rewrite: &R,
2045    shape: Shape,
2046) -> RewriteResult {
2047    let shape = shape.offset_left(prefix.len(), rewrite.span())?;
2048    rewrite
2049        .rewrite_result(context, shape)
2050        .map(|r| format!("{}{}", prefix, r))
2051}
2052
2053// FIXME: this is probably not correct for multi-line Rewrites. we should
2054// subtract suffix.len() from the last line budget, not the first!
2055pub(crate) fn rewrite_unary_suffix<R: Rewrite + Spanned>(
2056    context: &RewriteContext<'_>,
2057    suffix: &str,
2058    rewrite: &R,
2059    shape: Shape,
2060) -> RewriteResult {
2061    let shape = shape.sub_width(suffix.len(), rewrite.span())?;
2062    rewrite.rewrite_result(context, shape).map(|mut r| {
2063        r.push_str(suffix);
2064        r
2065    })
2066}
2067
2068fn rewrite_unary_op(
2069    context: &RewriteContext<'_>,
2070    op: ast::UnOp,
2071    expr: &ast::Expr,
2072    shape: Shape,
2073) -> RewriteResult {
2074    // For some reason, an UnOp is not spanned like BinOp!
2075    rewrite_unary_prefix(context, op.as_str(), expr, shape)
2076}
2077
2078pub(crate) enum RhsAssignKind<'ast> {
2079    Expr(&'ast ast::ExprKind, #[allow(dead_code)] Span),
2080    Bounds,
2081    Ty,
2082}
2083
2084impl<'ast> RhsAssignKind<'ast> {
2085    // TODO(calebcartwright)
2086    // Preemptive addition for handling RHS with chains, not yet utilized.
2087    // It may make more sense to construct the chain first and then check
2088    // whether there are actually chain elements.
2089    #[allow(dead_code)]
2090    fn is_chain(&self) -> bool {
2091        match self {
2092            RhsAssignKind::Expr(kind, _) => {
2093                matches!(
2094                    kind,
2095                    ast::ExprKind::Try(..)
2096                        | ast::ExprKind::Field(..)
2097                        | ast::ExprKind::MethodCall(..)
2098                        | ast::ExprKind::Await(_, _)
2099                )
2100            }
2101            _ => false,
2102        }
2103    }
2104}
2105
2106fn rewrite_assignment(
2107    context: &RewriteContext<'_>,
2108    lhs: &ast::Expr,
2109    rhs: &ast::Expr,
2110    op: Option<&ast::AssignOp>,
2111    shape: Shape,
2112) -> RewriteResult {
2113    let operator_str = match op {
2114        Some(op) => context.snippet(op.span),
2115        None => "=",
2116    };
2117
2118    // 1 = space between lhs and operator.
2119    let lhs_shape = shape.sub_width(operator_str.len() + 1, lhs.span())?;
2120    let lhs_str = format!(
2121        "{} {}",
2122        lhs.rewrite_result(context, lhs_shape)?,
2123        operator_str
2124    );
2125
2126    rewrite_assign_rhs(
2127        context,
2128        lhs_str,
2129        rhs,
2130        &RhsAssignKind::Expr(&rhs.kind, rhs.span),
2131        shape,
2132    )
2133}
2134
2135/// Controls where to put the rhs.
2136#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2137pub(crate) enum RhsTactics {
2138    /// Use heuristics.
2139    Default,
2140    /// Put the rhs on the next line if it uses multiple line, without extra indentation.
2141    ForceNextLineWithoutIndent,
2142    /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
2143    /// did not work.
2144    AllowOverflow,
2145}
2146
2147// The left hand side must contain everything up to, and including, the
2148// assignment operator.
2149pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2150    context: &RewriteContext<'_>,
2151    lhs: S,
2152    ex: &R,
2153    rhs_kind: &RhsAssignKind<'_>,
2154    shape: Shape,
2155) -> RewriteResult {
2156    rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
2157}
2158
2159pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
2160    context: &RewriteContext<'_>,
2161    lhs: &str,
2162    ex: &R,
2163    shape: Shape,
2164    rhs_kind: &RhsAssignKind<'_>,
2165    rhs_tactics: RhsTactics,
2166) -> RewriteResult {
2167    let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
2168        shape.indent.width()
2169    } else {
2170        0
2171    });
2172    // 1 = space between operator and rhs.
2173    let orig_shape = shape.offset_left_opt(last_line_width + 1).unwrap_or(Shape {
2174        width: 0,
2175        offset: shape.offset + last_line_width + 1,
2176        ..shape
2177    });
2178    let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
2179        lhs.trim_end().len() > offset + 1
2180    } else {
2181        false
2182    };
2183
2184    choose_rhs(
2185        context,
2186        ex,
2187        orig_shape,
2188        ex.rewrite_result(context, orig_shape),
2189        rhs_kind,
2190        rhs_tactics,
2191        has_rhs_comment,
2192    )
2193}
2194
2195pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2196    context: &RewriteContext<'_>,
2197    lhs: S,
2198    ex: &R,
2199    shape: Shape,
2200    rhs_kind: &RhsAssignKind<'_>,
2201    rhs_tactics: RhsTactics,
2202) -> RewriteResult {
2203    let lhs = lhs.into();
2204    let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2205    Ok(lhs + &rhs)
2206}
2207
2208pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite + Spanned>(
2209    context: &RewriteContext<'_>,
2210    lhs: S,
2211    ex: &R,
2212    shape: Shape,
2213    rhs_kind: &RhsAssignKind<'_>,
2214    rhs_tactics: RhsTactics,
2215    between_span: Span,
2216    allow_extend: bool,
2217) -> RewriteResult {
2218    let lhs = lhs.into();
2219    let contains_comment = contains_comment(context.snippet(between_span));
2220    let shape = if contains_comment {
2221        shape.block_left(
2222            context.config.tab_spaces(),
2223            between_span.with_hi(ex.span().hi()),
2224        )?
2225    } else {
2226        shape
2227    };
2228    let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2229    if contains_comment {
2230        let rhs = rhs.trim_start();
2231        combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2232    } else {
2233        Ok(lhs + &rhs)
2234    }
2235}
2236
2237fn choose_rhs<R: Rewrite>(
2238    context: &RewriteContext<'_>,
2239    expr: &R,
2240    shape: Shape,
2241    orig_rhs: RewriteResult,
2242    _rhs_kind: &RhsAssignKind<'_>,
2243    rhs_tactics: RhsTactics,
2244    has_rhs_comment: bool,
2245) -> RewriteResult {
2246    match orig_rhs {
2247        Ok(ref new_str) if new_str.is_empty() => Ok(String::new()),
2248        Ok(ref new_str) if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width => {
2249            Ok(format!(" {new_str}"))
2250        }
2251        _ => {
2252            // Expression did not fit on the same line as the identifier.
2253            // Try splitting the line and see if that works better.
2254            let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)
2255                // TODO(ding-young) Ideally, we can replace unknown_error() with max_width_error(),
2256                // but this requires either implementing the Spanned trait for ast::GenericBounds
2257                // or grabbing the span from the call site.
2258                .unknown_error()?;
2259            let new_rhs = expr.rewrite_result(context, new_shape);
2260            let new_indent_str = &shape
2261                .indent
2262                .block_indent(context.config)
2263                .to_string_with_newline(context.config);
2264            let before_space_str = if has_rhs_comment { "" } else { " " };
2265
2266            match (orig_rhs, new_rhs) {
2267                (Ok(ref orig_rhs), Ok(ref new_rhs))
2268                    if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) =>
2269                {
2270                    Ok(format!("{before_space_str}{orig_rhs}"))
2271                }
2272                (Ok(ref orig_rhs), Ok(ref new_rhs))
2273                    if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2274                {
2275                    Ok(format!("{new_indent_str}{new_rhs}"))
2276                }
2277                (Err(_), Ok(ref new_rhs)) => Ok(format!("{new_indent_str}{new_rhs}")),
2278                (Err(_), Err(_)) if rhs_tactics == RhsTactics::AllowOverflow => {
2279                    let shape = shape.infinite_width();
2280                    expr.rewrite_result(context, shape)
2281                        .map(|s| format!("{}{}", before_space_str, s))
2282                }
2283                // When both orig_rhs and new_rhs result in errors, we currently propagate
2284                // the error from the second attempt since it is more generous with
2285                // width constraints. This decision is somewhat arbitrary and is open to change.
2286                (Err(_), Err(new_rhs_err)) => Err(new_rhs_err),
2287                (Ok(orig_rhs), _) => Ok(format!("{before_space_str}{orig_rhs}")),
2288            }
2289        }
2290    }
2291}
2292
2293fn shape_from_rhs_tactic(
2294    context: &RewriteContext<'_>,
2295    shape: Shape,
2296    rhs_tactic: RhsTactics,
2297) -> Option<Shape> {
2298    match rhs_tactic {
2299        RhsTactics::ForceNextLineWithoutIndent => shape
2300            .with_max_width(context.config)
2301            .sub_width_opt(shape.indent.width()),
2302        RhsTactics::Default | RhsTactics::AllowOverflow => {
2303            Shape::indented(shape.indent.block_indent(context.config), context.config)
2304                .sub_width_opt(shape.rhs_overhead(context.config))
2305        }
2306    }
2307}
2308
2309/// Returns true if formatting next_line_rhs is better on a new line when compared to the
2310/// original's line formatting.
2311///
2312/// It is considered better if:
2313/// 1. the tactic is ForceNextLineWithoutIndent
2314/// 2. next_line_rhs doesn't have newlines
2315/// 3. the original line has more newlines than next_line_rhs
2316/// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2317///    doesn't
2318pub(crate) fn prefer_next_line(
2319    orig_rhs: &str,
2320    next_line_rhs: &str,
2321    rhs_tactics: RhsTactics,
2322) -> bool {
2323    rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2324        || !next_line_rhs.contains('\n')
2325        || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2326        || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2327        || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2328        || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2329}
2330
2331fn rewrite_expr_addrof(
2332    context: &RewriteContext<'_>,
2333    borrow_kind: ast::BorrowKind,
2334    mutability: ast::Mutability,
2335    expr: &ast::Expr,
2336    shape: Shape,
2337) -> RewriteResult {
2338    let operator_str = match (mutability, borrow_kind) {
2339        (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2340        (ast::Mutability::Not, ast::BorrowKind::Pin) => "&pin const ",
2341        (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2342        (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2343        (ast::Mutability::Mut, ast::BorrowKind::Pin) => "&pin mut ",
2344        (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2345    };
2346    rewrite_unary_prefix(context, operator_str, expr, shape)
2347}
2348
2349pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2350    match expr.kind {
2351        ast::ExprKind::MethodCall(..) => true,
2352        ast::ExprKind::AddrOf(_, _, ref expr)
2353        | ast::ExprKind::Cast(ref expr, _)
2354        | ast::ExprKind::Try(ref expr)
2355        | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2356        _ => false,
2357    }
2358}
2359
2360/// Indicates the parts of a float literal specified as a string.
2361struct FloatSymbolParts<'a> {
2362    /// The integer part, e.g. `123` in `123.456e789`.
2363    /// Always non-empty, because in Rust `.1` is not a valid floating-point literal:
2364    /// <https://doc.rust-lang.org/reference/tokens.html#floating-point-literals>
2365    integer_part: &'a str,
2366    /// The fractional part excluding the decimal point, e.g. `456` in `123.456e789`.
2367    fractional_part: Option<&'a str>,
2368    /// The exponent part including the `e` or `E`, e.g. `e789` in `123.456e789`.
2369    exponent: Option<&'a str>,
2370}
2371
2372impl FloatSymbolParts<'_> {
2373    fn is_fractional_part_zero(&self) -> bool {
2374        let zero_literal_regex = static_regex!(r"^[0_]+$");
2375        self.fractional_part
2376            .is_none_or(|s| zero_literal_regex.is_match(s))
2377    }
2378}
2379
2380/// Parses a float literal. The `symbol` must be a valid floating point literal without a type
2381/// suffix. Otherwise the function may panic or return wrong result.
2382fn parse_float_symbol(symbol: &str) -> Result<FloatSymbolParts<'_>, &'static str> {
2383    // This regex may accept invalid float literals (such as `1`, `_` or `2.e3`). That's ok.
2384    // We only use it to parse literals whose validity has already been established.
2385    let float_literal_regex = static_regex!(r"^([0-9_]+)(?:\.([0-9_]+)?)?([eE][+-]?[0-9_]+)?$");
2386    let caps = float_literal_regex
2387        .captures(symbol)
2388        .ok_or("invalid float literal")?;
2389    Ok(FloatSymbolParts {
2390        integer_part: caps.get(1).ok_or("missing integer part")?.as_str(),
2391        fractional_part: caps.get(2).map(|m| m.as_str()),
2392        exponent: caps.get(3).map(|m| m.as_str()),
2393    })
2394}
2395
2396#[cfg(test)]
2397mod test {
2398    use super::*;
2399
2400    #[test]
2401    fn test_last_line_offsetted() {
2402        let lines = "one\n    two";
2403        assert_eq!(last_line_offsetted(2, lines), true);
2404        assert_eq!(last_line_offsetted(4, lines), false);
2405        assert_eq!(last_line_offsetted(6, lines), false);
2406
2407        let lines = "one    two";
2408        assert_eq!(last_line_offsetted(2, lines), false);
2409        assert_eq!(last_line_offsetted(0, lines), false);
2410
2411        let lines = "\ntwo";
2412        assert_eq!(last_line_offsetted(2, lines), false);
2413        assert_eq!(last_line_offsetted(0, lines), false);
2414
2415        let lines = "one\n    two      three";
2416        assert_eq!(last_line_offsetted(2, lines), true);
2417        let lines = "one\n two      three";
2418        assert_eq!(last_line_offsetted(2, lines), false);
2419    }
2420
2421    #[test]
2422    fn test_parse_float_symbol() {
2423        let parts = parse_float_symbol("123.456e789").unwrap();
2424        assert_eq!(parts.integer_part, "123");
2425        assert_eq!(parts.fractional_part, Some("456"));
2426        assert_eq!(parts.exponent, Some("e789"));
2427
2428        let parts = parse_float_symbol("123.456e+789").unwrap();
2429        assert_eq!(parts.integer_part, "123");
2430        assert_eq!(parts.fractional_part, Some("456"));
2431        assert_eq!(parts.exponent, Some("e+789"));
2432
2433        let parts = parse_float_symbol("123.456e-789").unwrap();
2434        assert_eq!(parts.integer_part, "123");
2435        assert_eq!(parts.fractional_part, Some("456"));
2436        assert_eq!(parts.exponent, Some("e-789"));
2437
2438        let parts = parse_float_symbol("123e789").unwrap();
2439        assert_eq!(parts.integer_part, "123");
2440        assert_eq!(parts.fractional_part, None);
2441        assert_eq!(parts.exponent, Some("e789"));
2442
2443        let parts = parse_float_symbol("123E789").unwrap();
2444        assert_eq!(parts.integer_part, "123");
2445        assert_eq!(parts.fractional_part, None);
2446        assert_eq!(parts.exponent, Some("E789"));
2447
2448        let parts = parse_float_symbol("123.").unwrap();
2449        assert_eq!(parts.integer_part, "123");
2450        assert_eq!(parts.fractional_part, None);
2451        assert_eq!(parts.exponent, None);
2452    }
2453
2454    #[test]
2455    fn test_parse_float_symbol_with_underscores() {
2456        let parts = parse_float_symbol("_123._456e_789").unwrap();
2457        assert_eq!(parts.integer_part, "_123");
2458        assert_eq!(parts.fractional_part, Some("_456"));
2459        assert_eq!(parts.exponent, Some("e_789"));
2460
2461        let parts = parse_float_symbol("123_.456_e789_").unwrap();
2462        assert_eq!(parts.integer_part, "123_");
2463        assert_eq!(parts.fractional_part, Some("456_"));
2464        assert_eq!(parts.exponent, Some("e789_"));
2465
2466        let parts = parse_float_symbol("1_23.4_56e7_89").unwrap();
2467        assert_eq!(parts.integer_part, "1_23");
2468        assert_eq!(parts.fractional_part, Some("4_56"));
2469        assert_eq!(parts.exponent, Some("e7_89"));
2470
2471        let parts = parse_float_symbol("_1_23_._4_56_e_7_89_").unwrap();
2472        assert_eq!(parts.integer_part, "_1_23_");
2473        assert_eq!(parts.fractional_part, Some("_4_56_"));
2474        assert_eq!(parts.exponent, Some("e_7_89_"));
2475    }
2476
2477    #[test]
2478    fn test_float_lit_ends_in_dot() {
2479        type TZ = FloatLiteralTrailingZero;
2480
2481        assert!(float_lit_ends_in_dot("1.", None, TZ::Preserve));
2482        assert!(!float_lit_ends_in_dot("1.0", None, TZ::Preserve));
2483        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Preserve));
2484        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Preserve));
2485        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Preserve));
2486        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Preserve));
2487
2488        assert!(!float_lit_ends_in_dot("1.", None, TZ::Always));
2489        assert!(!float_lit_ends_in_dot("1.0", None, TZ::Always));
2490        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Always));
2491        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Always));
2492        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Always));
2493        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Always));
2494
2495        assert!(!float_lit_ends_in_dot("1.", None, TZ::IfNoPostfix));
2496        assert!(!float_lit_ends_in_dot("1.0", None, TZ::IfNoPostfix));
2497        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::IfNoPostfix));
2498        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::IfNoPostfix));
2499        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::IfNoPostfix));
2500        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::IfNoPostfix));
2501
2502        assert!(float_lit_ends_in_dot("1.", None, TZ::Never));
2503        assert!(float_lit_ends_in_dot("1.0", None, TZ::Never));
2504        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Never));
2505        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Never));
2506        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Never));
2507        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Never));
2508    }
2509}