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