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