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