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 {
783            ref pat,
784            ref iter,
785            ref body,
786            label,
787            kind,
788        } => Some(ControlFlow::new_for(
789            pat, iter, body, label, expr.span, kind,
790        )),
791        ast::ExprKind::Loop(ref block, label, _) => {
792            Some(ControlFlow::new_loop(block, label, expr.span))
793        }
794        ast::ExprKind::While(ref cond, ref block, label) => {
795            let (pat, cond) = extract_pats_and_cond(cond);
796            Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
797        }
798        _ => None,
799    }
800}
801
802fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
803    pat.map_or("", |_| "let")
804}
805
806impl<'a> ControlFlow<'a> {
807    fn new_if(
808        cond: &'a ast::Expr,
809        pat: Option<&'a ast::Pat>,
810        block: &'a ast::Block,
811        else_block: Option<&'a ast::Expr>,
812        allow_single_line: bool,
813        nested_if: bool,
814        span: Span,
815    ) -> ControlFlow<'a> {
816        let matcher = choose_matcher(pat);
817        ControlFlow {
818            cond: Some(cond),
819            block,
820            else_block,
821            label: None,
822            pat,
823            keyword: "if",
824            matcher,
825            connector: " =",
826            allow_single_line,
827            nested_if,
828            is_loop: false,
829            span,
830        }
831    }
832
833    fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
834        ControlFlow {
835            cond: None,
836            block,
837            else_block: None,
838            label,
839            pat: None,
840            keyword: "loop",
841            matcher: "",
842            connector: "",
843            allow_single_line: false,
844            nested_if: false,
845            is_loop: true,
846            span,
847        }
848    }
849
850    fn new_while(
851        pat: Option<&'a ast::Pat>,
852        cond: &'a ast::Expr,
853        block: &'a ast::Block,
854        label: Option<ast::Label>,
855        span: Span,
856    ) -> ControlFlow<'a> {
857        let matcher = choose_matcher(pat);
858        ControlFlow {
859            cond: Some(cond),
860            block,
861            else_block: None,
862            label,
863            pat,
864            keyword: "while",
865            matcher,
866            connector: " =",
867            allow_single_line: false,
868            nested_if: false,
869            is_loop: true,
870            span,
871        }
872    }
873
874    fn new_for(
875        pat: &'a ast::Pat,
876        cond: &'a ast::Expr,
877        block: &'a ast::Block,
878        label: Option<ast::Label>,
879        span: Span,
880        kind: ForLoopKind,
881    ) -> ControlFlow<'a> {
882        ControlFlow {
883            cond: Some(cond),
884            block,
885            else_block: None,
886            label,
887            pat: Some(pat),
888            keyword: match kind {
889                ForLoopKind::For => "for",
890                ForLoopKind::ForAwait => "for await",
891            },
892            matcher: "",
893            connector: " in",
894            allow_single_line: false,
895            nested_if: false,
896            is_loop: true,
897            span,
898        }
899    }
900
901    fn rewrite_single_line(
902        &self,
903        pat_expr_str: &str,
904        context: &RewriteContext<'_>,
905        width: usize,
906    ) -> Option<String> {
907        assert!(self.allow_single_line);
908        let else_block = self.else_block?;
909        let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
910
911        if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
912            let (if_expr, else_expr) = match (
913                stmt::Stmt::from_simple_block(context, self.block, None),
914                stmt::Stmt::from_simple_block(context, else_node, None),
915                pat_expr_str.contains('\n'),
916            ) {
917                (Some(if_expr), Some(else_expr), false) => (if_expr, else_expr),
918                _ => return None,
919            };
920
921            let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
922            let if_str = if_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
923
924            let new_width = new_width.checked_sub(if_str.len())?;
925            let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
926
927            if if_str.contains('\n') || else_str.contains('\n') {
928                return None;
929            }
930
931            let result = format!(
932                "{} {} {{ {} }} else {{ {} }}",
933                self.keyword, pat_expr_str, if_str, else_str
934            );
935
936            if result.len() <= width {
937                return Some(result);
938            }
939        }
940
941        None
942    }
943}
944
945/// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
946/// shape's indent.
947fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
948    let mut leading_whitespaces = 0;
949    for c in pat_str.chars().rev() {
950        match c {
951            '\n' => break,
952            _ if c.is_whitespace() => leading_whitespaces += 1,
953            _ => leading_whitespaces = 0,
954        }
955    }
956    leading_whitespaces > start_column
957}
958
959impl<'a> ControlFlow<'a> {
960    fn rewrite_pat_expr(
961        &self,
962        context: &RewriteContext<'_>,
963        expr: &ast::Expr,
964        shape: Shape,
965        offset: usize,
966    ) -> RewriteResult {
967        debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
968
969        let cond_shape = shape.offset_left(offset, expr.span)?;
970        if let Some(pat) = self.pat {
971            let matcher = if self.matcher.is_empty() {
972                self.matcher.to_owned()
973            } else {
974                format!("{} ", self.matcher)
975            };
976            let pat_shape = cond_shape
977                .offset_left(matcher.len(), pat.span)?
978                .sub_width(self.connector.len(), pat.span)?;
979            let pat_string = pat.rewrite_result(context, pat_shape)?;
980            let comments_lo = context
981                .snippet_provider
982                .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
983            let comments_span = mk_sp(comments_lo, expr.span.lo());
984            return rewrite_assign_rhs_with_comments(
985                context,
986                &format!("{}{}{}", matcher, pat_string, self.connector),
987                expr,
988                cond_shape,
989                &RhsAssignKind::Expr(&expr.kind, expr.span),
990                RhsTactics::Default,
991                comments_span,
992                true,
993            );
994        }
995
996        let expr_rw = expr.rewrite_result(context, cond_shape);
997        // The expression may (partially) fit on the current line.
998        // We do not allow splitting between `if` and condition.
999        if self.keyword == "if" || expr_rw.is_ok() {
1000            return expr_rw;
1001        }
1002
1003        // The expression won't fit on the current line, jump to next.
1004        let nested_shape = shape
1005            .block_indent(context.config.tab_spaces())
1006            .with_max_width(context.config);
1007        let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
1008        expr.rewrite_result(context, nested_shape)
1009            .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
1010    }
1011
1012    fn rewrite_cond(
1013        &self,
1014        context: &RewriteContext<'_>,
1015        shape: Shape,
1016        alt_block_sep: &str,
1017    ) -> Result<(String, usize), RewriteError> {
1018        // Do not take the rhs overhead from the upper expressions into account
1019        // when rewriting pattern.
1020        let new_width = context.budget(shape.used_width());
1021        let fresh_shape = Shape {
1022            width: new_width,
1023            ..shape
1024        };
1025        let constr_shape = if self.nested_if {
1026            // We are part of an if-elseif-else chain. Our constraints are tightened.
1027            // 7 = "} else " .len()
1028            fresh_shape.offset_left(7, self.span)?
1029        } else {
1030            fresh_shape
1031        };
1032
1033        let label_string = rewrite_label(context, self.label);
1034        // 1 = space after keyword.
1035        let offset = self.keyword.len() + label_string.len() + 1;
1036
1037        let pat_expr_string = match self.cond {
1038            Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
1039            None => String::new(),
1040        };
1041
1042        let brace_overhead =
1043            if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1044                // 2 = ` {`
1045                2
1046            } else {
1047                0
1048            };
1049        let one_line_budget = context
1050            .config
1051            .max_width()
1052            .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
1053        let force_newline_brace = (pat_expr_string.contains('\n')
1054            || pat_expr_string.len() > one_line_budget)
1055            && (!last_line_extendable(&pat_expr_string)
1056                || last_line_offsetted(shape.used_width(), &pat_expr_string));
1057
1058        // Try to format if-else on single line.
1059        if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1060            let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1061
1062            if let Some(cond_str) = trial {
1063                if cond_str.len() <= context.config.single_line_if_else_max_width() {
1064                    return Ok((cond_str, 0));
1065                }
1066            }
1067        }
1068
1069        let cond_span = if let Some(cond) = self.cond {
1070            cond.span
1071        } else {
1072            mk_sp(self.block.span.lo(), self.block.span.lo())
1073        };
1074
1075        // `for event in event`
1076        // Do not include label in the span.
1077        let lo = self
1078            .label
1079            .map_or(self.span.lo(), |label| label.ident.span.hi());
1080        let between_kwd_cond = mk_sp(
1081            context
1082                .snippet_provider
1083                .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1084            if self.pat.is_none() {
1085                cond_span.lo()
1086            } else if self.matcher.is_empty() {
1087                self.pat.unwrap().span.lo()
1088            } else {
1089                context
1090                    .snippet_provider
1091                    .span_before(self.span, self.matcher.trim())
1092            },
1093        );
1094
1095        let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1096
1097        let after_cond_comment =
1098            extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1099
1100        let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1101            ""
1102        } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1103            || force_newline_brace
1104        {
1105            alt_block_sep
1106        } else {
1107            " "
1108        };
1109
1110        let used_width = if pat_expr_string.contains('\n') {
1111            last_line_width(&pat_expr_string)
1112        } else {
1113            // 2 = spaces after keyword and condition.
1114            label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1115        };
1116
1117        Ok((
1118            format!(
1119                "{}{}{}{}{}",
1120                label_string,
1121                self.keyword,
1122                between_kwd_cond_comment.as_ref().map_or(
1123                    if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1124                        ""
1125                    } else {
1126                        " "
1127                    },
1128                    |s| &**s,
1129                ),
1130                pat_expr_string,
1131                after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1132            ),
1133            used_width,
1134        ))
1135    }
1136}
1137
1138/// Rewrite the `else` keyword with surrounding comments.
1139///
1140/// force_newline_else: whether or not to rewrite the `else` keyword on a newline.
1141/// is_last: true if this is an `else` and `false` if this is an `else if` block.
1142/// context: rewrite context
1143/// span: Span between the end of the last expression and the start of the else block,
1144///       which contains the `else` keyword
1145/// shape: Shape
1146pub(crate) fn rewrite_else_kw_with_comments(
1147    force_newline_else: bool,
1148    is_last: bool,
1149    context: &RewriteContext<'_>,
1150    span: Span,
1151    shape: Shape,
1152) -> String {
1153    let else_kw_lo = context.snippet_provider.span_before(span, "else");
1154    let before_else_kw = mk_sp(span.lo(), else_kw_lo);
1155    let before_else_kw_comment = extract_comment(before_else_kw, context, shape);
1156
1157    let else_kw_hi = context.snippet_provider.span_after(span, "else");
1158    let after_else_kw = mk_sp(else_kw_hi, span.hi());
1159    let after_else_kw_comment = extract_comment(after_else_kw, context, shape);
1160
1161    let newline_sep = &shape.indent.to_string_with_newline(context.config);
1162    let before_sep = match context.config.control_brace_style() {
1163        _ if force_newline_else => newline_sep.as_ref(),
1164        ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1165            newline_sep.as_ref()
1166        }
1167        ControlBraceStyle::AlwaysSameLine => " ",
1168    };
1169    let after_sep = match context.config.control_brace_style() {
1170        ControlBraceStyle::AlwaysNextLine if is_last => newline_sep.as_ref(),
1171        _ => " ",
1172    };
1173
1174    format!(
1175        "{}else{}",
1176        before_else_kw_comment.as_ref().map_or(before_sep, |s| &**s),
1177        after_else_kw_comment.as_ref().map_or(after_sep, |s| &**s),
1178    )
1179}
1180
1181impl<'a> Rewrite for ControlFlow<'a> {
1182    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1183        self.rewrite_result(context, shape).ok()
1184    }
1185
1186    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1187        debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1188
1189        let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1190        let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1191        // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1192        if used_width == 0 {
1193            return Ok(cond_str);
1194        }
1195
1196        let block_width = shape.width.saturating_sub(used_width);
1197        // This is used only for the empty block case: `{}`. So, we use 1 if we know
1198        // we should avoid the single line case.
1199        let block_width = if self.else_block.is_some() || self.nested_if {
1200            min(1, block_width)
1201        } else {
1202            block_width
1203        };
1204        let block_shape = Shape {
1205            width: block_width,
1206            ..shape
1207        };
1208        let block_str = {
1209            let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1210            let old_is_loop = context.is_loop_block.replace(self.is_loop);
1211            let result =
1212                rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1213            context.is_loop_block.replace(old_is_loop);
1214            context.is_if_else_block.replace(old_val);
1215            result?
1216        };
1217
1218        let mut result = format!("{cond_str}{block_str}");
1219
1220        if let Some(else_block) = self.else_block {
1221            let shape = Shape::indented(shape.indent, context.config);
1222            let mut last_in_chain = false;
1223            let rewrite = match else_block.kind {
1224                // If the else expression is another if-else expression, prevent it
1225                // from being formatted on a single line.
1226                // Note how we're passing the original shape, as the
1227                // cost of "else" should not cascade.
1228                ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1229                    let (pats, cond) = extract_pats_and_cond(cond);
1230                    ControlFlow::new_if(
1231                        cond,
1232                        pats,
1233                        if_block,
1234                        next_else_block.as_ref().map(|e| &**e),
1235                        false,
1236                        true,
1237                        mk_sp(else_block.span.lo(), self.span.hi()),
1238                    )
1239                    .rewrite_result(context, shape)
1240                }
1241                _ => {
1242                    last_in_chain = true;
1243                    // When rewriting a block, the width is only used for single line
1244                    // blocks, passing 1 lets us avoid that.
1245                    let else_shape = Shape {
1246                        width: min(1, shape.width),
1247                        ..shape
1248                    };
1249                    format_expr(else_block, ExprType::Statement, context, else_shape)
1250                }
1251            };
1252
1253            let else_kw = rewrite_else_kw_with_comments(
1254                false,
1255                last_in_chain,
1256                context,
1257                self.block.span.between(else_block.span),
1258                shape,
1259            );
1260            result.push_str(&else_kw);
1261            result.push_str(&rewrite?);
1262        }
1263
1264        Ok(result)
1265    }
1266}
1267
1268fn rewrite_label(context: &RewriteContext<'_>, opt_label: Option<ast::Label>) -> Cow<'static, str> {
1269    match opt_label {
1270        Some(label) => Cow::from(format!("{}: ", context.snippet(label.ident.span))),
1271        None => Cow::from(""),
1272    }
1273}
1274
1275fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1276    match rewrite_missing_comment(span, shape, context) {
1277        Ok(ref comment) if !comment.is_empty() => Some(format!(
1278            "{indent}{comment}{indent}",
1279            indent = shape.indent.to_string_with_newline(context.config)
1280        )),
1281        _ => None,
1282    }
1283}
1284
1285pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1286    contains_comment(context.snippet(block.span))
1287}
1288
1289// Checks that a block contains no statements, an expression and no comments or
1290// attributes.
1291// FIXME: incorrectly returns false when comment is contained completely within
1292// the expression.
1293pub(crate) fn is_simple_block(
1294    context: &RewriteContext<'_>,
1295    block: &ast::Block,
1296    attrs: Option<&[ast::Attribute]>,
1297) -> bool {
1298    block.stmts.len() == 1
1299        && stmt_is_expr(&block.stmts[0])
1300        && !block_contains_comment(context, block)
1301        && attrs.map_or(true, |a| a.is_empty())
1302}
1303
1304/// Checks whether a block contains at most one statement or expression, and no
1305/// comments or attributes.
1306pub(crate) fn is_simple_block_stmt(
1307    context: &RewriteContext<'_>,
1308    block: &ast::Block,
1309    attrs: Option<&[ast::Attribute]>,
1310) -> bool {
1311    block.stmts.len() <= 1
1312        && !block_contains_comment(context, block)
1313        && attrs.map_or(true, |a| a.is_empty())
1314}
1315
1316fn block_has_statements(block: &ast::Block) -> bool {
1317    block
1318        .stmts
1319        .iter()
1320        .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1321}
1322
1323/// Checks whether a block contains no statements, expressions, comments, or
1324/// inner attributes.
1325pub(crate) fn is_empty_block(
1326    context: &RewriteContext<'_>,
1327    block: &ast::Block,
1328    attrs: Option<&[ast::Attribute]>,
1329) -> bool {
1330    !block_has_statements(block)
1331        && !block_contains_comment(context, block)
1332        && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1333}
1334
1335pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1336    matches!(stmt.kind, ast::StmtKind::Expr(..))
1337}
1338
1339pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1340    matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1341}
1342
1343pub(crate) fn rewrite_literal(
1344    context: &RewriteContext<'_>,
1345    token_lit: token::Lit,
1346    span: Span,
1347    shape: Shape,
1348) -> RewriteResult {
1349    match token_lit.kind {
1350        token::LitKind::Str => rewrite_string_lit(context, span, shape),
1351        token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape),
1352        token::LitKind::Float => rewrite_float_lit(context, token_lit, span, shape),
1353        _ => wrap_str(
1354            context.snippet(span).to_owned(),
1355            context.config.max_width(),
1356            shape,
1357        )
1358        .max_width_error(shape.width, span),
1359    }
1360}
1361
1362fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> RewriteResult {
1363    let string_lit = context.snippet(span);
1364
1365    if !context.config.format_strings() {
1366        if string_lit
1367            .lines()
1368            .dropping_back(1)
1369            .all(|line| line.ends_with('\\'))
1370            && context.config.style_edition() >= StyleEdition::Edition2024
1371        {
1372            return Ok(string_lit.to_owned());
1373        } else {
1374            return wrap_str(string_lit.to_owned(), context.config.max_width(), shape)
1375                .max_width_error(shape.width, span);
1376        }
1377    }
1378
1379    // Remove the quote characters.
1380    let str_lit = &string_lit[1..string_lit.len() - 1];
1381
1382    rewrite_string(
1383        str_lit,
1384        &StringFormat::new(shape.visual_indent(0), context.config),
1385        shape.width.saturating_sub(2),
1386    )
1387    .max_width_error(shape.width, span)
1388}
1389
1390fn rewrite_int_lit(
1391    context: &RewriteContext<'_>,
1392    token_lit: token::Lit,
1393    span: Span,
1394    shape: Shape,
1395) -> RewriteResult {
1396    if token_lit.is_semantic_float() {
1397        return rewrite_float_lit(context, token_lit, span, shape);
1398    }
1399
1400    let symbol = token_lit.symbol.as_str();
1401
1402    if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1403        let hex_lit = match context.config.hex_literal_case() {
1404            HexLiteralCase::Preserve => None,
1405            HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1406            HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1407        };
1408        if let Some(hex_lit) = hex_lit {
1409            return wrap_str(
1410                format!(
1411                    "0x{}{}",
1412                    hex_lit,
1413                    token_lit.suffix.as_ref().map_or("", |s| s.as_str())
1414                ),
1415                context.config.max_width(),
1416                shape,
1417            )
1418            .max_width_error(shape.width, span);
1419        }
1420    }
1421
1422    wrap_str(
1423        context.snippet(span).to_owned(),
1424        context.config.max_width(),
1425        shape,
1426    )
1427    .max_width_error(shape.width, span)
1428}
1429
1430fn rewrite_float_lit(
1431    context: &RewriteContext<'_>,
1432    token_lit: token::Lit,
1433    span: Span,
1434    shape: Shape,
1435) -> RewriteResult {
1436    if matches!(
1437        context.config.float_literal_trailing_zero(),
1438        FloatLiteralTrailingZero::Preserve
1439    ) {
1440        return wrap_str(
1441            context.snippet(span).to_owned(),
1442            context.config.max_width(),
1443            shape,
1444        )
1445        .max_width_error(shape.width, span);
1446    }
1447
1448    let symbol = token_lit.symbol.as_str();
1449    let suffix = token_lit.suffix.as_ref().map(|s| s.as_str());
1450
1451    let float_parts = parse_float_symbol(symbol).unwrap();
1452    let FloatSymbolParts {
1453        integer_part,
1454        fractional_part,
1455        exponent,
1456    } = float_parts;
1457
1458    let has_postfix = exponent.is_some() || suffix.is_some();
1459    let fractional_part_nonzero = !float_parts.is_fractional_part_zero();
1460
1461    let (include_period, include_fractional_part) =
1462        match context.config.float_literal_trailing_zero() {
1463            FloatLiteralTrailingZero::Preserve => unreachable!("handled above"),
1464            FloatLiteralTrailingZero::Always => (true, true),
1465            FloatLiteralTrailingZero::IfNoPostfix => (
1466                fractional_part_nonzero || !has_postfix,
1467                fractional_part_nonzero || !has_postfix,
1468            ),
1469            FloatLiteralTrailingZero::Never => (
1470                fractional_part_nonzero || !has_postfix,
1471                fractional_part_nonzero,
1472            ),
1473        };
1474
1475    let period = if include_period { "." } else { "" };
1476    let fractional_part = if include_fractional_part {
1477        fractional_part.unwrap_or("0")
1478    } else {
1479        ""
1480    };
1481    wrap_str(
1482        format!(
1483            "{}{}{}{}{}",
1484            integer_part,
1485            period,
1486            fractional_part,
1487            exponent.unwrap_or(""),
1488            suffix.unwrap_or(""),
1489        ),
1490        context.config.max_width(),
1491        shape,
1492    )
1493    .max_width_error(shape.width, span)
1494}
1495
1496fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1497    if context.inside_macro() {
1498        if span_ends_with_comma(context, span) {
1499            Some(SeparatorTactic::Always)
1500        } else {
1501            Some(SeparatorTactic::Never)
1502        }
1503    } else {
1504        None
1505    }
1506}
1507
1508pub(crate) fn rewrite_call(
1509    context: &RewriteContext<'_>,
1510    callee: &str,
1511    args: &[Box<ast::Expr>],
1512    span: Span,
1513    shape: Shape,
1514) -> RewriteResult {
1515    overflow::rewrite_with_parens(
1516        context,
1517        callee,
1518        args.iter(),
1519        shape,
1520        span,
1521        context.config.fn_call_width(),
1522        choose_separator_tactic(context, span),
1523    )
1524}
1525
1526pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1527    match expr.kind {
1528        ast::ExprKind::Lit(..) => true,
1529        ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1530        ast::ExprKind::AddrOf(_, _, ref expr)
1531        | ast::ExprKind::Cast(ref expr, _)
1532        | ast::ExprKind::Field(ref expr, _)
1533        | ast::ExprKind::Try(ref expr)
1534        | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1535        ast::ExprKind::Index(ref lhs, ref rhs, _) => is_simple_expr(lhs) && is_simple_expr(rhs),
1536        ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1537            is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1538        }
1539        _ => false,
1540    }
1541}
1542
1543pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1544    lists.iter().all(OverflowableItem::is_simple)
1545}
1546
1547pub(crate) fn can_be_overflowed_expr(
1548    context: &RewriteContext<'_>,
1549    expr: &ast::Expr,
1550    args_len: usize,
1551) -> bool {
1552    match expr.kind {
1553        _ if !expr.attrs.is_empty() => false,
1554        ast::ExprKind::Match(..) => {
1555            (context.use_block_indent() && args_len == 1)
1556                || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1557                || context.config.overflow_delimited_expr()
1558        }
1559        ast::ExprKind::If(..)
1560        | ast::ExprKind::ForLoop { .. }
1561        | ast::ExprKind::Loop(..)
1562        | ast::ExprKind::While(..) => {
1563            context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1564        }
1565
1566        // Handle always block-like expressions
1567        ast::ExprKind::Gen(..)
1568        | ast::ExprKind::Block(..)
1569        | ast::ExprKind::Closure(..)
1570        | ast::ExprKind::TryBlock(..) => true,
1571
1572        // Handle `[]` and `{}`-like expressions
1573        ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1574            context.config.overflow_delimited_expr()
1575                || (context.use_block_indent() && args_len == 1)
1576        }
1577        ast::ExprKind::MacCall(ref mac) => {
1578            match (mac.args.delim, context.config.overflow_delimited_expr()) {
1579                (Delimiter::Bracket, true) | (Delimiter::Brace, true) => true,
1580                _ => context.use_block_indent() && args_len == 1,
1581            }
1582        }
1583
1584        // Handle parenthetical expressions
1585        ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1586            context.use_block_indent() && args_len == 1
1587        }
1588
1589        // Handle unary-like expressions
1590        ast::ExprKind::AddrOf(_, _, ref expr)
1591        | ast::ExprKind::Try(ref expr)
1592        | ast::ExprKind::Unary(_, ref expr)
1593        | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1594        _ => false,
1595    }
1596}
1597
1598pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1599    match expr.kind {
1600        ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1601        ast::ExprKind::AddrOf(_, _, ref expr)
1602        | ast::ExprKind::Try(ref expr)
1603        | ast::ExprKind::Unary(_, ref expr)
1604        | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1605        _ => false,
1606    }
1607}
1608
1609/// Returns `true` if a function call or a method call represented by the given span ends with a
1610/// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1611/// comma from macro can potentially break the code.
1612pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1613    let mut result: bool = Default::default();
1614    let mut prev_char: char = Default::default();
1615    let closing_delimiters = &[')', '}', ']'];
1616
1617    for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1618        match c {
1619            _ if kind.is_comment() || c.is_whitespace() => continue,
1620            c if closing_delimiters.contains(&c) => {
1621                result &= !closing_delimiters.contains(&prev_char);
1622            }
1623            ',' => result = true,
1624            _ => result = false,
1625        }
1626        prev_char = c;
1627    }
1628
1629    result
1630}
1631
1632pub(crate) fn rewrite_paren(
1633    context: &RewriteContext<'_>,
1634    mut subexpr: &ast::Expr,
1635    shape: Shape,
1636    mut span: Span,
1637) -> RewriteResult {
1638    debug!("rewrite_paren, shape: {:?}", shape);
1639
1640    // Extract comments within parens.
1641    let mut pre_span;
1642    let mut post_span;
1643    let mut pre_comment;
1644    let mut post_comment;
1645    let remove_nested_parens = context.config.remove_nested_parens();
1646    loop {
1647        // 1 = "(" or ")"
1648        pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span().lo());
1649        post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1650        pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1651        post_comment = rewrite_missing_comment(post_span, shape, context)?;
1652
1653        // Remove nested parens if there are no comments.
1654        if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1655            if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1656                span = subexpr.span;
1657                subexpr = subsubexpr;
1658                continue;
1659            }
1660        }
1661
1662        break;
1663    }
1664
1665    // 1 = `(` and `)`
1666    let sub_shape = shape.offset_left(1, span)?.sub_width(1, span)?;
1667    let subexpr_str = subexpr.rewrite_result(context, sub_shape)?;
1668    let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1669    if fits_single_line {
1670        Ok(format!("({pre_comment}{subexpr_str}{post_comment})"))
1671    } else {
1672        rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1673    }
1674}
1675
1676fn rewrite_paren_in_multi_line(
1677    context: &RewriteContext<'_>,
1678    subexpr: &ast::Expr,
1679    shape: Shape,
1680    pre_span: Span,
1681    post_span: Span,
1682) -> RewriteResult {
1683    let nested_indent = shape.indent.block_indent(context.config);
1684    let nested_shape = Shape::indented(nested_indent, context.config);
1685    let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1686    let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1687    let subexpr_str = subexpr.rewrite_result(context, nested_shape)?;
1688
1689    let mut result = String::with_capacity(subexpr_str.len() * 2);
1690    result.push('(');
1691    if !pre_comment.is_empty() {
1692        result.push_str(&nested_indent.to_string_with_newline(context.config));
1693        result.push_str(&pre_comment);
1694    }
1695    result.push_str(&nested_indent.to_string_with_newline(context.config));
1696    result.push_str(&subexpr_str);
1697    if !post_comment.is_empty() {
1698        result.push_str(&nested_indent.to_string_with_newline(context.config));
1699        result.push_str(&post_comment);
1700    }
1701    result.push_str(&shape.indent.to_string_with_newline(context.config));
1702    result.push(')');
1703
1704    Ok(result)
1705}
1706
1707fn rewrite_index(
1708    expr: &ast::Expr,
1709    index: &ast::Expr,
1710    context: &RewriteContext<'_>,
1711    shape: Shape,
1712) -> RewriteResult {
1713    let expr_str = expr.rewrite_result(context, shape)?;
1714
1715    let offset = last_line_width(&expr_str) + 1;
1716    let rhs_overhead = shape.rhs_overhead(context.config);
1717    let index_shape = if expr_str.contains('\n') {
1718        Shape::legacy(context.config.max_width(), shape.indent)
1719            .offset_left(offset, index.span())
1720            .and_then(|shape| shape.sub_width(1 + rhs_overhead, index.span()))
1721    } else {
1722        match context.config.indent_style() {
1723            IndentStyle::Block => shape
1724                .offset_left(offset, index.span())
1725                .and_then(|shape| shape.sub_width(1, index.span())),
1726            IndentStyle::Visual => shape
1727                .visual_indent(offset)
1728                .sub_width(offset + 1, index.span()),
1729        }
1730    };
1731    let orig_index_rw = index_shape
1732        .map_err(RewriteError::from)
1733        .and_then(|s| index.rewrite_result(context, s));
1734
1735    // Return if index fits in a single line.
1736    match orig_index_rw {
1737        Ok(ref index_str) if !index_str.contains('\n') => {
1738            return Ok(format!("{expr_str}[{index_str}]"));
1739        }
1740        _ => (),
1741    }
1742
1743    // Try putting index on the next line and see if it fits in a single line.
1744    let indent = shape.indent.block_indent(context.config);
1745    let index_shape = Shape::indented(indent, context.config)
1746        .offset_left(1, index.span())?
1747        .sub_width(1 + rhs_overhead, index.span())?;
1748    let new_index_rw = index.rewrite_result(context, index_shape);
1749    match (orig_index_rw, new_index_rw) {
1750        (_, Ok(ref new_index_str)) if !new_index_str.contains('\n') => Ok(format!(
1751            "{}{}[{}]",
1752            expr_str,
1753            indent.to_string_with_newline(context.config),
1754            new_index_str,
1755        )),
1756        (Err(_), Ok(ref new_index_str)) => Ok(format!(
1757            "{}{}[{}]",
1758            expr_str,
1759            indent.to_string_with_newline(context.config),
1760            new_index_str,
1761        )),
1762        (Ok(ref index_str), _) => Ok(format!("{expr_str}[{index_str}]")),
1763        // When both orig_index_rw and new_index_rw result in errors, we currently propagate the
1764        // error from the second attempt since it is more generous with width constraints.
1765        // This decision is somewhat arbitrary and is open to change.
1766        (Err(_), Err(new_index_rw_err)) => Err(new_index_rw_err),
1767    }
1768}
1769
1770fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1771    !has_base && fields.iter().all(|field| !field.is_shorthand)
1772}
1773
1774fn rewrite_struct_lit<'a>(
1775    context: &RewriteContext<'_>,
1776    path: &ast::Path,
1777    qself: &Option<Box<ast::QSelf>>,
1778    fields: &'a [ast::ExprField],
1779    struct_rest: &ast::StructRest,
1780    attrs: &[ast::Attribute],
1781    span: Span,
1782    shape: Shape,
1783) -> RewriteResult {
1784    debug!("rewrite_struct_lit: shape {:?}", shape);
1785
1786    enum StructLitField<'a> {
1787        Regular(&'a ast::ExprField),
1788        Base(&'a ast::Expr),
1789        Rest(Span),
1790    }
1791
1792    // 2 = " {".len()
1793    let path_shape = shape.sub_width(2, span)?;
1794    let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1795
1796    let has_base_or_rest = match struct_rest {
1797        ast::StructRest::None if fields.is_empty() => return Ok(format!("{path_str} {{}}")),
1798        ast::StructRest::Rest(_) if fields.is_empty() => {
1799            return Ok(format!("{path_str} {{ .. }}"));
1800        }
1801        ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1802        _ => false,
1803    };
1804
1805    // Foo { a: Foo } - indent is +3, width is -5.
1806    let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2, span)?;
1807
1808    let one_line_width = h_shape.map_or(0, |shape| shape.width);
1809    let body_lo = context.snippet_provider.span_after(span, "{");
1810    let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1811        && context.config.struct_field_align_threshold() > 0
1812    {
1813        rewrite_with_alignment(
1814            fields,
1815            context,
1816            v_shape,
1817            mk_sp(body_lo, span.hi()),
1818            one_line_width,
1819        )
1820        .unknown_error()?
1821    } else {
1822        let field_iter = fields.iter().map(StructLitField::Regular).chain(
1823            match struct_rest {
1824                ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1825                ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1826                ast::StructRest::None | ast::StructRest::NoneWithError(_) => None,
1827            }
1828            .into_iter(),
1829        );
1830
1831        let span_lo = |item: &StructLitField<'_>| match *item {
1832            StructLitField::Regular(field) => field.span().lo(),
1833            StructLitField::Base(expr) => {
1834                let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1835                let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1836                let pos = snippet.find_uncommented("..").unwrap();
1837                last_field_hi + BytePos(pos as u32)
1838            }
1839            StructLitField::Rest(span) => span.lo(),
1840        };
1841        let span_hi = |item: &StructLitField<'_>| match *item {
1842            StructLitField::Regular(field) => field.span().hi(),
1843            StructLitField::Base(expr) => expr.span.hi(),
1844            StructLitField::Rest(span) => span.hi(),
1845        };
1846        let rewrite = |item: &StructLitField<'_>| match *item {
1847            StructLitField::Regular(field) => {
1848                // The 1 taken from the v_budget is for the comma.
1849                rewrite_field(context, field, v_shape.sub_width(1, span)?, 0)
1850            }
1851            StructLitField::Base(expr) => {
1852                // 2 = ..
1853                expr.rewrite_result(context, v_shape.offset_left(2, span)?)
1854                    .map(|s| format!("..{}", s))
1855            }
1856            StructLitField::Rest(_) => Ok("..".to_owned()),
1857        };
1858
1859        let items = itemize_list(
1860            context.snippet_provider,
1861            field_iter,
1862            "}",
1863            ",",
1864            span_lo,
1865            span_hi,
1866            rewrite,
1867            body_lo,
1868            span.hi(),
1869            false,
1870        );
1871        let item_vec = items.collect::<Vec<_>>();
1872
1873        let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1874        let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1875
1876        let ends_with_comma = span_ends_with_comma(context, span);
1877        let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1878
1879        let fmt = struct_lit_formatting(
1880            nested_shape,
1881            tactic,
1882            context,
1883            force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1884        );
1885
1886        write_list(&item_vec, &fmt)?
1887    };
1888
1889    let fields_str =
1890        wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1891    Ok(format!("{path_str} {{{fields_str}}}"))
1892
1893    // FIXME if context.config.indent_style() == Visual, but we run out
1894    // of space, we should fall back to BlockIndent.
1895}
1896
1897pub(crate) fn wrap_struct_field(
1898    context: &RewriteContext<'_>,
1899    attrs: &[ast::Attribute],
1900    fields_str: &str,
1901    shape: Shape,
1902    nested_shape: Shape,
1903    one_line_width: usize,
1904) -> RewriteResult {
1905    let should_vertical = context.config.indent_style() == IndentStyle::Block
1906        && (fields_str.contains('\n')
1907            || !context.config.struct_lit_single_line()
1908            || fields_str.len() > one_line_width);
1909
1910    let inner_attrs = &inner_attributes(attrs);
1911    if inner_attrs.is_empty() {
1912        if should_vertical {
1913            Ok(format!(
1914                "{}{}{}",
1915                nested_shape.indent.to_string_with_newline(context.config),
1916                fields_str,
1917                shape.indent.to_string_with_newline(context.config)
1918            ))
1919        } else {
1920            // One liner or visual indent.
1921            Ok(format!(" {fields_str} "))
1922        }
1923    } else {
1924        Ok(format!(
1925            "{}{}{}{}{}",
1926            nested_shape.indent.to_string_with_newline(context.config),
1927            inner_attrs.rewrite_result(context, shape)?,
1928            nested_shape.indent.to_string_with_newline(context.config),
1929            fields_str,
1930            shape.indent.to_string_with_newline(context.config)
1931        ))
1932    }
1933}
1934
1935pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1936    colon_spaces(config)
1937}
1938
1939pub(crate) fn rewrite_field(
1940    context: &RewriteContext<'_>,
1941    field: &ast::ExprField,
1942    shape: Shape,
1943    prefix_max_width: usize,
1944) -> RewriteResult {
1945    if contains_skip(&field.attrs) {
1946        return Ok(context.snippet(field.span()).to_owned());
1947    }
1948    let mut attrs_str = field.attrs.rewrite_result(context, shape)?;
1949    if !attrs_str.is_empty() {
1950        attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1951    };
1952    let name = context.snippet(field.ident.span);
1953    if field.is_shorthand {
1954        Ok(attrs_str + name)
1955    } else {
1956        let mut separator = String::from(struct_lit_field_separator(context.config));
1957        for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1958            separator.push(' ');
1959        }
1960        let overhead = name.len() + separator.len();
1961        let expr_shape = shape.offset_left(overhead, field.span)?;
1962        let expr = field.expr.rewrite_result(context, expr_shape);
1963        let is_lit = matches!(field.expr.kind, ast::ExprKind::Lit(_));
1964        match expr {
1965            Ok(ref e)
1966                if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() =>
1967            {
1968                Ok(attrs_str + name)
1969            }
1970            Ok(e) => Ok(format!("{attrs_str}{name}{separator}{e}")),
1971            Err(_) => {
1972                let expr_offset = shape.indent.block_indent(context.config);
1973                let expr = field
1974                    .expr
1975                    .rewrite_result(context, Shape::indented(expr_offset, context.config));
1976                expr.map(|s| {
1977                    format!(
1978                        "{}{}:\n{}{}",
1979                        attrs_str,
1980                        name,
1981                        expr_offset.to_string(context.config),
1982                        s
1983                    )
1984                })
1985            }
1986        }
1987    }
1988}
1989
1990fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1991    context: &RewriteContext<'_>,
1992    mut items: impl Iterator<Item = &'a T>,
1993    span: Span,
1994    shape: Shape,
1995    is_singleton_tuple: bool,
1996) -> RewriteResult {
1997    // In case of length 1, need a trailing comma
1998    debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1999    if is_singleton_tuple {
2000        // 3 = "(" + ",)"
2001        let nested_shape = shape.sub_width(3, span)?.visual_indent(1);
2002        return items
2003            .next()
2004            .unwrap()
2005            .rewrite_result(context, nested_shape)
2006            .map(|s| format!("({},)", s));
2007    }
2008
2009    let list_lo = context.snippet_provider.span_after(span, "(");
2010    let nested_shape = shape.sub_width(2, span)?.visual_indent(1);
2011    let items = itemize_list(
2012        context.snippet_provider,
2013        items,
2014        ")",
2015        ",",
2016        |item| item.span().lo(),
2017        |item| item.span().hi(),
2018        |item| item.rewrite_result(context, nested_shape),
2019        list_lo,
2020        span.hi() - BytePos(1),
2021        false,
2022    );
2023    let item_vec: Vec<_> = items.collect();
2024    let tactic = definitive_tactic(
2025        &item_vec,
2026        ListTactic::HorizontalVertical,
2027        Separator::Comma,
2028        nested_shape.width,
2029    );
2030    let fmt = ListFormatting::new(nested_shape, context.config)
2031        .tactic(tactic)
2032        .ends_with_newline(false);
2033    let list_str = write_list(&item_vec, &fmt)?;
2034
2035    Ok(format!("({list_str})"))
2036}
2037
2038fn rewrite_let(
2039    context: &RewriteContext<'_>,
2040    shape: Shape,
2041    pat: &ast::Pat,
2042    expr: &ast::Expr,
2043) -> RewriteResult {
2044    let mut result = "let ".to_owned();
2045
2046    // TODO(ytmimi) comments could appear between `let` and the `pat`
2047
2048    // 4 = "let ".len()
2049    let mut pat_shape = shape.offset_left(4, pat.span)?;
2050    if context.config.style_edition() >= StyleEdition::Edition2027 {
2051        // 2 for the length of " ="
2052        pat_shape = pat_shape.sub_width(2, pat.span)?;
2053    }
2054    let pat_str = pat.rewrite_result(context, pat_shape)?;
2055    result.push_str(&pat_str);
2056
2057    // TODO(ytmimi) comments could appear between `pat` and `=`
2058    result.push_str(" =");
2059
2060    let comments_lo = context
2061        .snippet_provider
2062        .span_after(expr.span.with_lo(pat.span.hi()), "=");
2063    let comments_span = mk_sp(comments_lo, expr.span.lo());
2064    rewrite_assign_rhs_with_comments(
2065        context,
2066        result,
2067        expr,
2068        shape,
2069        &RhsAssignKind::Expr(&expr.kind, expr.span),
2070        RhsTactics::Default,
2071        comments_span,
2072        true,
2073    )
2074}
2075
2076pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
2077    context: &'a RewriteContext<'_>,
2078    items: impl Iterator<Item = &'a T>,
2079    span: Span,
2080    shape: Shape,
2081    is_singleton_tuple: bool,
2082) -> RewriteResult {
2083    debug!("rewrite_tuple {:?}", shape);
2084    if context.use_block_indent() {
2085        // We use the same rule as function calls for rewriting tuples.
2086        let force_tactic = if context.inside_macro() {
2087            if span_ends_with_comma(context, span) {
2088                Some(SeparatorTactic::Always)
2089            } else {
2090                Some(SeparatorTactic::Never)
2091            }
2092        } else if is_singleton_tuple {
2093            Some(SeparatorTactic::Always)
2094        } else {
2095            None
2096        };
2097        overflow::rewrite_with_parens(
2098            context,
2099            "",
2100            items,
2101            shape,
2102            span,
2103            context.config.fn_call_width(),
2104            force_tactic,
2105        )
2106    } else {
2107        rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
2108    }
2109}
2110
2111pub(crate) fn rewrite_unary_prefix<R: Rewrite + Spanned>(
2112    context: &RewriteContext<'_>,
2113    prefix: &str,
2114    rewrite: &R,
2115    shape: Shape,
2116) -> RewriteResult {
2117    let shape = shape.offset_left(prefix.len(), rewrite.span())?;
2118    rewrite
2119        .rewrite_result(context, shape)
2120        .map(|r| format!("{}{}", prefix, r))
2121}
2122
2123// FIXME: this is probably not correct for multi-line Rewrites. we should
2124// subtract suffix.len() from the last line budget, not the first!
2125pub(crate) fn rewrite_unary_suffix<R: Rewrite + Spanned>(
2126    context: &RewriteContext<'_>,
2127    suffix: &str,
2128    rewrite: &R,
2129    shape: Shape,
2130) -> RewriteResult {
2131    let shape = shape.sub_width(suffix.len(), rewrite.span())?;
2132    rewrite.rewrite_result(context, shape).map(|mut r| {
2133        r.push_str(suffix);
2134        r
2135    })
2136}
2137
2138fn rewrite_unary_op(
2139    context: &RewriteContext<'_>,
2140    op: ast::UnOp,
2141    expr: &ast::Expr,
2142    shape: Shape,
2143) -> RewriteResult {
2144    // For some reason, an UnOp is not spanned like BinOp!
2145    rewrite_unary_prefix(context, op.as_str(), expr, shape)
2146}
2147
2148pub(crate) enum RhsAssignKind<'ast> {
2149    Expr(&'ast ast::ExprKind, #[allow(dead_code)] Span),
2150    Bounds,
2151    Ty,
2152}
2153
2154impl<'ast> RhsAssignKind<'ast> {
2155    // TODO(calebcartwright)
2156    // Preemptive addition for handling RHS with chains, not yet utilized.
2157    // It may make more sense to construct the chain first and then check
2158    // whether there are actually chain elements.
2159    #[allow(dead_code)]
2160    fn is_chain(&self) -> bool {
2161        match self {
2162            RhsAssignKind::Expr(kind, _) => {
2163                matches!(
2164                    kind,
2165                    ast::ExprKind::Try(..)
2166                        | ast::ExprKind::Field(..)
2167                        | ast::ExprKind::MethodCall(..)
2168                        | ast::ExprKind::Await(_, _)
2169                )
2170            }
2171            _ => false,
2172        }
2173    }
2174}
2175
2176fn rewrite_assignment(
2177    context: &RewriteContext<'_>,
2178    lhs: &ast::Expr,
2179    rhs: &ast::Expr,
2180    op: Option<&ast::AssignOp>,
2181    shape: Shape,
2182) -> RewriteResult {
2183    let operator_str = match op {
2184        Some(op) => context.snippet(op.span),
2185        None => "=",
2186    };
2187
2188    // 1 = space between lhs and operator.
2189    let lhs_shape = shape.sub_width(operator_str.len() + 1, lhs.span())?;
2190    let lhs_str = format!(
2191        "{} {}",
2192        lhs.rewrite_result(context, lhs_shape)?,
2193        operator_str
2194    );
2195
2196    rewrite_assign_rhs(
2197        context,
2198        lhs_str,
2199        rhs,
2200        &RhsAssignKind::Expr(&rhs.kind, rhs.span),
2201        shape,
2202    )
2203}
2204
2205/// Controls where to put the rhs.
2206#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2207pub(crate) enum RhsTactics {
2208    /// Use heuristics.
2209    Default,
2210    /// Put the rhs on the next line if it uses multiple line, without extra indentation.
2211    ForceNextLineWithoutIndent,
2212    /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
2213    /// did not work.
2214    AllowOverflow,
2215}
2216
2217// The left hand side must contain everything up to, and including, the
2218// assignment operator.
2219pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
2220    context: &RewriteContext<'_>,
2221    lhs: S,
2222    ex: &R,
2223    rhs_kind: &RhsAssignKind<'_>,
2224    shape: Shape,
2225) -> RewriteResult {
2226    rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
2227}
2228
2229pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
2230    context: &RewriteContext<'_>,
2231    lhs: &str,
2232    ex: &R,
2233    shape: Shape,
2234    rhs_kind: &RhsAssignKind<'_>,
2235    rhs_tactics: RhsTactics,
2236) -> RewriteResult {
2237    let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
2238        shape.indent.width()
2239    } else {
2240        0
2241    });
2242    // 1 = space between operator and rhs.
2243    let orig_shape = shape.offset_left_opt(last_line_width + 1).unwrap_or(Shape {
2244        width: 0,
2245        offset: shape.offset + last_line_width + 1,
2246        ..shape
2247    });
2248    let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
2249        lhs.trim_end().len() > offset + 1
2250    } else {
2251        false
2252    };
2253
2254    choose_rhs(
2255        context,
2256        ex,
2257        orig_shape,
2258        ex.rewrite_result(context, orig_shape),
2259        rhs_kind,
2260        rhs_tactics,
2261        has_rhs_comment,
2262    )
2263}
2264
2265pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2266    context: &RewriteContext<'_>,
2267    lhs: S,
2268    ex: &R,
2269    shape: Shape,
2270    rhs_kind: &RhsAssignKind<'_>,
2271    rhs_tactics: RhsTactics,
2272) -> RewriteResult {
2273    let lhs = lhs.into();
2274    let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2275    Ok(lhs + &rhs)
2276}
2277
2278pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite + Spanned>(
2279    context: &RewriteContext<'_>,
2280    lhs: S,
2281    ex: &R,
2282    shape: Shape,
2283    rhs_kind: &RhsAssignKind<'_>,
2284    rhs_tactics: RhsTactics,
2285    between_span: Span,
2286    allow_extend: bool,
2287) -> RewriteResult {
2288    let lhs = lhs.into();
2289    let contains_comment = contains_comment(context.snippet(between_span));
2290    let shape = if contains_comment {
2291        shape.block_left(
2292            context.config.tab_spaces(),
2293            between_span.with_hi(ex.span().hi()),
2294        )?
2295    } else {
2296        shape
2297    };
2298    let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2299    if contains_comment {
2300        let rhs = rhs.trim_start();
2301        combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2302    } else {
2303        Ok(lhs + &rhs)
2304    }
2305}
2306
2307fn choose_rhs<R: Rewrite>(
2308    context: &RewriteContext<'_>,
2309    expr: &R,
2310    shape: Shape,
2311    orig_rhs: RewriteResult,
2312    _rhs_kind: &RhsAssignKind<'_>,
2313    rhs_tactics: RhsTactics,
2314    has_rhs_comment: bool,
2315) -> RewriteResult {
2316    match orig_rhs {
2317        Ok(ref new_str) if new_str.is_empty() => Ok(String::new()),
2318        Ok(ref new_str) if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width => {
2319            Ok(format!(" {new_str}"))
2320        }
2321        _ => {
2322            // Expression did not fit on the same line as the identifier.
2323            // Try splitting the line and see if that works better.
2324            let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)
2325                // TODO(ding-young) Ideally, we can replace unknown_error() with max_width_error(),
2326                // but this requires either implementing the Spanned trait for ast::GenericBounds
2327                // or grabbing the span from the call site.
2328                .unknown_error()?;
2329            let new_rhs = expr.rewrite_result(context, new_shape);
2330            let new_indent_str = &shape
2331                .indent
2332                .block_indent(context.config)
2333                .to_string_with_newline(context.config);
2334            let before_space_str = if has_rhs_comment { "" } else { " " };
2335
2336            match (orig_rhs, new_rhs) {
2337                (Ok(ref orig_rhs), Ok(ref new_rhs))
2338                    if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) =>
2339                {
2340                    Ok(format!("{before_space_str}{orig_rhs}"))
2341                }
2342                (Ok(ref orig_rhs), Ok(ref new_rhs))
2343                    if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2344                {
2345                    Ok(format!("{new_indent_str}{new_rhs}"))
2346                }
2347                (Err(_), Ok(ref new_rhs)) => Ok(format!("{new_indent_str}{new_rhs}")),
2348                (Err(_), Err(_)) if rhs_tactics == RhsTactics::AllowOverflow => {
2349                    let shape = shape.infinite_width();
2350                    expr.rewrite_result(context, shape)
2351                        .map(|s| format!("{}{}", before_space_str, s))
2352                }
2353                // When both orig_rhs and new_rhs result in errors, we currently propagate
2354                // the error from the second attempt since it is more generous with
2355                // width constraints. This decision is somewhat arbitrary and is open to change.
2356                (Err(_), Err(new_rhs_err)) => Err(new_rhs_err),
2357                (Ok(orig_rhs), _) => Ok(format!("{before_space_str}{orig_rhs}")),
2358            }
2359        }
2360    }
2361}
2362
2363fn shape_from_rhs_tactic(
2364    context: &RewriteContext<'_>,
2365    shape: Shape,
2366    rhs_tactic: RhsTactics,
2367) -> Option<Shape> {
2368    match rhs_tactic {
2369        RhsTactics::ForceNextLineWithoutIndent => shape
2370            .with_max_width(context.config)
2371            .sub_width_opt(shape.indent.width()),
2372        RhsTactics::Default | RhsTactics::AllowOverflow => {
2373            Shape::indented(shape.indent.block_indent(context.config), context.config)
2374                .sub_width_opt(shape.rhs_overhead(context.config))
2375        }
2376    }
2377}
2378
2379/// Returns true if formatting next_line_rhs is better on a new line when compared to the
2380/// original's line formatting.
2381///
2382/// It is considered better if:
2383/// 1. the tactic is ForceNextLineWithoutIndent
2384/// 2. next_line_rhs doesn't have newlines
2385/// 3. the original line has more newlines than next_line_rhs
2386/// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2387///    doesn't
2388pub(crate) fn prefer_next_line(
2389    orig_rhs: &str,
2390    next_line_rhs: &str,
2391    rhs_tactics: RhsTactics,
2392) -> bool {
2393    rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2394        || !next_line_rhs.contains('\n')
2395        || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2396        || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2397        || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2398        || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2399}
2400
2401fn rewrite_expr_addrof(
2402    context: &RewriteContext<'_>,
2403    borrow_kind: ast::BorrowKind,
2404    mutability: ast::Mutability,
2405    expr: &ast::Expr,
2406    shape: Shape,
2407) -> RewriteResult {
2408    let operator_str = match (mutability, borrow_kind) {
2409        (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2410        (ast::Mutability::Not, ast::BorrowKind::Pin) => "&pin const ",
2411        (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2412        (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2413        (ast::Mutability::Mut, ast::BorrowKind::Pin) => "&pin mut ",
2414        (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2415    };
2416    rewrite_unary_prefix(context, operator_str, expr, shape)
2417}
2418
2419pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2420    match expr.kind {
2421        ast::ExprKind::MethodCall(..) => true,
2422        ast::ExprKind::AddrOf(_, _, ref expr)
2423        | ast::ExprKind::Cast(ref expr, _)
2424        | ast::ExprKind::Try(ref expr)
2425        | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2426        _ => false,
2427    }
2428}
2429
2430/// Indicates the parts of a float literal specified as a string.
2431struct FloatSymbolParts<'a> {
2432    /// The integer part, e.g. `123` in `123.456e789`.
2433    /// Always non-empty, because in Rust `.1` is not a valid floating-point literal:
2434    /// <https://doc.rust-lang.org/reference/tokens.html#floating-point-literals>
2435    integer_part: &'a str,
2436    /// The fractional part excluding the decimal point, e.g. `456` in `123.456e789`.
2437    fractional_part: Option<&'a str>,
2438    /// The exponent part including the `e` or `E`, e.g. `e789` in `123.456e789`.
2439    exponent: Option<&'a str>,
2440}
2441
2442impl FloatSymbolParts<'_> {
2443    fn is_fractional_part_zero(&self) -> bool {
2444        let zero_literal_regex = static_regex!(r"^[0_]+$");
2445        self.fractional_part
2446            .is_none_or(|s| zero_literal_regex.is_match(s))
2447    }
2448}
2449
2450/// Parses a float literal. The `symbol` must be a valid floating point literal without a type
2451/// suffix. Otherwise the function may panic or return wrong result.
2452fn parse_float_symbol(symbol: &str) -> Result<FloatSymbolParts<'_>, &'static str> {
2453    // This regex may accept invalid float literals (such as `1`, `_` or `2.e3`). That's ok.
2454    // We only use it to parse literals whose validity has already been established.
2455    let float_literal_regex = static_regex!(r"^([0-9_]+)(?:\.([0-9_]+)?)?([eE][+-]?[0-9_]+)?$");
2456    let caps = float_literal_regex
2457        .captures(symbol)
2458        .ok_or("invalid float literal")?;
2459    Ok(FloatSymbolParts {
2460        integer_part: caps.get(1).ok_or("missing integer part")?.as_str(),
2461        fractional_part: caps.get(2).map(|m| m.as_str()),
2462        exponent: caps.get(3).map(|m| m.as_str()),
2463    })
2464}
2465
2466#[cfg(test)]
2467mod test {
2468    use super::*;
2469
2470    #[test]
2471    fn test_last_line_offsetted() {
2472        let lines = "one\n    two";
2473        assert_eq!(last_line_offsetted(2, lines), true);
2474        assert_eq!(last_line_offsetted(4, lines), false);
2475        assert_eq!(last_line_offsetted(6, lines), false);
2476
2477        let lines = "one    two";
2478        assert_eq!(last_line_offsetted(2, lines), false);
2479        assert_eq!(last_line_offsetted(0, lines), false);
2480
2481        let lines = "\ntwo";
2482        assert_eq!(last_line_offsetted(2, lines), false);
2483        assert_eq!(last_line_offsetted(0, lines), false);
2484
2485        let lines = "one\n    two      three";
2486        assert_eq!(last_line_offsetted(2, lines), true);
2487        let lines = "one\n two      three";
2488        assert_eq!(last_line_offsetted(2, lines), false);
2489    }
2490
2491    #[test]
2492    fn test_parse_float_symbol() {
2493        let parts = parse_float_symbol("123.456e789").unwrap();
2494        assert_eq!(parts.integer_part, "123");
2495        assert_eq!(parts.fractional_part, Some("456"));
2496        assert_eq!(parts.exponent, Some("e789"));
2497
2498        let parts = parse_float_symbol("123.456e+789").unwrap();
2499        assert_eq!(parts.integer_part, "123");
2500        assert_eq!(parts.fractional_part, Some("456"));
2501        assert_eq!(parts.exponent, Some("e+789"));
2502
2503        let parts = parse_float_symbol("123.456e-789").unwrap();
2504        assert_eq!(parts.integer_part, "123");
2505        assert_eq!(parts.fractional_part, Some("456"));
2506        assert_eq!(parts.exponent, Some("e-789"));
2507
2508        let parts = parse_float_symbol("123e789").unwrap();
2509        assert_eq!(parts.integer_part, "123");
2510        assert_eq!(parts.fractional_part, None);
2511        assert_eq!(parts.exponent, Some("e789"));
2512
2513        let parts = parse_float_symbol("123E789").unwrap();
2514        assert_eq!(parts.integer_part, "123");
2515        assert_eq!(parts.fractional_part, None);
2516        assert_eq!(parts.exponent, Some("E789"));
2517
2518        let parts = parse_float_symbol("123.").unwrap();
2519        assert_eq!(parts.integer_part, "123");
2520        assert_eq!(parts.fractional_part, None);
2521        assert_eq!(parts.exponent, None);
2522    }
2523
2524    #[test]
2525    fn test_parse_float_symbol_with_underscores() {
2526        let parts = parse_float_symbol("_123._456e_789").unwrap();
2527        assert_eq!(parts.integer_part, "_123");
2528        assert_eq!(parts.fractional_part, Some("_456"));
2529        assert_eq!(parts.exponent, Some("e_789"));
2530
2531        let parts = parse_float_symbol("123_.456_e789_").unwrap();
2532        assert_eq!(parts.integer_part, "123_");
2533        assert_eq!(parts.fractional_part, Some("456_"));
2534        assert_eq!(parts.exponent, Some("e789_"));
2535
2536        let parts = parse_float_symbol("1_23.4_56e7_89").unwrap();
2537        assert_eq!(parts.integer_part, "1_23");
2538        assert_eq!(parts.fractional_part, Some("4_56"));
2539        assert_eq!(parts.exponent, Some("e7_89"));
2540
2541        let parts = parse_float_symbol("_1_23_._4_56_e_7_89_").unwrap();
2542        assert_eq!(parts.integer_part, "_1_23_");
2543        assert_eq!(parts.fractional_part, Some("_4_56_"));
2544        assert_eq!(parts.exponent, Some("e_7_89_"));
2545    }
2546
2547    #[test]
2548    fn test_float_lit_ends_in_dot() {
2549        type TZ = FloatLiteralTrailingZero;
2550
2551        assert!(float_lit_ends_in_dot("1.", None, TZ::Preserve));
2552        assert!(!float_lit_ends_in_dot("1.0", None, TZ::Preserve));
2553        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Preserve));
2554        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Preserve));
2555        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Preserve));
2556        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Preserve));
2557
2558        assert!(!float_lit_ends_in_dot("1.", None, TZ::Always));
2559        assert!(!float_lit_ends_in_dot("1.0", None, TZ::Always));
2560        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Always));
2561        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Always));
2562        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Always));
2563        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Always));
2564
2565        assert!(!float_lit_ends_in_dot("1.", None, TZ::IfNoPostfix));
2566        assert!(!float_lit_ends_in_dot("1.0", None, TZ::IfNoPostfix));
2567        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::IfNoPostfix));
2568        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::IfNoPostfix));
2569        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::IfNoPostfix));
2570        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::IfNoPostfix));
2571
2572        assert!(float_lit_ends_in_dot("1.", None, TZ::Never));
2573        assert!(float_lit_ends_in_dot("1.0", None, TZ::Never));
2574        assert!(!float_lit_ends_in_dot("1.e2", None, TZ::Never));
2575        assert!(!float_lit_ends_in_dot("1.0e2", None, TZ::Never));
2576        assert!(!float_lit_ends_in_dot("1.", Some("f32"), TZ::Never));
2577        assert!(!float_lit_ends_in_dot("1.0", Some("f32"), TZ::Never));
2578    }
2579}