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