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