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