]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/expr.rs
Auto merge of #102944 - nnethercote:ast-Lit-third-time-lucky, 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, token};
7 use rustc_span::{BytePos, Span};
8
9 use crate::chains::rewrite_chain;
10 use crate::closures;
11 use crate::comment::{
12     combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
13     rewrite_missing_comment, CharClasses, FindUncommented,
14 };
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version};
17 use crate::lists::{
18     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19     struct_lit_tactic, write_list, ListFormatting, Separator,
20 };
21 use crate::macros::{rewrite_macro, MacroPosition};
22 use crate::matches::rewrite_match;
23 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
24 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::string::{rewrite_string, StringFormat};
30 use crate::types::{rewrite_path, PathContext};
31 use crate::utils::{
32     colon_spaces, contains_skip, count_newlines, 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(token_lit) => {
79             if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
80                 Some(expr_rw)
81             } else {
82                 if let LitKind::StrRaw(_) = token_lit.kind {
83                     Some(context.snippet(expr.span).trim().into())
84                 } else {
85                     None
86                 }
87             }
88         }
89         ast::ExprKind::Call(ref callee, ref args) => {
90             let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
91             let callee_str = callee.rewrite(context, shape)?;
92             rewrite_call(context, &callee_str, args, inner_span, shape)
93         }
94         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
95         ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
96             // FIXME: format comments between operands and operator
97             rewrite_all_pairs(expr, shape, context).or_else(|| {
98                 rewrite_pair(
99                     &**lhs,
100                     &**rhs,
101                     PairParts::infix(&format!(" {} ", context.snippet(op.span))),
102                     context,
103                     shape,
104                     context.config.binop_separator(),
105                 )
106             })
107         }
108         ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
109         ast::ExprKind::Struct(ref struct_expr) => {
110             let ast::StructExpr {
111                 qself,
112                 fields,
113                 path,
114                 rest,
115             } = &**struct_expr;
116             rewrite_struct_lit(
117                 context,
118                 path,
119                 qself.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(token_lit) => match token_lit.kind {
278                         token::LitKind::Float if token_lit.suffix.is_none() => {
279                             context.snippet(lhs.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     token_lit: token::Lit,
1189     span: Span,
1190     shape: Shape,
1191 ) -> Option<String> {
1192     match token_lit.kind {
1193         token::LitKind::Str => rewrite_string_lit(context, span, shape),
1194         token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape),
1195         _ => wrap_str(
1196             context.snippet(span).to_owned(),
1197             context.config.max_width(),
1198             shape,
1199         ),
1200     }
1201 }
1202
1203 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1204     let string_lit = context.snippet(span);
1205
1206     if !context.config.format_strings() {
1207         if string_lit
1208             .lines()
1209             .dropping_back(1)
1210             .all(|line| line.ends_with('\\'))
1211             && context.config.version() == Version::Two
1212         {
1213             return Some(string_lit.to_owned());
1214         } else {
1215             return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1216         }
1217     }
1218
1219     // Remove the quote characters.
1220     let str_lit = &string_lit[1..string_lit.len() - 1];
1221
1222     rewrite_string(
1223         str_lit,
1224         &StringFormat::new(shape.visual_indent(0), context.config),
1225         shape.width.saturating_sub(2),
1226     )
1227 }
1228
1229 fn rewrite_int_lit(
1230     context: &RewriteContext<'_>,
1231     token_lit: token::Lit,
1232     span: Span,
1233     shape: Shape,
1234 ) -> Option<String> {
1235     let symbol = token_lit.symbol.as_str();
1236
1237     if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1238         let hex_lit = match context.config.hex_literal_case() {
1239             HexLiteralCase::Preserve => None,
1240             HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1241             HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1242         };
1243         if let Some(hex_lit) = hex_lit {
1244             return wrap_str(
1245                 format!(
1246                     "0x{}{}",
1247                     hex_lit,
1248                     token_lit.suffix.map_or(String::new(), |s| s.to_string())
1249                 ),
1250                 context.config.max_width(),
1251                 shape,
1252             );
1253         }
1254     }
1255
1256     wrap_str(
1257         context.snippet(span).to_owned(),
1258         context.config.max_width(),
1259         shape,
1260     )
1261 }
1262
1263 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1264     if context.inside_macro() {
1265         if span_ends_with_comma(context, span) {
1266             Some(SeparatorTactic::Always)
1267         } else {
1268             Some(SeparatorTactic::Never)
1269         }
1270     } else {
1271         None
1272     }
1273 }
1274
1275 pub(crate) fn rewrite_call(
1276     context: &RewriteContext<'_>,
1277     callee: &str,
1278     args: &[ptr::P<ast::Expr>],
1279     span: Span,
1280     shape: Shape,
1281 ) -> Option<String> {
1282     overflow::rewrite_with_parens(
1283         context,
1284         callee,
1285         args.iter(),
1286         shape,
1287         span,
1288         context.config.fn_call_width(),
1289         choose_separator_tactic(context, span),
1290     )
1291 }
1292
1293 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1294     match expr.kind {
1295         ast::ExprKind::Lit(..) => true,
1296         ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1297         ast::ExprKind::AddrOf(_, _, ref expr)
1298         | ast::ExprKind::Box(ref expr)
1299         | ast::ExprKind::Cast(ref expr, _)
1300         | ast::ExprKind::Field(ref expr, _)
1301         | ast::ExprKind::Try(ref expr)
1302         | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1303         ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1304         ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1305             is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1306         }
1307         _ => false,
1308     }
1309 }
1310
1311 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1312     lists.iter().all(OverflowableItem::is_simple)
1313 }
1314
1315 pub(crate) fn can_be_overflowed_expr(
1316     context: &RewriteContext<'_>,
1317     expr: &ast::Expr,
1318     args_len: usize,
1319 ) -> bool {
1320     match expr.kind {
1321         _ if !expr.attrs.is_empty() => false,
1322         ast::ExprKind::Match(..) => {
1323             (context.use_block_indent() && args_len == 1)
1324                 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1325                 || context.config.overflow_delimited_expr()
1326         }
1327         ast::ExprKind::If(..)
1328         | ast::ExprKind::ForLoop(..)
1329         | ast::ExprKind::Loop(..)
1330         | ast::ExprKind::While(..) => {
1331             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1332         }
1333
1334         // Handle always block-like expressions
1335         ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1336
1337         // Handle `[]` and `{}`-like expressions
1338         ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1339             context.config.overflow_delimited_expr()
1340                 || (context.use_block_indent() && args_len == 1)
1341         }
1342         ast::ExprKind::MacCall(ref mac) => {
1343             match (
1344                 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim().unwrap()),
1345                 context.config.overflow_delimited_expr(),
1346             ) {
1347                 (Some(ast::MacDelimiter::Bracket), true)
1348                 | (Some(ast::MacDelimiter::Brace), true) => true,
1349                 _ => context.use_block_indent() && args_len == 1,
1350             }
1351         }
1352
1353         // Handle parenthetical expressions
1354         ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1355             context.use_block_indent() && args_len == 1
1356         }
1357
1358         // Handle unary-like expressions
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, _) => can_be_overflowed_expr(context, expr, args_len),
1364         _ => false,
1365     }
1366 }
1367
1368 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1369     match expr.kind {
1370         ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1371         ast::ExprKind::AddrOf(_, _, ref expr)
1372         | ast::ExprKind::Box(ref expr)
1373         | ast::ExprKind::Try(ref expr)
1374         | ast::ExprKind::Unary(_, ref expr)
1375         | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1376         _ => false,
1377     }
1378 }
1379
1380 /// Returns `true` if a function call or a method call represented by the given span ends with a
1381 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1382 /// comma from macro can potentially break the code.
1383 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1384     let mut result: bool = Default::default();
1385     let mut prev_char: char = Default::default();
1386     let closing_delimiters = &[')', '}', ']'];
1387
1388     for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1389         match c {
1390             _ if kind.is_comment() || c.is_whitespace() => continue,
1391             c if closing_delimiters.contains(&c) => {
1392                 result &= !closing_delimiters.contains(&prev_char);
1393             }
1394             ',' => result = true,
1395             _ => result = false,
1396         }
1397         prev_char = c;
1398     }
1399
1400     result
1401 }
1402
1403 fn rewrite_paren(
1404     context: &RewriteContext<'_>,
1405     mut subexpr: &ast::Expr,
1406     shape: Shape,
1407     mut span: Span,
1408 ) -> Option<String> {
1409     debug!("rewrite_paren, shape: {:?}", shape);
1410
1411     // Extract comments within parens.
1412     let mut pre_span;
1413     let mut post_span;
1414     let mut pre_comment;
1415     let mut post_comment;
1416     let remove_nested_parens = context.config.remove_nested_parens();
1417     loop {
1418         // 1 = "(" or ")"
1419         pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1420         post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1421         pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1422         post_comment = rewrite_missing_comment(post_span, shape, context)?;
1423
1424         // Remove nested parens if there are no comments.
1425         if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1426             if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1427                 span = subexpr.span;
1428                 subexpr = subsubexpr;
1429                 continue;
1430             }
1431         }
1432
1433         break;
1434     }
1435
1436     // 1 = `(` and `)`
1437     let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1438     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1439     let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1440     if fits_single_line {
1441         Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1442     } else {
1443         rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1444     }
1445 }
1446
1447 fn rewrite_paren_in_multi_line(
1448     context: &RewriteContext<'_>,
1449     subexpr: &ast::Expr,
1450     shape: Shape,
1451     pre_span: Span,
1452     post_span: Span,
1453 ) -> Option<String> {
1454     let nested_indent = shape.indent.block_indent(context.config);
1455     let nested_shape = Shape::indented(nested_indent, context.config);
1456     let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1457     let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1458     let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1459
1460     let mut result = String::with_capacity(subexpr_str.len() * 2);
1461     result.push('(');
1462     if !pre_comment.is_empty() {
1463         result.push_str(&nested_indent.to_string_with_newline(context.config));
1464         result.push_str(&pre_comment);
1465     }
1466     result.push_str(&nested_indent.to_string_with_newline(context.config));
1467     result.push_str(&subexpr_str);
1468     if !post_comment.is_empty() {
1469         result.push_str(&nested_indent.to_string_with_newline(context.config));
1470         result.push_str(&post_comment);
1471     }
1472     result.push_str(&shape.indent.to_string_with_newline(context.config));
1473     result.push(')');
1474
1475     Some(result)
1476 }
1477
1478 fn rewrite_index(
1479     expr: &ast::Expr,
1480     index: &ast::Expr,
1481     context: &RewriteContext<'_>,
1482     shape: Shape,
1483 ) -> Option<String> {
1484     let expr_str = expr.rewrite(context, shape)?;
1485
1486     let offset = last_line_width(&expr_str) + 1;
1487     let rhs_overhead = shape.rhs_overhead(context.config);
1488     let index_shape = if expr_str.contains('\n') {
1489         Shape::legacy(context.config.max_width(), shape.indent)
1490             .offset_left(offset)
1491             .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1492     } else {
1493         match context.config.indent_style() {
1494             IndentStyle::Block => shape
1495                 .offset_left(offset)
1496                 .and_then(|shape| shape.sub_width(1)),
1497             IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1498         }
1499     };
1500     let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1501
1502     // Return if index fits in a single line.
1503     match orig_index_rw {
1504         Some(ref index_str) if !index_str.contains('\n') => {
1505             return Some(format!("{}[{}]", expr_str, index_str));
1506         }
1507         _ => (),
1508     }
1509
1510     // Try putting index on the next line and see if it fits in a single line.
1511     let indent = shape.indent.block_indent(context.config);
1512     let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1513     let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1514     let new_index_rw = index.rewrite(context, index_shape);
1515     match (orig_index_rw, new_index_rw) {
1516         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1517             "{}{}[{}]",
1518             expr_str,
1519             indent.to_string_with_newline(context.config),
1520             new_index_str,
1521         )),
1522         (None, Some(ref new_index_str)) => Some(format!(
1523             "{}{}[{}]",
1524             expr_str,
1525             indent.to_string_with_newline(context.config),
1526             new_index_str,
1527         )),
1528         (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1529         _ => None,
1530     }
1531 }
1532
1533 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1534     !has_base && fields.iter().all(|field| !field.is_shorthand)
1535 }
1536
1537 fn rewrite_struct_lit<'a>(
1538     context: &RewriteContext<'_>,
1539     path: &ast::Path,
1540     qself: Option<&ast::QSelf>,
1541     fields: &'a [ast::ExprField],
1542     struct_rest: &ast::StructRest,
1543     attrs: &[ast::Attribute],
1544     span: Span,
1545     shape: Shape,
1546 ) -> Option<String> {
1547     debug!("rewrite_struct_lit: shape {:?}", shape);
1548
1549     enum StructLitField<'a> {
1550         Regular(&'a ast::ExprField),
1551         Base(&'a ast::Expr),
1552         Rest(Span),
1553     }
1554
1555     // 2 = " {".len()
1556     let path_shape = shape.sub_width(2)?;
1557     let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1558
1559     let has_base_or_rest = match struct_rest {
1560         ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1561         ast::StructRest::Rest(_) if fields.is_empty() => {
1562             return Some(format!("{} {{ .. }}", path_str));
1563         }
1564         ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1565         _ => false,
1566     };
1567
1568     // Foo { a: Foo } - indent is +3, width is -5.
1569     let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1570
1571     let one_line_width = h_shape.map_or(0, |shape| shape.width);
1572     let body_lo = context.snippet_provider.span_after(span, "{");
1573     let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1574         && context.config.struct_field_align_threshold() > 0
1575     {
1576         rewrite_with_alignment(
1577             fields,
1578             context,
1579             v_shape,
1580             mk_sp(body_lo, span.hi()),
1581             one_line_width,
1582         )?
1583     } else {
1584         let field_iter = fields.iter().map(StructLitField::Regular).chain(
1585             match struct_rest {
1586                 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1587                 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1588                 ast::StructRest::None => None,
1589             }
1590             .into_iter(),
1591         );
1592
1593         let span_lo = |item: &StructLitField<'_>| match *item {
1594             StructLitField::Regular(field) => field.span().lo(),
1595             StructLitField::Base(expr) => {
1596                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1597                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1598                 let pos = snippet.find_uncommented("..").unwrap();
1599                 last_field_hi + BytePos(pos as u32)
1600             }
1601             StructLitField::Rest(span) => span.lo(),
1602         };
1603         let span_hi = |item: &StructLitField<'_>| match *item {
1604             StructLitField::Regular(field) => field.span().hi(),
1605             StructLitField::Base(expr) => expr.span.hi(),
1606             StructLitField::Rest(span) => span.hi(),
1607         };
1608         let rewrite = |item: &StructLitField<'_>| match *item {
1609             StructLitField::Regular(field) => {
1610                 // The 1 taken from the v_budget is for the comma.
1611                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1612             }
1613             StructLitField::Base(expr) => {
1614                 // 2 = ..
1615                 expr.rewrite(context, v_shape.offset_left(2)?)
1616                     .map(|s| format!("..{}", s))
1617             }
1618             StructLitField::Rest(_) => Some("..".to_owned()),
1619         };
1620
1621         let items = itemize_list(
1622             context.snippet_provider,
1623             field_iter,
1624             "}",
1625             ",",
1626             span_lo,
1627             span_hi,
1628             rewrite,
1629             body_lo,
1630             span.hi(),
1631             false,
1632         );
1633         let item_vec = items.collect::<Vec<_>>();
1634
1635         let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1636         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1637
1638         let ends_with_comma = span_ends_with_comma(context, span);
1639         let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1640
1641         let fmt = struct_lit_formatting(
1642             nested_shape,
1643             tactic,
1644             context,
1645             force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1646         );
1647
1648         write_list(&item_vec, &fmt)?
1649     };
1650
1651     let fields_str =
1652         wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1653     Some(format!("{} {{{}}}", path_str, fields_str))
1654
1655     // FIXME if context.config.indent_style() == Visual, but we run out
1656     // of space, we should fall back to BlockIndent.
1657 }
1658
1659 pub(crate) fn wrap_struct_field(
1660     context: &RewriteContext<'_>,
1661     attrs: &[ast::Attribute],
1662     fields_str: &str,
1663     shape: Shape,
1664     nested_shape: Shape,
1665     one_line_width: usize,
1666 ) -> Option<String> {
1667     let should_vertical = context.config.indent_style() == IndentStyle::Block
1668         && (fields_str.contains('\n')
1669             || !context.config.struct_lit_single_line()
1670             || fields_str.len() > one_line_width);
1671
1672     let inner_attrs = &inner_attributes(attrs);
1673     if inner_attrs.is_empty() {
1674         if should_vertical {
1675             Some(format!(
1676                 "{}{}{}",
1677                 nested_shape.indent.to_string_with_newline(context.config),
1678                 fields_str,
1679                 shape.indent.to_string_with_newline(context.config)
1680             ))
1681         } else {
1682             // One liner or visual indent.
1683             Some(format!(" {} ", fields_str))
1684         }
1685     } else {
1686         Some(format!(
1687             "{}{}{}{}{}",
1688             nested_shape.indent.to_string_with_newline(context.config),
1689             inner_attrs.rewrite(context, shape)?,
1690             nested_shape.indent.to_string_with_newline(context.config),
1691             fields_str,
1692             shape.indent.to_string_with_newline(context.config)
1693         ))
1694     }
1695 }
1696
1697 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1698     colon_spaces(config)
1699 }
1700
1701 pub(crate) fn rewrite_field(
1702     context: &RewriteContext<'_>,
1703     field: &ast::ExprField,
1704     shape: Shape,
1705     prefix_max_width: usize,
1706 ) -> Option<String> {
1707     if contains_skip(&field.attrs) {
1708         return Some(context.snippet(field.span()).to_owned());
1709     }
1710     let mut attrs_str = field.attrs.rewrite(context, shape)?;
1711     if !attrs_str.is_empty() {
1712         attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1713     };
1714     let name = context.snippet(field.ident.span);
1715     if field.is_shorthand {
1716         Some(attrs_str + name)
1717     } else {
1718         let mut separator = String::from(struct_lit_field_separator(context.config));
1719         for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1720             separator.push(' ');
1721         }
1722         let overhead = name.len() + separator.len();
1723         let expr_shape = shape.offset_left(overhead)?;
1724         let expr = field.expr.rewrite(context, expr_shape);
1725
1726         match expr {
1727             Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1728                 Some(attrs_str + name)
1729             }
1730             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1731             None => {
1732                 let expr_offset = shape.indent.block_indent(context.config);
1733                 let expr = field
1734                     .expr
1735                     .rewrite(context, Shape::indented(expr_offset, context.config));
1736                 expr.map(|s| {
1737                     format!(
1738                         "{}{}:\n{}{}",
1739                         attrs_str,
1740                         name,
1741                         expr_offset.to_string(context.config),
1742                         s
1743                     )
1744                 })
1745             }
1746         }
1747     }
1748 }
1749
1750 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1751     context: &RewriteContext<'_>,
1752     mut items: impl Iterator<Item = &'a T>,
1753     span: Span,
1754     shape: Shape,
1755     is_singleton_tuple: bool,
1756 ) -> Option<String> {
1757     // In case of length 1, need a trailing comma
1758     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1759     if is_singleton_tuple {
1760         // 3 = "(" + ",)"
1761         let nested_shape = shape.sub_width(3)?.visual_indent(1);
1762         return items
1763             .next()
1764             .unwrap()
1765             .rewrite(context, nested_shape)
1766             .map(|s| format!("({},)", s));
1767     }
1768
1769     let list_lo = context.snippet_provider.span_after(span, "(");
1770     let nested_shape = shape.sub_width(2)?.visual_indent(1);
1771     let items = itemize_list(
1772         context.snippet_provider,
1773         items,
1774         ")",
1775         ",",
1776         |item| item.span().lo(),
1777         |item| item.span().hi(),
1778         |item| item.rewrite(context, nested_shape),
1779         list_lo,
1780         span.hi() - BytePos(1),
1781         false,
1782     );
1783     let item_vec: Vec<_> = items.collect();
1784     let tactic = definitive_tactic(
1785         &item_vec,
1786         ListTactic::HorizontalVertical,
1787         Separator::Comma,
1788         nested_shape.width,
1789     );
1790     let fmt = ListFormatting::new(nested_shape, context.config)
1791         .tactic(tactic)
1792         .ends_with_newline(false);
1793     let list_str = write_list(&item_vec, &fmt)?;
1794
1795     Some(format!("({})", list_str))
1796 }
1797
1798 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1799     context: &'a RewriteContext<'_>,
1800     items: impl Iterator<Item = &'a T>,
1801     span: Span,
1802     shape: Shape,
1803     is_singleton_tuple: bool,
1804 ) -> Option<String> {
1805     debug!("rewrite_tuple {:?}", shape);
1806     if context.use_block_indent() {
1807         // We use the same rule as function calls for rewriting tuples.
1808         let force_tactic = if context.inside_macro() {
1809             if span_ends_with_comma(context, span) {
1810                 Some(SeparatorTactic::Always)
1811             } else {
1812                 Some(SeparatorTactic::Never)
1813             }
1814         } else if is_singleton_tuple {
1815             Some(SeparatorTactic::Always)
1816         } else {
1817             None
1818         };
1819         overflow::rewrite_with_parens(
1820             context,
1821             "",
1822             items,
1823             shape,
1824             span,
1825             context.config.fn_call_width(),
1826             force_tactic,
1827         )
1828     } else {
1829         rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1830     }
1831 }
1832
1833 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1834     context: &RewriteContext<'_>,
1835     prefix: &str,
1836     rewrite: &R,
1837     shape: Shape,
1838 ) -> Option<String> {
1839     rewrite
1840         .rewrite(context, shape.offset_left(prefix.len())?)
1841         .map(|r| format!("{}{}", prefix, r))
1842 }
1843
1844 // FIXME: this is probably not correct for multi-line Rewrites. we should
1845 // subtract suffix.len() from the last line budget, not the first!
1846 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1847     context: &RewriteContext<'_>,
1848     suffix: &str,
1849     rewrite: &R,
1850     shape: Shape,
1851 ) -> Option<String> {
1852     rewrite
1853         .rewrite(context, shape.sub_width(suffix.len())?)
1854         .map(|mut r| {
1855             r.push_str(suffix);
1856             r
1857         })
1858 }
1859
1860 fn rewrite_unary_op(
1861     context: &RewriteContext<'_>,
1862     op: ast::UnOp,
1863     expr: &ast::Expr,
1864     shape: Shape,
1865 ) -> Option<String> {
1866     // For some reason, an UnOp is not spanned like BinOp!
1867     rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1868 }
1869
1870 pub(crate) enum RhsAssignKind<'ast> {
1871     Expr(&'ast ast::ExprKind, Span),
1872     Bounds,
1873     Ty,
1874 }
1875
1876 impl<'ast> RhsAssignKind<'ast> {
1877     // TODO(calebcartwright)
1878     // Preemptive addition for handling RHS with chains, not yet utilized.
1879     // It may make more sense to construct the chain first and then check
1880     // whether there are actually chain elements.
1881     #[allow(dead_code)]
1882     fn is_chain(&self) -> bool {
1883         match self {
1884             RhsAssignKind::Expr(kind, _) => {
1885                 matches!(
1886                     kind,
1887                     ast::ExprKind::Try(..)
1888                         | ast::ExprKind::Field(..)
1889                         | ast::ExprKind::MethodCall(..)
1890                         | ast::ExprKind::Await(_)
1891                 )
1892             }
1893             _ => false,
1894         }
1895     }
1896 }
1897
1898 fn rewrite_assignment(
1899     context: &RewriteContext<'_>,
1900     lhs: &ast::Expr,
1901     rhs: &ast::Expr,
1902     op: Option<&ast::BinOp>,
1903     shape: Shape,
1904 ) -> Option<String> {
1905     let operator_str = match op {
1906         Some(op) => context.snippet(op.span),
1907         None => "=",
1908     };
1909
1910     // 1 = space between lhs and operator.
1911     let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1912     let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1913
1914     rewrite_assign_rhs(
1915         context,
1916         lhs_str,
1917         rhs,
1918         &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1919         shape,
1920     )
1921 }
1922
1923 /// Controls where to put the rhs.
1924 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1925 pub(crate) enum RhsTactics {
1926     /// Use heuristics.
1927     Default,
1928     /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1929     ForceNextLineWithoutIndent,
1930     /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1931     /// did not work.
1932     AllowOverflow,
1933 }
1934
1935 // The left hand side must contain everything up to, and including, the
1936 // assignment operator.
1937 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1938     context: &RewriteContext<'_>,
1939     lhs: S,
1940     ex: &R,
1941     rhs_kind: &RhsAssignKind<'_>,
1942     shape: Shape,
1943 ) -> Option<String> {
1944     rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1945 }
1946
1947 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1948     context: &RewriteContext<'_>,
1949     lhs: &str,
1950     ex: &R,
1951     shape: Shape,
1952     rhs_kind: &RhsAssignKind<'_>,
1953     rhs_tactics: RhsTactics,
1954 ) -> Option<String> {
1955     let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1956         shape.indent.width()
1957     } else {
1958         0
1959     });
1960     // 1 = space between operator and rhs.
1961     let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1962         width: 0,
1963         offset: shape.offset + last_line_width + 1,
1964         ..shape
1965     });
1966     let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1967         lhs.trim_end().len() > offset + 1
1968     } else {
1969         false
1970     };
1971
1972     choose_rhs(
1973         context,
1974         ex,
1975         orig_shape,
1976         ex.rewrite(context, orig_shape),
1977         rhs_kind,
1978         rhs_tactics,
1979         has_rhs_comment,
1980     )
1981 }
1982
1983 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1984     context: &RewriteContext<'_>,
1985     lhs: S,
1986     ex: &R,
1987     shape: Shape,
1988     rhs_kind: &RhsAssignKind<'_>,
1989     rhs_tactics: RhsTactics,
1990 ) -> Option<String> {
1991     let lhs = lhs.into();
1992     let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
1993     Some(lhs + &rhs)
1994 }
1995
1996 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1997     context: &RewriteContext<'_>,
1998     lhs: S,
1999     ex: &R,
2000     shape: Shape,
2001     rhs_kind: &RhsAssignKind<'_>,
2002     rhs_tactics: RhsTactics,
2003     between_span: Span,
2004     allow_extend: bool,
2005 ) -> Option<String> {
2006     let lhs = lhs.into();
2007     let contains_comment = contains_comment(context.snippet(between_span));
2008     let shape = if contains_comment {
2009         shape.block_left(context.config.tab_spaces())?
2010     } else {
2011         shape
2012     };
2013     let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2014
2015     if contains_comment {
2016         let rhs = rhs.trim_start();
2017         combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2018     } else {
2019         Some(lhs + &rhs)
2020     }
2021 }
2022
2023 fn choose_rhs<R: Rewrite>(
2024     context: &RewriteContext<'_>,
2025     expr: &R,
2026     shape: Shape,
2027     orig_rhs: Option<String>,
2028     _rhs_kind: &RhsAssignKind<'_>,
2029     rhs_tactics: RhsTactics,
2030     has_rhs_comment: bool,
2031 ) -> Option<String> {
2032     match orig_rhs {
2033         Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2034         Some(ref new_str)
2035             if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2036         {
2037             Some(format!(" {}", new_str))
2038         }
2039         _ => {
2040             // Expression did not fit on the same line as the identifier.
2041             // Try splitting the line and see if that works better.
2042             let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2043             let new_rhs = expr.rewrite(context, new_shape);
2044             let new_indent_str = &shape
2045                 .indent
2046                 .block_indent(context.config)
2047                 .to_string_with_newline(context.config);
2048             let before_space_str = if has_rhs_comment { "" } else { " " };
2049
2050             match (orig_rhs, new_rhs) {
2051                 (Some(ref orig_rhs), Some(ref new_rhs))
2052                     if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2053                         .is_none() =>
2054                 {
2055                     Some(format!("{}{}", before_space_str, orig_rhs))
2056                 }
2057                 (Some(ref orig_rhs), Some(ref new_rhs))
2058                     if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2059                 {
2060                     Some(format!("{}{}", new_indent_str, new_rhs))
2061                 }
2062                 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2063                 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2064                     let shape = shape.infinite_width();
2065                     expr.rewrite(context, shape)
2066                         .map(|s| format!("{}{}", before_space_str, s))
2067                 }
2068                 (None, None) => None,
2069                 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2070             }
2071         }
2072     }
2073 }
2074
2075 fn shape_from_rhs_tactic(
2076     context: &RewriteContext<'_>,
2077     shape: Shape,
2078     rhs_tactic: RhsTactics,
2079 ) -> Option<Shape> {
2080     match rhs_tactic {
2081         RhsTactics::ForceNextLineWithoutIndent => shape
2082             .with_max_width(context.config)
2083             .sub_width(shape.indent.width()),
2084         RhsTactics::Default | RhsTactics::AllowOverflow => {
2085             Shape::indented(shape.indent.block_indent(context.config), context.config)
2086                 .sub_width(shape.rhs_overhead(context.config))
2087         }
2088     }
2089 }
2090
2091 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2092 /// original's line formatting.
2093 ///
2094 /// It is considered better if:
2095 /// 1. the tactic is ForceNextLineWithoutIndent
2096 /// 2. next_line_rhs doesn't have newlines
2097 /// 3. the original line has more newlines than next_line_rhs
2098 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2099 ///    doesn't
2100 pub(crate) fn prefer_next_line(
2101     orig_rhs: &str,
2102     next_line_rhs: &str,
2103     rhs_tactics: RhsTactics,
2104 ) -> bool {
2105     rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2106         || !next_line_rhs.contains('\n')
2107         || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2108         || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2109         || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2110         || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2111 }
2112
2113 fn rewrite_expr_addrof(
2114     context: &RewriteContext<'_>,
2115     borrow_kind: ast::BorrowKind,
2116     mutability: ast::Mutability,
2117     expr: &ast::Expr,
2118     shape: Shape,
2119 ) -> Option<String> {
2120     let operator_str = match (mutability, borrow_kind) {
2121         (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2122         (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2123         (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2124         (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2125     };
2126     rewrite_unary_prefix(context, operator_str, expr, shape)
2127 }
2128
2129 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2130     match expr.kind {
2131         ast::ExprKind::MethodCall(..) => true,
2132         ast::ExprKind::AddrOf(_, _, ref expr)
2133         | ast::ExprKind::Box(ref expr)
2134         | ast::ExprKind::Cast(ref expr, _)
2135         | ast::ExprKind::Try(ref expr)
2136         | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2137         _ => false,
2138     }
2139 }
2140
2141 #[cfg(test)]
2142 mod test {
2143     use super::last_line_offsetted;
2144
2145     #[test]
2146     fn test_last_line_offsetted() {
2147         let lines = "one\n    two";
2148         assert_eq!(last_line_offsetted(2, lines), true);
2149         assert_eq!(last_line_offsetted(4, lines), false);
2150         assert_eq!(last_line_offsetted(6, lines), false);
2151
2152         let lines = "one    two";
2153         assert_eq!(last_line_offsetted(2, lines), false);
2154         assert_eq!(last_line_offsetted(0, lines), false);
2155
2156         let lines = "\ntwo";
2157         assert_eq!(last_line_offsetted(2, lines), false);
2158         assert_eq!(last_line_offsetted(0, lines), false);
2159
2160         let lines = "one\n    two      three";
2161         assert_eq!(last_line_offsetted(2, lines), true);
2162         let lines = "one\n two      three";
2163         assert_eq!(last_line_offsetted(2, lines), false);
2164     }
2165 }