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