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