]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
d22c3f21a779270406b3f0f15c1ef45c77e9b0ed
[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::cmp::{Ordering, min};
12 use std::iter::ExactSizeIterator;
13 use std::fmt::Write;
14
15 use {Indent, Shape, Spanned};
16 use codemap::SpanUtils;
17 use rewrite::{Rewrite, RewriteContext};
18 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
19             DefinitiveListTactic, definitive_tactic, ListItem, format_item_list, struct_lit_shape,
20             struct_lit_tactic, shape_for_tactic, struct_lit_formatting};
21 use string::{StringFormat, rewrite_string};
22 use utils::{extra_offset, last_line_width, wrap_str, binary_search, first_line_width,
23             semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr,
24             colon_spaces, contains_skip, mk_sp};
25 use visitor::FmtVisitor;
26 use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle, Style};
27 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
28 use types::{rewrite_path, PathContext, can_be_overflowed_type};
29 use items::{span_lo_for_arg, span_hi_for_arg};
30 use chains::rewrite_chain;
31 use macros::{rewrite_macro, MacroPosition};
32 use patterns::{TuplePatField, can_be_overflowed_pat};
33
34 use syntax::{ast, ptr};
35 use syntax::codemap::{CodeMap, Span, BytePos};
36 use syntax::parse::classify;
37
38 impl Rewrite for ast::Expr {
39     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
40         format_expr(self, ExprType::SubExpression, context, shape)
41     }
42 }
43
44 #[derive(PartialEq)]
45 enum ExprType {
46     Statement,
47     SubExpression,
48 }
49
50 fn combine_attr_and_expr(
51     context: &RewriteContext,
52     shape: Shape,
53     attr_str: &str,
54     expr_str: &str,
55 ) -> String {
56     let separator = if attr_str.is_empty() {
57         String::new()
58     } else {
59         if expr_str.contains('\n') || attr_str.contains('\n') ||
60             attr_str.len() + expr_str.len() > shape.width
61         {
62             format!("\n{}", shape.indent.to_string(context.config))
63         } else {
64             String::from(" ")
65         }
66     };
67     format!("{}{}{}", attr_str, separator, expr_str)
68 }
69
70 fn format_expr(
71     expr: &ast::Expr,
72     expr_type: ExprType,
73     context: &RewriteContext,
74     shape: Shape,
75 ) -> Option<String> {
76     let attr_rw = (&*expr.attrs).rewrite(context, shape);
77     if contains_skip(&*expr.attrs) {
78         if let Some(attr_str) = attr_rw {
79             return Some(combine_attr_and_expr(
80                 context,
81                 shape,
82                 &attr_str,
83                 &context.snippet(expr.span),
84             ));
85         } else {
86             return Some(context.snippet(expr.span));
87         }
88     }
89     let expr_rw = match expr.node {
90         ast::ExprKind::Array(ref expr_vec) => {
91             rewrite_array(
92                 expr_vec.iter().map(|e| &**e),
93                 mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
94                 context,
95                 shape,
96             )
97         }
98         ast::ExprKind::Lit(ref l) => {
99             match l.node {
100                 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
101                     rewrite_string_lit(context, l.span, shape)
102                 }
103                 _ => {
104                     wrap_str(
105                         context.snippet(expr.span),
106                         context.config.max_width(),
107                         shape,
108                     )
109                 }
110             }
111         }
112         ast::ExprKind::Call(ref callee, ref args) => {
113             let inner_span = mk_sp(callee.span.hi, expr.span.hi);
114             rewrite_call_with_binary_search(
115                 context,
116                 &**callee,
117                 &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
118                 inner_span,
119                 shape,
120             )
121         }
122         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
123         ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
124             // FIXME: format comments between operands and operator
125             rewrite_pair(
126                 &**lhs,
127                 &**rhs,
128                 "",
129                 &format!(" {} ", context.snippet(op.span)),
130                 "",
131                 context,
132                 shape,
133             )
134         }
135         ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
136         ast::ExprKind::Struct(ref path, ref fields, ref base) => {
137             rewrite_struct_lit(
138                 context,
139                 path,
140                 fields,
141                 base.as_ref().map(|e| &**e),
142                 expr.span,
143                 shape,
144             )
145         }
146         ast::ExprKind::Tup(ref items) => {
147             rewrite_tuple(
148                 context,
149                 &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
150                 expr.span,
151                 shape,
152             )
153         }
154         ast::ExprKind::If(..) |
155         ast::ExprKind::IfLet(..) |
156         ast::ExprKind::ForLoop(..) |
157         ast::ExprKind::Loop(..) |
158         ast::ExprKind::While(..) |
159         ast::ExprKind::WhileLet(..) => {
160             to_control_flow(expr, expr_type)
161                 .and_then(|control_flow| control_flow.rewrite(context, shape))
162         }
163         ast::ExprKind::Block(ref block) => block.rewrite(context, shape),
164         ast::ExprKind::Match(ref cond, ref arms) => {
165             rewrite_match(context, cond, arms, shape, expr.span)
166         }
167         ast::ExprKind::Path(ref qself, ref path) => {
168             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
169         }
170         ast::ExprKind::Assign(ref lhs, ref rhs) => {
171             rewrite_assignment(context, lhs, rhs, None, shape)
172         }
173         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
174             rewrite_assignment(context, lhs, rhs, Some(op), shape)
175         }
176         ast::ExprKind::Continue(ref opt_ident) => {
177             let id_str = match *opt_ident {
178                 Some(ident) => format!(" {}", ident.node),
179                 None => String::new(),
180             };
181             wrap_str(
182                 format!("continue{}", id_str),
183                 context.config.max_width(),
184                 shape,
185             )
186         }
187         ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
188             let id_str = match *opt_ident {
189                 Some(ident) => format!(" {}", ident.node),
190                 None => String::new(),
191             };
192
193             if let Some(ref expr) = *opt_expr {
194                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
195             } else {
196                 wrap_str(
197                     format!("break{}", id_str),
198                     context.config.max_width(),
199                     shape,
200                 )
201             }
202         }
203         ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
204             rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
205         }
206         ast::ExprKind::Try(..) |
207         ast::ExprKind::Field(..) |
208         ast::ExprKind::TupField(..) |
209         ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
210         ast::ExprKind::Mac(ref mac) => {
211             // Failure to rewrite a marco should not imply failure to
212             // rewrite the expression.
213             rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
214                 wrap_str(
215                     context.snippet(expr.span),
216                     context.config.max_width(),
217                     shape,
218                 )
219             })
220         }
221         ast::ExprKind::Ret(None) => {
222             wrap_str("return".to_owned(), context.config.max_width(), shape)
223         }
224         ast::ExprKind::Ret(Some(ref expr)) => {
225             rewrite_unary_prefix(context, "return ", &**expr, shape)
226         }
227         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
228         ast::ExprKind::AddrOf(mutability, ref expr) => {
229             rewrite_expr_addrof(context, mutability, expr, shape)
230         }
231         ast::ExprKind::Cast(ref expr, ref ty) => {
232             rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
233         }
234         ast::ExprKind::Type(ref expr, ref ty) => {
235             rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
236         }
237         ast::ExprKind::Index(ref expr, ref index) => {
238             rewrite_index(&**expr, &**index, context, shape)
239         }
240         ast::ExprKind::Repeat(ref expr, ref repeats) => {
241             let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
242                 ("[ ", " ]")
243             } else {
244                 ("[", "]")
245             };
246             rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
247         }
248         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
249             let delim = match limits {
250                 ast::RangeLimits::HalfOpen => "..",
251                 ast::RangeLimits::Closed => "...",
252             };
253
254             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
255                 (Some(ref lhs), Some(ref rhs)) => {
256                     let sp_delim = if context.config.spaces_around_ranges() {
257                         format!(" {} ", delim)
258                     } else {
259                         delim.into()
260                     };
261                     rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
262                 }
263                 (None, Some(ref rhs)) => {
264                     let sp_delim = if context.config.spaces_around_ranges() {
265                         format!("{} ", delim)
266                     } else {
267                         delim.into()
268                     };
269                     rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
270                 }
271                 (Some(ref lhs), None) => {
272                     let sp_delim = if context.config.spaces_around_ranges() {
273                         format!(" {}", delim)
274                     } else {
275                         delim.into()
276                     };
277                     rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
278                 }
279                 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
280             }
281         }
282         // We do not format these expressions yet, but they should still
283         // satisfy our width restrictions.
284         ast::ExprKind::InPlace(..) |
285         ast::ExprKind::InlineAsm(..) => {
286             wrap_str(
287                 context.snippet(expr.span),
288                 context.config.max_width(),
289                 shape,
290             )
291         }
292         ast::ExprKind::Catch(ref block) => {
293             if let rewrite @ Some(_) = try_one_line_block(context, shape, "do catch ", block) {
294                 return rewrite;
295             }
296             // 9 = `do catch `
297             let budget = shape.width.checked_sub(9).unwrap_or(0);
298             Some(format!(
299                 "{}{}",
300                 "do catch ",
301                 try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
302             ))
303         }
304     };
305     match (attr_rw, expr_rw) {
306         (Some(attr_str), Some(expr_str)) => {
307             recover_comment_removed(
308                 combine_attr_and_expr(context, shape, &attr_str, &expr_str),
309                 expr.span,
310                 context,
311                 shape,
312             )
313         }
314         _ => None,
315     }
316 }
317
318 fn try_one_line_block(
319     context: &RewriteContext,
320     shape: Shape,
321     prefix: &str,
322     block: &ast::Block,
323 ) -> Option<String> {
324     if is_simple_block(block, context.codemap) {
325         let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
326         let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
327         let result = format!("{}{{ {} }}", prefix, expr_str);
328         if result.len() <= shape.width && !result.contains('\n') {
329             return Some(result);
330         }
331     }
332     None
333 }
334
335 pub fn rewrite_pair<LHS, RHS>(
336     lhs: &LHS,
337     rhs: &RHS,
338     prefix: &str,
339     infix: &str,
340     suffix: &str,
341     context: &RewriteContext,
342     shape: Shape,
343 ) -> Option<String>
344 where
345     LHS: Rewrite,
346     RHS: Rewrite,
347 {
348     // Get "full width" rhs and see if it fits on the current line. This
349     // usually works fairly well since it tends to place operands of
350     // operations with high precendence close together.
351     // Note that this is non-conservative, but its just to see if it's even
352     // worth trying to put everything on one line.
353     let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
354     let rhs_result = rhs.rewrite(context, rhs_shape);
355
356     if let Some(rhs_result) = rhs_result {
357         // This is needed in case of line break not caused by a
358         // shortage of space, but by end-of-line comments, for example.
359         if !rhs_result.contains('\n') {
360             let lhs_shape =
361                 try_opt!(try_opt!(shape.offset_left(prefix.len())).sub_width(infix.len()));
362             let lhs_result = lhs.rewrite(context, lhs_shape);
363             if let Some(lhs_result) = lhs_result {
364                 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
365
366                 let remaining_width = shape
367                     .width
368                     .checked_sub(last_line_width(&result) + suffix.len())
369                     .unwrap_or(0);
370
371                 if rhs_result.len() <= remaining_width {
372                     result.push_str(&rhs_result);
373                     result.push_str(suffix);
374                     return Some(result);
375                 }
376
377                 // Try rewriting the rhs into the remaining space.
378                 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
379                 if let Some(rhs_shape) = rhs_shape {
380                     if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
381                         // FIXME this should always hold.
382                         if rhs_result.len() <= remaining_width {
383                             result.push_str(&rhs_result);
384                             result.push_str(suffix);
385                             return Some(result);
386                         }
387                     }
388                 }
389             }
390         }
391     }
392
393     // We have to use multiple lines.
394
395     // Re-evaluate the rhs because we have more space now:
396     let infix = infix.trim_right();
397     let rhs_shape = match context.config.control_style() {
398         Style::Legacy => {
399             try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
400         }
401         Style::Rfc => {
402             // Try to calculate the initial constraint on the right hand side.
403             let rhs_overhead = context
404                 .config
405                 .max_width()
406                 .checked_sub(shape.used_width() + shape.width)
407                 .unwrap_or(0);
408             try_opt!(
409                 Shape::indented(shape.indent.block_indent(context.config), context.config)
410                     .sub_width(rhs_overhead)
411             )
412         }
413     };
414     let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
415     let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
416     let lhs_shape = Shape {
417         width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
418         ..shape
419     };
420     let lhs_result = try_opt!(lhs.rewrite(context, lhs_shape));
421     Some(format!(
422         "{}{}{}\n{}{}{}",
423         prefix,
424         lhs_result,
425         infix,
426         rhs_shape.indent.to_string(context.config),
427         rhs_result,
428         suffix
429     ))
430 }
431
432 pub fn rewrite_array<'a, I>(
433     expr_iter: I,
434     span: Span,
435     context: &RewriteContext,
436     shape: Shape,
437 ) -> Option<String>
438 where
439     I: Iterator<Item = &'a ast::Expr>,
440 {
441     let bracket_size = if context.config.spaces_within_square_brackets() {
442         2 // "[ "
443     } else {
444         1 // "["
445     };
446
447     let nested_shape = match context.config.array_layout() {
448         IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
449         IndentStyle::Visual => {
450             try_opt!(
451                 shape
452                     .visual_indent(bracket_size)
453                     .sub_width(bracket_size * 2)
454             )
455         }
456     };
457
458     let items = itemize_list(
459         context.codemap,
460         expr_iter,
461         "]",
462         |item| item.span.lo,
463         |item| item.span.hi,
464         |item| item.rewrite(context, nested_shape),
465         span.lo,
466         span.hi,
467     ).collect::<Vec<_>>();
468
469     if items.is_empty() {
470         if context.config.spaces_within_square_brackets() {
471             return Some("[ ]".to_string());
472         } else {
473             return Some("[]".to_string());
474         }
475     }
476
477     let has_long_item = items
478         .iter()
479         .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
480
481     let tactic = match context.config.array_layout() {
482         IndentStyle::Block => {
483             // FIXME wrong shape in one-line case
484             match shape.width.checked_sub(2 * bracket_size) {
485                 Some(width) => {
486                     let tactic =
487                         ListTactic::LimitedHorizontalVertical(context.config.array_width());
488                     definitive_tactic(&items, tactic, width)
489                 }
490                 None => DefinitiveListTactic::Vertical,
491             }
492         }
493         IndentStyle::Visual => {
494             if has_long_item || items.iter().any(ListItem::is_multiline) {
495                 definitive_tactic(
496                     &items,
497                     ListTactic::LimitedHorizontalVertical(context.config.array_width()),
498                     nested_shape.width,
499                 )
500             } else {
501                 DefinitiveListTactic::Mixed
502             }
503         }
504     };
505
506     let fmt = ListFormatting {
507         tactic: tactic,
508         separator: ",",
509         trailing_separator: SeparatorTactic::Never,
510         shape: nested_shape,
511         ends_with_newline: false,
512         config: context.config,
513     };
514     let list_str = try_opt!(write_list(&items, &fmt));
515
516     let result = if context.config.array_layout() == IndentStyle::Visual ||
517         tactic != DefinitiveListTactic::Vertical
518     {
519         if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
520             format!("[ {} ]", list_str)
521         } else {
522             format!("[{}]", list_str)
523         }
524     } else {
525         format!(
526             "[\n{}{},\n{}]",
527             nested_shape.indent.to_string(context.config),
528             list_str,
529             shape.block().indent.to_string(context.config)
530         )
531     };
532
533     Some(result)
534 }
535
536 // Return type is (prefix, extra_offset)
537 fn rewrite_closure_fn_decl(
538     capture: ast::CaptureBy,
539     fn_decl: &ast::FnDecl,
540     body: &ast::Expr,
541     span: Span,
542     context: &RewriteContext,
543     shape: Shape,
544 ) -> Option<(String, usize)> {
545     let mover = if capture == ast::CaptureBy::Value {
546         "move "
547     } else {
548         ""
549     };
550     // 4 = "|| {".len(), which is overconservative when the closure consists of
551     // a single expression.
552     let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
553
554     // 1 = |
555     let argument_offset = nested_shape.indent + 1;
556     let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
557     let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
558
559     let arg_items = itemize_list(
560         context.codemap,
561         fn_decl.inputs.iter(),
562         "|",
563         |arg| span_lo_for_arg(arg),
564         |arg| span_hi_for_arg(context, arg),
565         |arg| arg.rewrite(context, arg_shape),
566         context.codemap.span_after(span, "|"),
567         body.span.lo,
568     );
569     let item_vec = arg_items.collect::<Vec<_>>();
570     // 1 = space between arguments and return type.
571     let horizontal_budget = nested_shape
572         .width
573         .checked_sub(ret_str.len() + 1)
574         .unwrap_or(0);
575     let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
576     let arg_shape = match tactic {
577         DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
578         _ => arg_shape,
579     };
580
581     let fmt = ListFormatting {
582         tactic: tactic,
583         separator: ",",
584         trailing_separator: SeparatorTactic::Never,
585         shape: arg_shape,
586         ends_with_newline: false,
587         config: context.config,
588     };
589     let list_str = try_opt!(write_list(&item_vec, &fmt));
590     let mut prefix = format!("{}|{}|", mover, list_str);
591     // 1 = space between `|...|` and body.
592     let extra_offset = extra_offset(&prefix, shape) + 1;
593
594     if !ret_str.is_empty() {
595         if prefix.contains('\n') {
596             prefix.push('\n');
597             prefix.push_str(&argument_offset.to_string(context.config));
598         } else {
599             prefix.push(' ');
600         }
601         prefix.push_str(&ret_str);
602     }
603
604     Some((prefix, extra_offset))
605 }
606
607 // This functions is pretty messy because of the rules around closures and blocks:
608 // FIXME - the below is probably no longer true in full.
609 //   * if there is a return type, then there must be braces,
610 //   * given a closure with braces, whether that is parsed to give an inner block
611 //     or not depends on if there is a return type and if there are statements
612 //     in that block,
613 //   * if the first expression in the body ends with a block (i.e., is a
614 //     statement without needing a semi-colon), then adding or removing braces
615 //     can change whether it is treated as an expression or statement.
616 fn rewrite_closure(
617     capture: ast::CaptureBy,
618     fn_decl: &ast::FnDecl,
619     body: &ast::Expr,
620     span: Span,
621     context: &RewriteContext,
622     shape: Shape,
623 ) -> Option<String> {
624     let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
625         capture,
626         fn_decl,
627         body,
628         span,
629         context,
630         shape,
631     ));
632     // 1 = space between `|...|` and body.
633     let body_shape = try_opt!(shape.offset_left(extra_offset));
634
635     if let ast::ExprKind::Block(ref block) = body.node {
636         // The body of the closure is an empty block.
637         if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
638             return Some(format!("{} {{}}", prefix));
639         }
640
641         // Figure out if the block is necessary.
642         let needs_block = block.rules != ast::BlockCheckMode::Default ||
643             block.stmts.len() > 1 || context.inside_macro ||
644             block_contains_comment(block, context.codemap) ||
645             prefix.contains('\n');
646
647         let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
648             true
649         } else {
650             false
651         };
652         if no_return_type && !needs_block {
653             // lock.stmts.len() == 1
654             if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
655                 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
656                     return Some(rw);
657                 }
658             }
659         }
660
661         if !needs_block {
662             // We need braces, but we might still prefer a one-liner.
663             let stmt = &block.stmts[0];
664             // 4 = braces and spaces.
665             if let Some(body_shape) = body_shape.sub_width(4) {
666                 // Checks if rewrite succeeded and fits on a single line.
667                 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
668                     return Some(format!("{} {{ {} }}", prefix, rewrite));
669                 }
670             }
671         }
672
673         // Either we require a block, or tried without and failed.
674         rewrite_closure_block(&block, &prefix, context, body_shape)
675     } else {
676         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
677             // The closure originally had a non-block expression, but we can't fit on
678             // one line, so we'll insert a block.
679             rewrite_closure_with_block(context, body_shape, &prefix, body)
680         })
681     }
682 }
683
684 // Rewrite closure with a single expression wrapping its body with block.
685 fn rewrite_closure_with_block(
686     context: &RewriteContext,
687     shape: Shape,
688     prefix: &str,
689     body: &ast::Expr,
690 ) -> Option<String> {
691     let block = ast::Block {
692         stmts: vec![
693             ast::Stmt {
694                 id: ast::NodeId::new(0),
695                 node: ast::StmtKind::Expr(ptr::P(body.clone())),
696                 span: body.span,
697             },
698         ],
699         id: ast::NodeId::new(0),
700         rules: ast::BlockCheckMode::Default,
701         span: body.span,
702     };
703     rewrite_closure_block(&block, prefix, context, shape)
704 }
705
706 // Rewrite closure with a single expression without wrapping its body with block.
707 fn rewrite_closure_expr(
708     expr: &ast::Expr,
709     prefix: &str,
710     context: &RewriteContext,
711     shape: Shape,
712 ) -> Option<String> {
713     let mut rewrite = expr.rewrite(context, shape);
714     if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
715         rewrite = and_one_line(rewrite);
716     }
717     rewrite.map(|rw| format!("{} {}", prefix, rw))
718 }
719
720 // Rewrite closure whose body is block.
721 fn rewrite_closure_block(
722     block: &ast::Block,
723     prefix: &str,
724     context: &RewriteContext,
725     shape: Shape,
726 ) -> Option<String> {
727     // Start with visual indent, then fall back to block indent if the
728     // closure is large.
729     let block_threshold = context.config.closure_block_indent_threshold();
730     if block_threshold >= 0 {
731         if let Some(block_str) = block.rewrite(&context, shape) {
732             if block_str.matches('\n').count() <= block_threshold as usize &&
733                 !need_block_indent(&block_str, shape)
734             {
735                 if let Some(block_str) = block_str.rewrite(context, shape) {
736                     return Some(format!("{} {}", prefix, block_str));
737                 }
738             }
739         }
740     }
741
742     // The body of the closure is big enough to be block indented, that
743     // means we must re-format.
744     let block_shape = shape.block().with_max_width(context.config);
745     let block_str = try_opt!(block.rewrite(&context, block_shape));
746     Some(format!("{} {}", prefix, block_str))
747 }
748
749 fn and_one_line(x: Option<String>) -> Option<String> {
750     x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
751 }
752
753 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
754     debug!("nop_block_collapse {:?} {}", block_str, budget);
755     block_str.map(|block_str| {
756         if block_str.starts_with('{') && budget >= 2 &&
757             (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
758         {
759             "{}".to_owned()
760         } else {
761             block_str.to_owned()
762         }
763     })
764 }
765
766 impl Rewrite for ast::Block {
767     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
768         // shape.width is used only for the single line case: either the empty block `{}`,
769         // or an unsafe expression `unsafe { e }`.
770
771         if self.stmts.is_empty() && !block_contains_comment(self, context.codemap) &&
772             shape.width >= 2
773         {
774             return Some("{}".to_owned());
775         }
776
777         // If a block contains only a single-line comment, then leave it on one line.
778         let user_str = context.snippet(self.span);
779         let user_str = user_str.trim();
780         if user_str.starts_with('{') && user_str.ends_with('}') {
781             let comment_str = user_str[1..user_str.len() - 1].trim();
782             if self.stmts.is_empty() && !comment_str.contains('\n') &&
783                 !comment_str.starts_with("//") &&
784                 comment_str.len() + 4 <= shape.width
785             {
786                 return Some(format!("{{ {} }}", comment_str));
787             }
788         }
789
790         let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
791         visitor.block_indent = shape.indent;
792         visitor.is_if_else_block = context.is_if_else_block;
793
794         let prefix = match self.rules {
795             ast::BlockCheckMode::Unsafe(..) => {
796                 let snippet = context.snippet(self.span);
797                 let open_pos = try_opt!(snippet.find_uncommented("{"));
798                 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
799
800                 // Extract comment between unsafe and block start.
801                 let trimmed = &snippet[6..open_pos].trim();
802
803                 let prefix = if !trimmed.is_empty() {
804                     // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
805                     let budget = try_opt!(shape.width.checked_sub(9));
806                     format!(
807                         "unsafe {} ",
808                         try_opt!(rewrite_comment(
809                             trimmed,
810                             true,
811                             Shape::legacy(budget, shape.indent + 7),
812                             context.config,
813                         ))
814                     )
815                 } else {
816                     "unsafe ".to_owned()
817                 };
818                 if let result @ Some(_) = try_one_line_block(context, shape, &prefix, self) {
819                     return result;
820                 }
821                 prefix
822             }
823             ast::BlockCheckMode::Default => {
824                 visitor.last_pos = self.span.lo;
825                 String::new()
826             }
827         };
828
829         visitor.visit_block(self);
830         if visitor.failed && shape.indent.alignment != 0 {
831             self.rewrite(
832                 context,
833                 Shape::indented(shape.indent.block_only(), context.config),
834             )
835         } else {
836             Some(format!("{}{}", prefix, visitor.buffer))
837         }
838     }
839 }
840
841 impl Rewrite for ast::Stmt {
842     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
843         let result = match self.node {
844             ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
845             ast::StmtKind::Expr(ref ex) |
846             ast::StmtKind::Semi(ref ex) => {
847                 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
848
849                 format_expr(
850                     ex,
851                     match self.node {
852                         ast::StmtKind::Expr(_) => ExprType::SubExpression,
853                         ast::StmtKind::Semi(_) => ExprType::Statement,
854                         _ => unreachable!(),
855                     },
856                     context,
857                     try_opt!(shape.sub_width(suffix.len())),
858                 ).map(|s| s + suffix)
859             }
860             ast::StmtKind::Mac(..) |
861             ast::StmtKind::Item(..) => None,
862         };
863         result.and_then(|res| {
864             recover_comment_removed(res, self.span, context, shape)
865         })
866     }
867 }
868
869 // Rewrite condition if the given expression has one.
870 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
871     match expr.node {
872         ast::ExprKind::Match(ref cond, _) => {
873             // `match `cond` {`
874             let cond_shape = match context.config.control_style() {
875                 Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
876                 Style::Rfc => try_opt!(shape.offset_left(8)),
877             };
878             cond.rewrite(context, cond_shape)
879         }
880         ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
881             stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
882         }
883         _ => {
884             to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
885                 let alt_block_sep = String::from("\n") +
886                     &shape.indent.block_only().to_string(context.config);
887                 control_flow
888                     .rewrite_cond(context, shape, &alt_block_sep)
889                     .and_then(|rw| Some(rw.0))
890             })
891         }
892     }
893 }
894
895 // Abstraction over control flow expressions
896 #[derive(Debug)]
897 struct ControlFlow<'a> {
898     cond: Option<&'a ast::Expr>,
899     block: &'a ast::Block,
900     else_block: Option<&'a ast::Expr>,
901     label: Option<ast::SpannedIdent>,
902     pat: Option<&'a ast::Pat>,
903     keyword: &'a str,
904     matcher: &'a str,
905     connector: &'a str,
906     allow_single_line: bool,
907     // True if this is an `if` expression in an `else if` :-( hacky
908     nested_if: bool,
909     span: Span,
910 }
911
912 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
913     match expr.node {
914         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
915             Some(ControlFlow::new_if(
916                 cond,
917                 None,
918                 if_block,
919                 else_block.as_ref().map(|e| &**e),
920                 expr_type == ExprType::SubExpression,
921                 false,
922                 expr.span,
923             ))
924         }
925         ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
926             Some(ControlFlow::new_if(
927                 cond,
928                 Some(pat),
929                 if_block,
930                 else_block.as_ref().map(|e| &**e),
931                 expr_type == ExprType::SubExpression,
932                 false,
933                 expr.span,
934             ))
935         }
936         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
937             Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
938         }
939         ast::ExprKind::Loop(ref block, label) => Some(
940             ControlFlow::new_loop(block, label, expr.span),
941         ),
942         ast::ExprKind::While(ref cond, ref block, label) => Some(
943             ControlFlow::new_while(None, cond, block, label, expr.span),
944         ),
945         ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
946             Some(ControlFlow::new_while(
947                 Some(pat),
948                 cond,
949                 block,
950                 label,
951                 expr.span,
952             ))
953         }
954         _ => None,
955     }
956 }
957
958 impl<'a> ControlFlow<'a> {
959     fn new_if(
960         cond: &'a ast::Expr,
961         pat: Option<&'a ast::Pat>,
962         block: &'a ast::Block,
963         else_block: Option<&'a ast::Expr>,
964         allow_single_line: bool,
965         nested_if: bool,
966         span: Span,
967     ) -> ControlFlow<'a> {
968         ControlFlow {
969             cond: Some(cond),
970             block: block,
971             else_block: else_block,
972             label: None,
973             pat: pat,
974             keyword: "if",
975             matcher: match pat {
976                 Some(..) => "let",
977                 None => "",
978             },
979             connector: " =",
980             allow_single_line: allow_single_line,
981             nested_if: nested_if,
982             span: span,
983         }
984     }
985
986     fn new_loop(
987         block: &'a ast::Block,
988         label: Option<ast::SpannedIdent>,
989         span: Span,
990     ) -> ControlFlow<'a> {
991         ControlFlow {
992             cond: None,
993             block: block,
994             else_block: None,
995             label: label,
996             pat: None,
997             keyword: "loop",
998             matcher: "",
999             connector: "",
1000             allow_single_line: false,
1001             nested_if: false,
1002             span: span,
1003         }
1004     }
1005
1006     fn new_while(
1007         pat: Option<&'a ast::Pat>,
1008         cond: &'a ast::Expr,
1009         block: &'a ast::Block,
1010         label: Option<ast::SpannedIdent>,
1011         span: Span,
1012     ) -> ControlFlow<'a> {
1013         ControlFlow {
1014             cond: Some(cond),
1015             block: block,
1016             else_block: None,
1017             label: label,
1018             pat: pat,
1019             keyword: "while",
1020             matcher: match pat {
1021                 Some(..) => "let",
1022                 None => "",
1023             },
1024             connector: " =",
1025             allow_single_line: false,
1026             nested_if: false,
1027             span: span,
1028         }
1029     }
1030
1031     fn new_for(
1032         pat: &'a ast::Pat,
1033         cond: &'a ast::Expr,
1034         block: &'a ast::Block,
1035         label: Option<ast::SpannedIdent>,
1036         span: Span,
1037     ) -> ControlFlow<'a> {
1038         ControlFlow {
1039             cond: Some(cond),
1040             block: block,
1041             else_block: None,
1042             label: label,
1043             pat: Some(pat),
1044             keyword: "for",
1045             matcher: "",
1046             connector: " in",
1047             allow_single_line: false,
1048             nested_if: false,
1049             span: span,
1050         }
1051     }
1052
1053     fn rewrite_single_line(
1054         &self,
1055         pat_expr_str: &str,
1056         context: &RewriteContext,
1057         width: usize,
1058     ) -> Option<String> {
1059         assert!(self.allow_single_line);
1060         let else_block = try_opt!(self.else_block);
1061         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
1062
1063         if let ast::ExprKind::Block(ref else_node) = else_block.node {
1064             if !is_simple_block(self.block, context.codemap) ||
1065                 !is_simple_block(else_node, context.codemap) ||
1066                 pat_expr_str.contains('\n')
1067             {
1068                 return None;
1069             }
1070
1071             let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
1072             let expr = &self.block.stmts[0];
1073             let if_str = try_opt!(expr.rewrite(
1074                 context,
1075                 Shape::legacy(new_width, Indent::empty()),
1076             ));
1077
1078             let new_width = try_opt!(new_width.checked_sub(if_str.len()));
1079             let else_expr = &else_node.stmts[0];
1080             let else_str = try_opt!(else_expr.rewrite(
1081                 context,
1082                 Shape::legacy(new_width, Indent::empty()),
1083             ));
1084
1085             if if_str.contains('\n') || else_str.contains('\n') {
1086                 return None;
1087             }
1088
1089             let result = format!(
1090                 "{} {} {{ {} }} else {{ {} }}",
1091                 self.keyword,
1092                 pat_expr_str,
1093                 if_str,
1094                 else_str
1095             );
1096
1097             if result.len() <= width {
1098                 return Some(result);
1099             }
1100         }
1101
1102         None
1103     }
1104 }
1105
1106 impl<'a> ControlFlow<'a> {
1107     fn rewrite_cond(
1108         &self,
1109         context: &RewriteContext,
1110         shape: Shape,
1111         alt_block_sep: &str,
1112     ) -> Option<(String, usize)> {
1113         let constr_shape = if self.nested_if {
1114             // We are part of an if-elseif-else chain. Our constraints are tightened.
1115             // 7 = "} else " .len()
1116             try_opt!(shape.shrink_left(7))
1117         } else {
1118             shape
1119         };
1120
1121         let label_string = rewrite_label(self.label);
1122         // 1 = space after keyword.
1123         let offset = self.keyword.len() + label_string.len() + 1;
1124
1125         let pat_expr_string = match self.cond {
1126             Some(cond) => {
1127                 let mut cond_shape = match context.config.control_style() {
1128                     Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1129                     Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1130                 };
1131                 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1132                     // 2 = " {".len()
1133                     cond_shape = try_opt!(cond_shape.sub_width(2));
1134                 }
1135
1136                 try_opt!(rewrite_pat_expr(
1137                     context,
1138                     self.pat,
1139                     cond,
1140                     self.matcher,
1141                     self.connector,
1142                     self.keyword,
1143                     cond_shape,
1144                 ))
1145             }
1146             None => String::new(),
1147         };
1148
1149         let force_newline_brace = context.config.control_style() == Style::Rfc &&
1150             pat_expr_string.contains('\n');
1151
1152         // Try to format if-else on single line.
1153         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1154             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1155
1156             if let Some(cond_str) = trial {
1157                 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1158                     return Some((cond_str, 0));
1159                 }
1160             }
1161         }
1162
1163         let cond_span = if let Some(cond) = self.cond {
1164             cond.span
1165         } else {
1166             mk_sp(self.block.span.lo, self.block.span.lo)
1167         };
1168
1169         // for event in event
1170         let between_kwd_cond = mk_sp(
1171             context.codemap.span_after(self.span, self.keyword.trim()),
1172             self.pat.map_or(
1173                 cond_span.lo,
1174                 |p| if self.matcher.is_empty() {
1175                     p.span.lo
1176                 } else {
1177                     context.codemap.span_before(self.span, self.matcher.trim())
1178                 },
1179             ),
1180         );
1181
1182         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1183
1184         let after_cond_comment =
1185             extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1186
1187         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1188             ""
1189         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1190                    force_newline_brace
1191         {
1192             alt_block_sep
1193         } else {
1194             " "
1195         };
1196
1197         let used_width = if pat_expr_string.contains('\n') {
1198             last_line_width(&pat_expr_string)
1199         } else {
1200             // 2 = spaces after keyword and condition.
1201             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1202         };
1203
1204         Some((
1205             format!(
1206                 "{}{}{}{}{}",
1207                 label_string,
1208                 self.keyword,
1209                 between_kwd_cond_comment.as_ref().map_or(
1210                     if pat_expr_string.is_empty() ||
1211                         pat_expr_string.starts_with('\n')
1212                     {
1213                         ""
1214                     } else {
1215                         " "
1216                     },
1217                     |s| &**s,
1218                 ),
1219                 pat_expr_string,
1220                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1221             ),
1222             used_width,
1223         ))
1224     }
1225 }
1226
1227 impl<'a> Rewrite for ControlFlow<'a> {
1228     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1229         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1230
1231         let alt_block_sep = String::from("\n") +
1232             &shape.indent.block_only().to_string(context.config);
1233         let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1234         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1235         if used_width == 0 {
1236             return Some(cond_str);
1237         }
1238
1239         let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1240         // This is used only for the empty block case: `{}`. So, we use 1 if we know
1241         // we should avoid the single line case.
1242         let block_width = if self.else_block.is_some() || self.nested_if {
1243             min(1, block_width)
1244         } else {
1245             block_width
1246         };
1247         let block_shape = Shape {
1248             width: block_width,
1249             ..shape
1250         };
1251         let mut block_context = context.clone();
1252         block_context.is_if_else_block = self.else_block.is_some();
1253         let block_str = try_opt!(self.block.rewrite(&block_context, block_shape));
1254
1255         let mut result = format!("{}{}", cond_str, block_str);
1256
1257         if let Some(else_block) = self.else_block {
1258             let shape = Shape::indented(shape.indent, context.config);
1259             let mut last_in_chain = false;
1260             let rewrite = match else_block.node {
1261                 // If the else expression is another if-else expression, prevent it
1262                 // from being formatted on a single line.
1263                 // Note how we're passing the original shape, as the
1264                 // cost of "else" should not cascade.
1265                 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1266                     ControlFlow::new_if(
1267                         cond,
1268                         Some(pat),
1269                         if_block,
1270                         next_else_block.as_ref().map(|e| &**e),
1271                         false,
1272                         true,
1273                         mk_sp(else_block.span.lo, self.span.hi),
1274                     ).rewrite(context, shape)
1275                 }
1276                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1277                     ControlFlow::new_if(
1278                         cond,
1279                         None,
1280                         if_block,
1281                         next_else_block.as_ref().map(|e| &**e),
1282                         false,
1283                         true,
1284                         mk_sp(else_block.span.lo, self.span.hi),
1285                     ).rewrite(context, shape)
1286                 }
1287                 _ => {
1288                     last_in_chain = true;
1289                     // When rewriting a block, the width is only used for single line
1290                     // blocks, passing 1 lets us avoid that.
1291                     let else_shape = Shape {
1292                         width: min(1, shape.width),
1293                         ..shape
1294                     };
1295                     else_block.rewrite(context, else_shape)
1296                 }
1297             };
1298
1299             let between_kwd_else_block = mk_sp(
1300                 self.block.span.hi,
1301                 context.codemap.span_before(
1302                     mk_sp(self.block.span.hi, else_block.span.lo),
1303                     "else",
1304                 ),
1305             );
1306             let between_kwd_else_block_comment =
1307                 extract_comment(between_kwd_else_block, context, shape);
1308
1309             let after_else = mk_sp(
1310                 context.codemap.span_after(
1311                     mk_sp(self.block.span.hi, else_block.span.lo),
1312                     "else",
1313                 ),
1314                 else_block.span.lo,
1315             );
1316             let after_else_comment = extract_comment(after_else, context, shape);
1317
1318             let between_sep = match context.config.control_brace_style() {
1319                 ControlBraceStyle::AlwaysNextLine |
1320                 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1321                 ControlBraceStyle::AlwaysSameLine => " ",
1322             };
1323             let after_sep = match context.config.control_brace_style() {
1324                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1325                 _ => " ",
1326             };
1327             try_opt!(
1328                 write!(
1329                     &mut result,
1330                     "{}else{}",
1331                     between_kwd_else_block_comment.as_ref().map_or(
1332                         between_sep,
1333                         |s| &**s,
1334                     ),
1335                     after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1336                 ).ok()
1337             );
1338             result.push_str(&try_opt!(rewrite));
1339         }
1340
1341         Some(result)
1342     }
1343 }
1344
1345 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1346     match label {
1347         Some(ident) => format!("{}: ", ident.node),
1348         None => "".to_owned(),
1349     }
1350 }
1351
1352 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1353     let comment_str = context.snippet(span);
1354     if contains_comment(&comment_str) {
1355         let comment = try_opt!(rewrite_comment(
1356             comment_str.trim(),
1357             false,
1358             shape,
1359             context.config,
1360         ));
1361         Some(format!(
1362             "\n{indent}{}\n{indent}",
1363             comment,
1364             indent = shape.indent.to_string(context.config)
1365         ))
1366     } else {
1367         None
1368     }
1369 }
1370
1371 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1372     let snippet = codemap.span_to_snippet(block.span).unwrap();
1373     contains_comment(&snippet)
1374 }
1375
1376 // Checks that a block contains no statements, an expression and no comments.
1377 // FIXME: incorrectly returns false when comment is contained completely within
1378 // the expression.
1379 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1380     (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1381          !block_contains_comment(block, codemap))
1382 }
1383
1384 /// Checks whether a block contains at most one statement or expression, and no comments.
1385 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1386     block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1387 }
1388
1389 /// Checks whether a block contains no statements, expressions, or comments.
1390 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1391     block.stmts.is_empty() && !block_contains_comment(block, codemap)
1392 }
1393
1394 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1395     match stmt.node {
1396         ast::StmtKind::Expr(..) => true,
1397         _ => false,
1398     }
1399 }
1400
1401 fn is_unsafe_block(block: &ast::Block) -> bool {
1402     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1403         true
1404     } else {
1405         false
1406     }
1407 }
1408
1409 // inter-match-arm-comment-rules:
1410 //  - all comments following a match arm before the start of the next arm
1411 //    are about the second arm
1412 fn rewrite_match_arm_comment(
1413     context: &RewriteContext,
1414     missed_str: &str,
1415     shape: Shape,
1416     arm_indent_str: &str,
1417 ) -> Option<String> {
1418     // The leading "," is not part of the arm-comment
1419     let missed_str = match missed_str.find_uncommented(",") {
1420         Some(n) => &missed_str[n + 1..],
1421         None => &missed_str[..],
1422     };
1423
1424     let mut result = String::new();
1425     // any text not preceeded by a newline is pushed unmodified to the block
1426     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1427     result.push_str(&missed_str[..first_brk]);
1428     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1429
1430     let first = missed_str
1431         .find(|c: char| !c.is_whitespace())
1432         .unwrap_or(missed_str.len());
1433     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1434         // Excessive vertical whitespace before comment should be preserved
1435         // FIXME handle vertical whitespace better
1436         result.push('\n');
1437     }
1438     let missed_str = missed_str[first..].trim();
1439     if !missed_str.is_empty() {
1440         let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1441         result.push('\n');
1442         result.push_str(arm_indent_str);
1443         result.push_str(&comment);
1444     }
1445
1446     Some(result)
1447 }
1448
1449 fn rewrite_match(
1450     context: &RewriteContext,
1451     cond: &ast::Expr,
1452     arms: &[ast::Arm],
1453     shape: Shape,
1454     span: Span,
1455 ) -> Option<String> {
1456     if arms.is_empty() {
1457         return None;
1458     }
1459
1460     // `match `cond` {`
1461     let cond_shape = match context.config.control_style() {
1462         Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1463         Style::Rfc => try_opt!(shape.offset_left(8)),
1464     };
1465     let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1466     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1467     let block_sep = match context.config.control_brace_style() {
1468         ControlBraceStyle::AlwaysSameLine => " ",
1469         _ => alt_block_sep.as_str(),
1470     };
1471     let mut result = format!("match {}{}{{", cond_str, block_sep);
1472
1473     let arm_shape = if context.config.indent_match_arms() {
1474         shape.block_indent(context.config.tab_spaces())
1475     } else {
1476         shape.block_indent(0)
1477     };
1478
1479     let arm_indent_str = arm_shape.indent.to_string(context.config);
1480
1481     let open_brace_pos = context.codemap.span_after(
1482         mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
1483         "{",
1484     );
1485
1486     for (i, arm) in arms.iter().enumerate() {
1487         // Make sure we get the stuff between arms.
1488         let missed_str = if i == 0 {
1489             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1490         } else {
1491             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1492         };
1493         let comment = try_opt!(rewrite_match_arm_comment(
1494             context,
1495             &missed_str,
1496             arm_shape,
1497             &arm_indent_str,
1498         ));
1499         result.push_str(&comment);
1500         result.push('\n');
1501         result.push_str(&arm_indent_str);
1502
1503         let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1504         if let Some(ref arm_str) = arm_str {
1505             result.push_str(arm_str);
1506         } else {
1507             // We couldn't format the arm, just reproduce the source.
1508             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1509             result.push_str(&snippet);
1510             result.push_str(arm_comma(context.config, &arm.body));
1511         }
1512     }
1513     // BytePos(1) = closing match brace.
1514     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1515     let last_comment = context.snippet(last_span);
1516     let comment = try_opt!(rewrite_match_arm_comment(
1517         context,
1518         &last_comment,
1519         arm_shape,
1520         &arm_indent_str,
1521     ));
1522     result.push_str(&comment);
1523     result.push('\n');
1524     result.push_str(&shape.indent.to_string(context.config));
1525     result.push('}');
1526     Some(result)
1527 }
1528
1529 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1530     let &ast::Arm {
1531         ref attrs,
1532         ref pats,
1533         ..
1534     } = arm;
1535     if !attrs.is_empty() {
1536         return attrs[0].span.lo;
1537     }
1538
1539     pats[0].span.lo
1540 }
1541
1542 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1543     arm.body.span.hi
1544 }
1545
1546 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1547     if config.match_block_trailing_comma() {
1548         ","
1549     } else if let ast::ExprKind::Block(ref block) = body.node {
1550         if let ast::BlockCheckMode::Default = block.rules {
1551             ""
1552         } else {
1553             ","
1554         }
1555     } else {
1556         ","
1557     }
1558 }
1559
1560 // Match arms.
1561 impl Rewrite for ast::Arm {
1562     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1563         debug!("Arm::rewrite {:?} {:?}", self, shape);
1564         let &ast::Arm {
1565             ref attrs,
1566             ref pats,
1567             ref guard,
1568             ref body,
1569         } = self;
1570
1571         let attr_str = if !attrs.is_empty() {
1572             if contains_skip(attrs) {
1573                 return None;
1574             }
1575             format!(
1576                 "{}\n{}",
1577                 try_opt!(attrs.rewrite(context, shape)),
1578                 shape.indent.to_string(context.config)
1579             )
1580         } else {
1581             String::new()
1582         };
1583
1584         // Patterns
1585         // 5 = ` => {`
1586         let pat_shape = try_opt!(shape.sub_width(5));
1587
1588         let pat_strs = try_opt!(
1589             pats.iter()
1590                 .map(|p| p.rewrite(context, pat_shape))
1591                 .collect::<Option<Vec<_>>>()
1592         );
1593
1594         let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1595         let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1596         let fmt = ListFormatting {
1597             tactic: if all_simple {
1598                 DefinitiveListTactic::Mixed
1599             } else {
1600                 DefinitiveListTactic::Vertical
1601             },
1602             separator: " |",
1603             trailing_separator: SeparatorTactic::Never,
1604             shape: pat_shape,
1605             ends_with_newline: false,
1606             config: context.config,
1607         };
1608         let pats_str = try_opt!(write_list(items, &fmt));
1609
1610         let guard_shape = if pats_str.contains('\n') {
1611             shape.with_max_width(context.config)
1612         } else {
1613             shape
1614         };
1615
1616         let guard_str = try_opt!(rewrite_guard(
1617             context,
1618             guard,
1619             guard_shape,
1620             trimmed_last_line_width(&pats_str),
1621         ));
1622
1623         let pats_str = format!("{}{}", pats_str, guard_str);
1624
1625         let (mut extend, body) = match body.node {
1626             ast::ExprKind::Block(ref block)
1627                 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1628                        context.config.wrap_match_arms() => {
1629                 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1630                     (false, &**expr)
1631                 } else {
1632                     (false, &**body)
1633                 }
1634             }
1635             ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1636             ast::ExprKind::Closure(..) |
1637             ast::ExprKind::Struct(..) |
1638             ast::ExprKind::Tup(..) => (true, &**body),
1639             _ => (false, &**body),
1640         };
1641         extend &= context.use_block_indent();
1642
1643         let comma = arm_comma(&context.config, body);
1644         let alt_block_sep = String::from("\n") +
1645             &shape.indent.block_only().to_string(context.config);
1646
1647         let pat_width = extra_offset(&pats_str, shape);
1648         // Let's try and get the arm body on the same line as the condition.
1649         // 4 = ` => `.len()
1650         if shape.width > pat_width + comma.len() + 4 {
1651             let arm_shape = shape
1652                 .offset_left(pat_width + 4)
1653                 .unwrap()
1654                 .sub_width(comma.len())
1655                 .unwrap();
1656             let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
1657             let is_block = if let ast::ExprKind::Block(..) = body.node {
1658                 true
1659             } else {
1660                 false
1661             };
1662
1663             match rewrite {
1664                 Some(ref body_str)
1665                     if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1666                            !context.config.wrap_match_arms() ||
1667                            (extend && first_line_width(body_str) <= arm_shape.width) ||
1668                            is_block => {
1669                     let block_sep = match context.config.control_brace_style() {
1670                         ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1671                         _ => " ",
1672                     };
1673
1674                     return Some(format!(
1675                         "{}{} =>{}{}{}",
1676                         attr_str.trim_left(),
1677                         pats_str,
1678                         block_sep,
1679                         body_str,
1680                         comma
1681                     ));
1682                 }
1683                 _ => {}
1684             }
1685         }
1686
1687         // FIXME: we're doing a second rewrite of the expr; This may not be
1688         // necessary.
1689         let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1690         let next_line_body = try_opt!(nop_block_collapse(
1691             body.rewrite(context, body_shape),
1692             body_shape.width,
1693         ));
1694         let indent_str = shape
1695             .indent
1696             .block_indent(context.config)
1697             .to_string(context.config);
1698         let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1699             if context.config.match_block_trailing_comma() {
1700                 ("{", "},")
1701             } else {
1702                 ("{", "}")
1703             }
1704         } else {
1705             ("", ",")
1706         };
1707
1708
1709         let block_sep = match context.config.control_brace_style() {
1710             ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1711             _ if body_prefix.is_empty() => "\n".to_owned(),
1712             _ => " ".to_owned() + body_prefix + "\n",
1713         };
1714
1715         if context.config.wrap_match_arms() {
1716             Some(format!(
1717                 "{}{} =>{}{}{}\n{}{}",
1718                 attr_str.trim_left(),
1719                 pats_str,
1720                 block_sep,
1721                 indent_str,
1722                 next_line_body,
1723                 shape.indent.to_string(context.config),
1724                 body_suffix
1725             ))
1726         } else {
1727             Some(format!(
1728                 "{}{} =>{}{}{}{}",
1729                 attr_str.trim_left(),
1730                 pats_str,
1731                 block_sep,
1732                 indent_str,
1733                 next_line_body,
1734                 body_suffix
1735             ))
1736         }
1737     }
1738 }
1739
1740 // A pattern is simple if it is very short or it is short-ish and just a path.
1741 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1742 fn pat_is_simple(pat_str: &str) -> bool {
1743     pat_str.len() <= 16 ||
1744         (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1745 }
1746
1747 // The `if ...` guard on a match arm.
1748 fn rewrite_guard(
1749     context: &RewriteContext,
1750     guard: &Option<ptr::P<ast::Expr>>,
1751     shape: Shape,
1752     // The amount of space used up on this line for the pattern in
1753     // the arm (excludes offset).
1754     pattern_width: usize,
1755 ) -> Option<String> {
1756     if let Some(ref guard) = *guard {
1757         // First try to fit the guard string on the same line as the pattern.
1758         // 4 = ` if `, 5 = ` => {`
1759         if let Some(cond_shape) = shape
1760             .shrink_left(pattern_width + 4)
1761             .and_then(|s| s.sub_width(5))
1762         {
1763             if let Some(cond_str) = guard
1764                 .rewrite(context, cond_shape)
1765                 .and_then(|s| s.rewrite(context, cond_shape))
1766             {
1767                 if !cond_str.contains('\n') {
1768                     return Some(format!(" if {}", cond_str));
1769                 }
1770             }
1771         }
1772
1773         // Not enough space to put the guard after the pattern, try a newline.
1774         // 3 == `if `
1775         if let Some(cond_shape) = Shape::indented(
1776             shape.indent.block_indent(context.config) + 3,
1777             context.config,
1778         ).sub_width(3)
1779         {
1780             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1781                 return Some(format!(
1782                     "\n{}if {}",
1783                     shape
1784                         .indent
1785                         .block_indent(context.config)
1786                         .to_string(context.config),
1787                     cond_str
1788                 ));
1789             }
1790         }
1791
1792         None
1793     } else {
1794         Some(String::new())
1795     }
1796 }
1797
1798 fn rewrite_pat_expr(
1799     context: &RewriteContext,
1800     pat: Option<&ast::Pat>,
1801     expr: &ast::Expr,
1802     matcher: &str,
1803     // Connecting piece between pattern and expression,
1804     // *without* trailing space.
1805     connector: &str,
1806     keyword: &str,
1807     shape: Shape,
1808 ) -> Option<String> {
1809     debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1810     let mut pat_string = String::new();
1811     let mut result = match pat {
1812         Some(pat) => {
1813             let matcher = if matcher.is_empty() {
1814                 matcher.to_owned()
1815             } else {
1816                 format!("{} ", matcher)
1817             };
1818             let pat_shape =
1819                 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1820             pat_string = try_opt!(pat.rewrite(context, pat_shape));
1821             format!("{}{}{}", matcher, pat_string, connector)
1822         }
1823         None => String::new(),
1824     };
1825
1826     // Consider only the last line of the pat string.
1827     let extra_offset = extra_offset(&result, shape);
1828
1829     // The expression may (partially) fit on the current line.
1830     if shape.width > extra_offset + 1 {
1831         let spacer = if pat.is_some() { " " } else { "" };
1832
1833         let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1834         let expr_rewrite = expr.rewrite(context, expr_shape);
1835
1836         if let Some(expr_string) = expr_rewrite {
1837             if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1838                 result.push_str(spacer);
1839                 result.push_str(&expr_string);
1840                 return Some(result);
1841             }
1842         }
1843     }
1844
1845     if pat.is_none() && keyword == "if" {
1846         return None;
1847     }
1848
1849     let nested_indent = shape.indent.block_only().block_indent(context.config);
1850
1851     // The expression won't fit on the current line, jump to next.
1852     result.push('\n');
1853     result.push_str(&nested_indent.to_string(context.config));
1854
1855     let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1856     result.push_str(&try_opt!(expr_rewrite));
1857
1858     Some(result)
1859 }
1860
1861 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1862     let string_lit = context.snippet(span);
1863
1864     if !context.config.format_strings() && !context.config.force_format_strings() {
1865         return Some(string_lit);
1866     }
1867
1868     if !context.config.force_format_strings() &&
1869         !string_requires_rewrite(context, span, &string_lit, shape)
1870     {
1871         return Some(string_lit);
1872     }
1873
1874     let fmt = StringFormat {
1875         opener: "\"",
1876         closer: "\"",
1877         line_start: " ",
1878         line_end: "\\",
1879         shape: shape,
1880         trim_end: false,
1881         config: context.config,
1882     };
1883
1884     // Remove the quote characters.
1885     let str_lit = &string_lit[1..string_lit.len() - 1];
1886
1887     rewrite_string(str_lit, &fmt)
1888 }
1889
1890 fn string_requires_rewrite(
1891     context: &RewriteContext,
1892     span: Span,
1893     string: &str,
1894     shape: Shape,
1895 ) -> bool {
1896     if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1897         return true;
1898     }
1899
1900     for (i, line) in string.lines().enumerate() {
1901         if i == 0 {
1902             if line.len() > shape.width {
1903                 return true;
1904             }
1905         } else {
1906             if line.len() > shape.width + shape.indent.width() {
1907                 return true;
1908             }
1909         }
1910     }
1911
1912     false
1913 }
1914
1915 pub fn rewrite_call_with_binary_search<R>(
1916     context: &RewriteContext,
1917     callee: &R,
1918     args: &[&ast::Expr],
1919     span: Span,
1920     shape: Shape,
1921 ) -> Option<String>
1922 where
1923     R: Rewrite,
1924 {
1925     let closure = |callee_max_width| {
1926         // FIXME using byte lens instead of char lens (and probably all over the
1927         // place too)
1928         let callee_shape = Shape {
1929             width: callee_max_width,
1930             ..shape
1931         };
1932         let callee_str = callee
1933             .rewrite(context, callee_shape)
1934             .ok_or(Ordering::Greater)?;
1935
1936         rewrite_call_inner(
1937             context,
1938             &callee_str,
1939             args,
1940             span,
1941             shape,
1942             context.config.fn_call_width(),
1943             false,
1944         )
1945     };
1946
1947     binary_search(1, shape.width, closure)
1948 }
1949
1950 pub fn rewrite_call(
1951     context: &RewriteContext,
1952     callee: &str,
1953     args: &[ptr::P<ast::Expr>],
1954     span: Span,
1955     shape: Shape,
1956 ) -> Option<String> {
1957     rewrite_call_inner(
1958         context,
1959         &callee,
1960         &args.iter().map(|x| &**x).collect::<Vec<_>>(),
1961         span,
1962         shape,
1963         context.config.fn_call_width(),
1964         false,
1965     ).ok()
1966 }
1967
1968 pub fn rewrite_call_inner<'a, T>(
1969     context: &RewriteContext,
1970     callee_str: &str,
1971     args: &[&T],
1972     span: Span,
1973     shape: Shape,
1974     args_max_width: usize,
1975     force_trailing_comma: bool,
1976 ) -> Result<String, Ordering>
1977 where
1978     T: Rewrite + Spanned + ToExpr + 'a,
1979 {
1980     // 2 = `( `, 1 = `(`
1981     let paren_overhead = if context.config.spaces_within_parens() {
1982         2
1983     } else {
1984         1
1985     };
1986     let used_width = extra_offset(&callee_str, shape);
1987     let one_line_width = shape
1988         .width
1989         .checked_sub(used_width + 2 * paren_overhead)
1990         .ok_or(Ordering::Greater)?;
1991
1992     let nested_shape = shape_from_fn_call_style(
1993         context,
1994         shape,
1995         used_width + 2 * paren_overhead,
1996         used_width + paren_overhead,
1997     ).ok_or(Ordering::Greater)?;
1998
1999     let span_lo = context.codemap.span_after(span, "(");
2000     let args_span = mk_sp(span_lo, span.hi);
2001
2002     let (extendable, list_str) = rewrite_call_args(
2003         context,
2004         args,
2005         args_span,
2006         nested_shape,
2007         one_line_width,
2008         args_max_width,
2009         force_trailing_comma,
2010     ).or_else(|| if context.use_block_indent() {
2011         rewrite_call_args(
2012             context,
2013             args,
2014             args_span,
2015             Shape::indented(
2016                 shape.block().indent.block_indent(context.config),
2017                 context.config,
2018             ),
2019             0,
2020             0,
2021             force_trailing_comma,
2022         )
2023     } else {
2024         None
2025     })
2026         .ok_or(Ordering::Less)?;
2027
2028     if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2029         let mut new_context = context.clone();
2030         new_context.use_block = true;
2031         return rewrite_call_inner(
2032             &new_context,
2033             callee_str,
2034             args,
2035             span,
2036             shape,
2037             args_max_width,
2038             force_trailing_comma,
2039         );
2040     }
2041
2042     let args_shape = shape
2043         .sub_width(last_line_width(&callee_str))
2044         .ok_or(Ordering::Less)?;
2045     Ok(format!(
2046         "{}{}",
2047         callee_str,
2048         wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2049     ))
2050 }
2051
2052 fn need_block_indent(s: &str, shape: Shape) -> bool {
2053     s.lines().skip(1).any(|s| {
2054         s.find(|c| !char::is_whitespace(c)).map_or(
2055             false,
2056             |w| w + 1 < shape.indent.width(),
2057         )
2058     })
2059 }
2060
2061 fn rewrite_call_args<'a, T>(
2062     context: &RewriteContext,
2063     args: &[&T],
2064     span: Span,
2065     shape: Shape,
2066     one_line_width: usize,
2067     args_max_width: usize,
2068     force_trailing_comma: bool,
2069 ) -> Option<(bool, String)>
2070 where
2071     T: Rewrite + Spanned + ToExpr + 'a,
2072 {
2073     let mut item_context = context.clone();
2074     item_context.inside_macro = false;
2075     let items = itemize_list(
2076         context.codemap,
2077         args.iter(),
2078         ")",
2079         |item| item.span().lo,
2080         |item| item.span().hi,
2081         |item| item.rewrite(&item_context, shape),
2082         span.lo,
2083         span.hi,
2084     );
2085     let mut item_vec: Vec<_> = items.collect();
2086
2087     // Try letting the last argument overflow to the next line with block
2088     // indentation. If its first line fits on one line with the other arguments,
2089     // we format the function arguments horizontally.
2090     let tactic = try_overflow_last_arg(
2091         &item_context,
2092         &mut item_vec,
2093         &args[..],
2094         shape,
2095         one_line_width,
2096         args_max_width,
2097     );
2098
2099     let fmt = ListFormatting {
2100         tactic: tactic,
2101         separator: ",",
2102         trailing_separator: if force_trailing_comma {
2103             SeparatorTactic::Always
2104         } else if context.inside_macro || !context.use_block_indent() {
2105             SeparatorTactic::Never
2106         } else {
2107             context.config.trailing_comma()
2108         },
2109         shape: shape,
2110         ends_with_newline: false,
2111         config: context.config,
2112     };
2113
2114     write_list(&item_vec, &fmt).map(|args_str| {
2115         (tactic != DefinitiveListTactic::Vertical, args_str)
2116     })
2117 }
2118
2119 fn try_overflow_last_arg<'a, T>(
2120     context: &RewriteContext,
2121     item_vec: &mut Vec<ListItem>,
2122     args: &[&T],
2123     shape: Shape,
2124     one_line_width: usize,
2125     args_max_width: usize,
2126 ) -> DefinitiveListTactic
2127 where
2128     T: Rewrite + Spanned + ToExpr + 'a,
2129 {
2130     let overflow_last = can_be_overflowed(&context, args);
2131
2132     // Replace the last item with its first line to see if it fits with
2133     // first arguments.
2134     let (orig_last, placeholder) = if overflow_last {
2135         let mut context = context.clone();
2136         if let Some(expr) = args[args.len() - 1].to_expr() {
2137             match expr.node {
2138                 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2139                 _ => (),
2140             }
2141         }
2142         last_arg_shape(&context, &item_vec, shape, args_max_width)
2143             .map_or((None, None), |arg_shape| {
2144                 rewrite_last_arg_with_overflow(
2145                     &context,
2146                     args[args.len() - 1],
2147                     &mut item_vec[args.len() - 1],
2148                     arg_shape,
2149                 )
2150             })
2151     } else {
2152         (None, None)
2153     };
2154
2155     let tactic = definitive_tactic(
2156         &*item_vec,
2157         ListTactic::LimitedHorizontalVertical(args_max_width),
2158         one_line_width,
2159     );
2160
2161     // Replace the stub with the full overflowing last argument if the rewrite
2162     // succeeded and its first line fits with the other arguments.
2163     match (overflow_last, tactic, placeholder) {
2164         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2165             item_vec[args.len() - 1].item = placeholder;
2166         }
2167         (true, _, _) => {
2168             item_vec[args.len() - 1].item = orig_last;
2169         }
2170         (false, _, _) => {}
2171     }
2172
2173     tactic
2174 }
2175
2176 fn last_arg_shape(
2177     context: &RewriteContext,
2178     items: &Vec<ListItem>,
2179     shape: Shape,
2180     args_max_width: usize,
2181 ) -> Option<Shape> {
2182     let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2183         acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2184     });
2185     let max_width = min(args_max_width, shape.width);
2186     let arg_indent = if context.use_block_indent() {
2187         shape.block().indent.block_unindent(context.config)
2188     } else {
2189         shape.block().indent
2190     };
2191     Some(Shape {
2192         width: try_opt!(max_width.checked_sub(overhead)),
2193         indent: arg_indent,
2194         offset: 0,
2195     })
2196 }
2197
2198 // Rewriting closure which is placed at the end of the function call's arg.
2199 // Returns `None` if the reformatted closure 'looks bad'.
2200 fn rewrite_last_closure(
2201     context: &RewriteContext,
2202     expr: &ast::Expr,
2203     shape: Shape,
2204 ) -> Option<String> {
2205     if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2206         let body = match body.node {
2207             ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2208                 stmt_expr(&block.stmts[0]).unwrap_or(body)
2209             }
2210             _ => body,
2211         };
2212         let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2213             capture,
2214             fn_decl,
2215             body,
2216             expr.span,
2217             context,
2218             shape,
2219         ));
2220         // If the closure goes multi line before its body, do not overflow the closure.
2221         if prefix.contains('\n') {
2222             return None;
2223         }
2224         let body_shape = try_opt!(shape.offset_left(extra_offset));
2225         // When overflowing the closure which consists of a single control flow expression,
2226         // force to use block if its condition uses multi line.
2227         if rewrite_cond(context, body, body_shape)
2228             .map(|cond| cond.contains('\n'))
2229             .unwrap_or(false)
2230         {
2231             return rewrite_closure_with_block(context, body_shape, &prefix, body);
2232         }
2233
2234         // Seems fine, just format the closure in usual manner.
2235         return expr.rewrite(context, shape);
2236     }
2237     None
2238 }
2239
2240 fn rewrite_last_arg_with_overflow<'a, T>(
2241     context: &RewriteContext,
2242     last_arg: &T,
2243     last_item: &mut ListItem,
2244     shape: Shape,
2245 ) -> (Option<String>, Option<String>)
2246 where
2247     T: Rewrite + Spanned + ToExpr + 'a,
2248 {
2249     let rewrite = if let Some(expr) = last_arg.to_expr() {
2250         match expr.node {
2251             // When overflowing the closure which consists of a single control flow expression,
2252             // force to use block if its condition uses multi line.
2253             ast::ExprKind::Closure(..) => rewrite_last_closure(context, expr, shape),
2254             _ => expr.rewrite(context, shape),
2255         }
2256     } else {
2257         last_arg.rewrite(context, shape)
2258     };
2259     let orig_last = last_item.item.clone();
2260
2261     if let Some(rewrite) = rewrite {
2262         let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2263         last_item.item = rewrite_first_line;
2264         (orig_last, Some(rewrite))
2265     } else {
2266         (orig_last, None)
2267     }
2268 }
2269
2270 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2271 where
2272     T: Rewrite + Spanned + ToExpr + 'a,
2273 {
2274     args.last().map_or(
2275         false,
2276         |x| x.can_be_overflowed(context, args.len()),
2277     )
2278 }
2279
2280 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2281     match expr.node {
2282         ast::ExprKind::Match(..) => {
2283             (context.use_block_indent() && args_len == 1) ||
2284                 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2285         }
2286         ast::ExprKind::If(..) |
2287         ast::ExprKind::IfLet(..) |
2288         ast::ExprKind::ForLoop(..) |
2289         ast::ExprKind::Loop(..) |
2290         ast::ExprKind::While(..) |
2291         ast::ExprKind::WhileLet(..) => {
2292             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2293         }
2294         ast::ExprKind::Block(..) |
2295         ast::ExprKind::Closure(..) => {
2296             context.use_block_indent() ||
2297                 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2298         }
2299         ast::ExprKind::Call(..) |
2300         ast::ExprKind::MethodCall(..) |
2301         ast::ExprKind::Mac(..) |
2302         ast::ExprKind::Struct(..) => context.use_block_indent() && args_len == 1,
2303         ast::ExprKind::Tup(..) => context.use_block_indent(),
2304         ast::ExprKind::AddrOf(_, ref expr) |
2305         ast::ExprKind::Box(ref expr) |
2306         ast::ExprKind::Try(ref expr) |
2307         ast::ExprKind::Unary(_, ref expr) |
2308         ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2309         _ => false,
2310     }
2311 }
2312
2313 fn paren_overhead(context: &RewriteContext) -> usize {
2314     if context.config.spaces_within_parens() {
2315         4
2316     } else {
2317         2
2318     }
2319 }
2320
2321 pub fn wrap_args_with_parens(
2322     context: &RewriteContext,
2323     args_str: &str,
2324     is_extendable: bool,
2325     shape: Shape,
2326     nested_shape: Shape,
2327 ) -> String {
2328     if !context.use_block_indent() ||
2329         (context.inside_macro && !args_str.contains('\n') &&
2330              args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2331     {
2332         if context.config.spaces_within_parens() && args_str.len() > 0 {
2333             format!("( {} )", args_str)
2334         } else {
2335             format!("({})", args_str)
2336         }
2337     } else {
2338         format!(
2339             "(\n{}{}\n{})",
2340             nested_shape.indent.to_string(context.config),
2341             args_str,
2342             shape.block().indent.to_string(context.config)
2343         )
2344     }
2345 }
2346
2347 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2348     debug!("rewrite_paren, shape: {:?}", shape);
2349     let paren_overhead = paren_overhead(context);
2350     let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2351
2352     let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2353         format!("( {} )", s)
2354     } else {
2355         format!("({})", s)
2356     };
2357
2358     let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2359     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2360
2361     if subexpr_str.contains('\n') {
2362         Some(paren_wrapper(&subexpr_str))
2363     } else {
2364         if subexpr_str.len() + paren_overhead <= shape.width {
2365             Some(paren_wrapper(&subexpr_str))
2366         } else {
2367             let sub_shape = try_opt!(shape.offset_left(2));
2368             let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2369             Some(paren_wrapper(&subexpr_str))
2370         }
2371     }
2372 }
2373
2374 fn rewrite_index(
2375     expr: &ast::Expr,
2376     index: &ast::Expr,
2377     context: &RewriteContext,
2378     shape: Shape,
2379 ) -> Option<String> {
2380     let expr_str = try_opt!(expr.rewrite(context, shape));
2381
2382     let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2383         ("[ ", " ]")
2384     } else {
2385         ("[", "]")
2386     };
2387
2388     let offset = expr_str.len() + lbr.len();
2389     if let Some(index_shape) = shape.visual_indent(offset).sub_width(offset + rbr.len()) {
2390         if let Some(index_str) = index.rewrite(context, index_shape) {
2391             return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2392         }
2393     }
2394
2395     let indent = shape.indent.block_indent(&context.config);
2396     let indent = indent.to_string(&context.config);
2397     // FIXME this is not right, since we don't take into account that shape.width
2398     // might be reduced from max_width by something on the right.
2399     let budget = try_opt!(
2400         context
2401             .config
2402             .max_width()
2403             .checked_sub(indent.len() + lbr.len() + rbr.len())
2404     );
2405     let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
2406     Some(format!(
2407         "{}\n{}{}{}{}",
2408         expr_str,
2409         indent,
2410         lbr,
2411         index_str,
2412         rbr
2413     ))
2414 }
2415
2416 fn rewrite_struct_lit<'a>(
2417     context: &RewriteContext,
2418     path: &ast::Path,
2419     fields: &'a [ast::Field],
2420     base: Option<&'a ast::Expr>,
2421     span: Span,
2422     shape: Shape,
2423 ) -> Option<String> {
2424     debug!("rewrite_struct_lit: shape {:?}", shape);
2425
2426     enum StructLitField<'a> {
2427         Regular(&'a ast::Field),
2428         Base(&'a ast::Expr),
2429     }
2430
2431     // 2 = " {".len()
2432     let path_shape = try_opt!(shape.sub_width(2));
2433     let path_str = try_opt!(rewrite_path(
2434         context,
2435         PathContext::Expr,
2436         None,
2437         path,
2438         path_shape,
2439     ));
2440
2441     if fields.len() == 0 && base.is_none() {
2442         return Some(format!("{} {{}}", path_str));
2443     }
2444
2445     let field_iter = fields
2446         .into_iter()
2447         .map(StructLitField::Regular)
2448         .chain(base.into_iter().map(StructLitField::Base));
2449
2450     // Foo { a: Foo } - indent is +3, width is -5.
2451     let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2452
2453     let span_lo = |item: &StructLitField| match *item {
2454         StructLitField::Regular(field) => field.span.lo,
2455         StructLitField::Base(expr) => {
2456             let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2457             let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2458             let pos = snippet.find_uncommented("..").unwrap();
2459             last_field_hi + BytePos(pos as u32)
2460         }
2461     };
2462     let span_hi = |item: &StructLitField| match *item {
2463         StructLitField::Regular(field) => field.span.hi,
2464         StructLitField::Base(expr) => expr.span.hi,
2465     };
2466     let rewrite = |item: &StructLitField| match *item {
2467         StructLitField::Regular(field) => {
2468             // The 1 taken from the v_budget is for the comma.
2469             rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
2470         }
2471         StructLitField::Base(expr) => {
2472             // 2 = ..
2473             expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2474                 .map(|s| format!("..{}", s))
2475         }
2476     };
2477
2478     let items = itemize_list(
2479         context.codemap,
2480         field_iter,
2481         "}",
2482         span_lo,
2483         span_hi,
2484         rewrite,
2485         context.codemap.span_after(span, "{"),
2486         span.hi,
2487     );
2488     let item_vec = items.collect::<Vec<_>>();
2489
2490     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2491     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2492     let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2493
2494     let fields_str = try_opt!(write_list(&item_vec, &fmt));
2495     let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
2496         (fields_str.contains('\n') ||
2497              context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2498              fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0))
2499     {
2500         format!(
2501             "\n{}{}\n{}",
2502             v_shape.indent.to_string(context.config),
2503             fields_str,
2504             shape.indent.to_string(context.config)
2505         )
2506     } else {
2507         // One liner or visual indent.
2508         format!(" {} ", fields_str)
2509     };
2510
2511     Some(format!("{} {{{}}}", path_str, fields_str))
2512
2513     // FIXME if context.config.struct_lit_style() == Visual, but we run out
2514     // of space, we should fall back to BlockIndent.
2515 }
2516
2517 pub fn struct_lit_field_separator(config: &Config) -> &str {
2518     colon_spaces(
2519         config.space_before_struct_lit_field_colon(),
2520         config.space_after_struct_lit_field_colon(),
2521     )
2522 }
2523
2524 fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> {
2525     let name = &field.ident.node.to_string();
2526     if field.is_shorthand {
2527         Some(name.to_string())
2528     } else {
2529         let separator = struct_lit_field_separator(context.config);
2530         let overhead = name.len() + separator.len();
2531         let mut expr_shape = try_opt!(shape.sub_width(overhead));
2532         expr_shape.offset += overhead;
2533         let expr = field.expr.rewrite(context, expr_shape);
2534
2535         let mut attrs_str = try_opt!((*field.attrs).rewrite(context, shape));
2536         if !attrs_str.is_empty() {
2537             attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2538         };
2539
2540         match expr {
2541             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2542             None => {
2543                 let expr_offset = shape.indent.block_indent(context.config);
2544                 let expr = field.expr.rewrite(
2545                     context,
2546                     Shape::indented(expr_offset, context.config),
2547                 );
2548                 expr.map(|s| {
2549                     format!(
2550                         "{}{}:\n{}{}",
2551                         attrs_str,
2552                         name,
2553                         expr_offset.to_string(&context.config),
2554                         s
2555                     )
2556                 })
2557             }
2558         }
2559     }
2560 }
2561
2562 fn shape_from_fn_call_style(
2563     context: &RewriteContext,
2564     shape: Shape,
2565     overhead: usize,
2566     offset: usize,
2567 ) -> Option<Shape> {
2568     if context.use_block_indent() {
2569         // 1 = ","
2570         shape
2571             .block()
2572             .block_indent(context.config.tab_spaces())
2573             .with_max_width(context.config)
2574             .sub_width(1)
2575     } else {
2576         shape.visual_indent(offset).sub_width(overhead)
2577     }
2578 }
2579
2580 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2581     context: &RewriteContext,
2582     items: &[&T],
2583     span: Span,
2584     shape: Shape,
2585 ) -> Option<String>
2586 where
2587     T: Rewrite + Spanned + ToExpr + 'a,
2588 {
2589     let mut items = items.iter();
2590     // In case of length 1, need a trailing comma
2591     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2592     if items.len() == 1 {
2593         // 3 = "(" + ",)"
2594         let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2595         return items.next().unwrap().rewrite(context, nested_shape).map(
2596             |s| if context.config.spaces_within_parens() {
2597                 format!("( {}, )", s)
2598             } else {
2599                 format!("({},)", s)
2600             },
2601         );
2602     }
2603
2604     let list_lo = context.codemap.span_after(span, "(");
2605     let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2606     let items = itemize_list(
2607         context.codemap,
2608         items,
2609         ")",
2610         |item| item.span().lo,
2611         |item| item.span().hi,
2612         |item| item.rewrite(context, nested_shape),
2613         list_lo,
2614         span.hi - BytePos(1),
2615     );
2616     let list_str = try_opt!(format_item_list(items, nested_shape, context.config));
2617
2618     if context.config.spaces_within_parens() && list_str.len() > 0 {
2619         Some(format!("( {} )", list_str))
2620     } else {
2621         Some(format!("({})", list_str))
2622     }
2623 }
2624
2625 pub fn rewrite_tuple<'a, T>(
2626     context: &RewriteContext,
2627     items: &[&T],
2628     span: Span,
2629     shape: Shape,
2630 ) -> Option<String>
2631 where
2632     T: Rewrite + Spanned + ToExpr + 'a,
2633 {
2634     debug!("rewrite_tuple {:?}", shape);
2635     if context.use_block_indent() {
2636         // We use the same rule as funcation call for rewriting tuple.
2637         rewrite_call_inner(
2638             context,
2639             &String::new(),
2640             items,
2641             span,
2642             shape,
2643             context.config.fn_call_width(),
2644             items.len() == 1,
2645         ).ok()
2646     } else {
2647         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2648     }
2649 }
2650
2651 pub fn rewrite_unary_prefix<R: Rewrite>(
2652     context: &RewriteContext,
2653     prefix: &str,
2654     rewrite: &R,
2655     shape: Shape,
2656 ) -> Option<String> {
2657     rewrite
2658         .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2659         .map(|r| format!("{}{}", prefix, r))
2660 }
2661
2662 // FIXME: this is probably not correct for multi-line Rewrites. we should
2663 // subtract suffix.len() from the last line budget, not the first!
2664 pub fn rewrite_unary_suffix<R: Rewrite>(
2665     context: &RewriteContext,
2666     suffix: &str,
2667     rewrite: &R,
2668     shape: Shape,
2669 ) -> Option<String> {
2670     rewrite
2671         .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2672         .map(|mut r| {
2673             r.push_str(suffix);
2674             r
2675         })
2676 }
2677
2678 fn rewrite_unary_op(
2679     context: &RewriteContext,
2680     op: &ast::UnOp,
2681     expr: &ast::Expr,
2682     shape: Shape,
2683 ) -> Option<String> {
2684     // For some reason, an UnOp is not spanned like BinOp!
2685     let operator_str = match *op {
2686         ast::UnOp::Deref => "*",
2687         ast::UnOp::Not => "!",
2688         ast::UnOp::Neg => "-",
2689     };
2690     rewrite_unary_prefix(context, operator_str, expr, shape)
2691 }
2692
2693 fn rewrite_assignment(
2694     context: &RewriteContext,
2695     lhs: &ast::Expr,
2696     rhs: &ast::Expr,
2697     op: Option<&ast::BinOp>,
2698     shape: Shape,
2699 ) -> Option<String> {
2700     let operator_str = match op {
2701         Some(op) => context.snippet(op.span),
2702         None => "=".to_owned(),
2703     };
2704
2705     // 1 = space between lhs and operator.
2706     let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2707     let lhs_str = format!(
2708         "{} {}",
2709         try_opt!(lhs.rewrite(context, lhs_shape)),
2710         operator_str
2711     );
2712
2713     rewrite_assign_rhs(context, lhs_str, rhs, shape)
2714 }
2715
2716 // The left hand side must contain everything up to, and including, the
2717 // assignment operator.
2718 pub fn rewrite_assign_rhs<S: Into<String>>(
2719     context: &RewriteContext,
2720     lhs: S,
2721     ex: &ast::Expr,
2722     shape: Shape,
2723 ) -> Option<String> {
2724     let mut result = lhs.into();
2725     let last_line_width = last_line_width(&result) -
2726         if result.contains('\n') {
2727             shape.indent.width()
2728         } else {
2729             0
2730         };
2731     // 1 = space between operator and rhs.
2732     let orig_shape = try_opt!(shape.block_indent(0).offset_left(last_line_width + 1));
2733     let rhs = match ex.node {
2734         ast::ExprKind::Mac(ref mac) => {
2735             match rewrite_macro(mac, None, context, orig_shape, MacroPosition::Expression) {
2736                 None if !context.snippet(ex.span).contains("\n") => {
2737                     context.snippet(ex.span).rewrite(context, orig_shape)
2738                 }
2739                 rhs @ _ => rhs,
2740             }
2741         }
2742         _ => ex.rewrite(context, orig_shape),
2743     };
2744
2745     fn count_line_breaks(src: &str) -> usize {
2746         src.chars().filter(|&x| x == '\n').count()
2747     }
2748
2749     match rhs {
2750         Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2751             result.push(' ');
2752             result.push_str(new_str);
2753         }
2754         _ => {
2755             // Expression did not fit on the same line as the identifier or is
2756             // at least three lines big. Try splitting the line and see
2757             // if that works better.
2758             let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2759             let new_rhs = ex.rewrite(context, new_shape);
2760
2761             // FIXME: DRY!
2762             match (rhs, new_rhs) {
2763                 (Some(ref orig_rhs), Some(ref replacement_rhs))
2764                     if count_line_breaks(orig_rhs) > count_line_breaks(replacement_rhs) + 1 => {
2765                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2766                     result.push_str(replacement_rhs);
2767                 }
2768                 (None, Some(ref final_rhs)) => {
2769                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2770                     result.push_str(final_rhs);
2771                 }
2772                 (None, None) => return None,
2773                 (Some(ref orig_rhs), _) => {
2774                     result.push(' ');
2775                     result.push_str(orig_rhs);
2776                 }
2777             }
2778         }
2779     }
2780
2781     Some(result)
2782 }
2783
2784 fn rewrite_expr_addrof(
2785     context: &RewriteContext,
2786     mutability: ast::Mutability,
2787     expr: &ast::Expr,
2788     shape: Shape,
2789 ) -> Option<String> {
2790     let operator_str = match mutability {
2791         ast::Mutability::Immutable => "&",
2792         ast::Mutability::Mutable => "&mut ",
2793     };
2794     rewrite_unary_prefix(context, operator_str, expr, shape)
2795 }
2796
2797 pub trait ToExpr {
2798     fn to_expr(&self) -> Option<&ast::Expr>;
2799     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2800 }
2801
2802 impl ToExpr for ast::Expr {
2803     fn to_expr(&self) -> Option<&ast::Expr> {
2804         Some(self)
2805     }
2806
2807     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2808         can_be_overflowed_expr(context, self, len)
2809     }
2810 }
2811
2812 impl ToExpr for ast::Ty {
2813     fn to_expr(&self) -> Option<&ast::Expr> {
2814         None
2815     }
2816
2817     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2818         can_be_overflowed_type(context, self, len)
2819     }
2820 }
2821
2822 impl<'a> ToExpr for TuplePatField<'a> {
2823     fn to_expr(&self) -> Option<&ast::Expr> {
2824         None
2825     }
2826
2827     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2828         can_be_overflowed_pat(context, self, len)
2829     }
2830 }