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