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