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