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