]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Merge pull request #1732 from olson-sean-k/issue-1377
[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, last_line_extendable};
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 =
1081                 try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
1082
1083             if if_str.contains('\n') || else_str.contains('\n') {
1084                 return None;
1085             }
1086
1087             let result = format!(
1088                 "{} {} {{ {} }} else {{ {} }}",
1089                 self.keyword,
1090                 pat_expr_str,
1091                 if_str,
1092                 else_str
1093             );
1094
1095             if result.len() <= width {
1096                 return Some(result);
1097             }
1098         }
1099
1100         None
1101     }
1102 }
1103
1104 impl<'a> ControlFlow<'a> {
1105     fn rewrite_cond(
1106         &self,
1107         context: &RewriteContext,
1108         shape: Shape,
1109         alt_block_sep: &str,
1110     ) -> Option<(String, usize)> {
1111         let constr_shape = if self.nested_if {
1112             // We are part of an if-elseif-else chain. Our constraints are tightened.
1113             // 7 = "} else " .len()
1114             try_opt!(shape.shrink_left(7))
1115         } else {
1116             shape
1117         };
1118
1119         let label_string = rewrite_label(self.label);
1120         // 1 = space after keyword.
1121         let offset = self.keyword.len() + label_string.len() + 1;
1122
1123         let pat_expr_string = match self.cond {
1124             Some(cond) => {
1125                 let mut cond_shape = match context.config.control_style() {
1126                     Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
1127                     Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
1128                 };
1129                 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1130                     // 2 = " {".len()
1131                     cond_shape = try_opt!(cond_shape.sub_width(2));
1132                 }
1133
1134                 try_opt!(rewrite_pat_expr(
1135                     context,
1136                     self.pat,
1137                     cond,
1138                     self.matcher,
1139                     self.connector,
1140                     self.keyword,
1141                     cond_shape,
1142                 ))
1143             }
1144             None => String::new(),
1145         };
1146
1147         let force_newline_brace = context.config.control_style() == Style::Rfc &&
1148             pat_expr_string.contains('\n') &&
1149             !last_line_extendable(&pat_expr_string);
1150
1151         // Try to format if-else on single line.
1152         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1153             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1154
1155             if let Some(cond_str) = trial {
1156                 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1157                     return Some((cond_str, 0));
1158                 }
1159             }
1160         }
1161
1162         let cond_span = if let Some(cond) = self.cond {
1163             cond.span
1164         } else {
1165             mk_sp(self.block.span.lo, self.block.span.lo)
1166         };
1167
1168         // for event in event
1169         let between_kwd_cond = mk_sp(
1170             context.codemap.span_after(self.span, self.keyword.trim()),
1171             self.pat.map_or(
1172                 cond_span.lo,
1173                 |p| if self.matcher.is_empty() {
1174                     p.span.lo
1175                 } else {
1176                     context.codemap.span_before(self.span, self.matcher.trim())
1177                 },
1178             ),
1179         );
1180
1181         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1182
1183         let after_cond_comment =
1184             extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
1185
1186         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1187             ""
1188         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
1189                    force_newline_brace
1190         {
1191             alt_block_sep
1192         } else {
1193             " "
1194         };
1195
1196         let used_width = if pat_expr_string.contains('\n') {
1197             last_line_width(&pat_expr_string)
1198         } else {
1199             // 2 = spaces after keyword and condition.
1200             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1201         };
1202
1203         Some((
1204             format!(
1205                 "{}{}{}{}{}",
1206                 label_string,
1207                 self.keyword,
1208                 between_kwd_cond_comment.as_ref().map_or(
1209                     if pat_expr_string.is_empty() ||
1210                         pat_expr_string.starts_with('\n')
1211                     {
1212                         ""
1213                     } else {
1214                         " "
1215                     },
1216                     |s| &**s,
1217                 ),
1218                 pat_expr_string,
1219                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1220             ),
1221             used_width,
1222         ))
1223     }
1224 }
1225
1226 impl<'a> Rewrite for ControlFlow<'a> {
1227     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1228         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1229
1230         let alt_block_sep = String::from("\n") +
1231             &shape.indent.block_only().to_string(context.config);
1232         let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
1233         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1234         if used_width == 0 {
1235             return Some(cond_str);
1236         }
1237
1238         let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1239         // This is used only for the empty block case: `{}`. So, we use 1 if we know
1240         // we should avoid the single line case.
1241         let block_width = if self.else_block.is_some() || self.nested_if {
1242             min(1, block_width)
1243         } else {
1244             block_width
1245         };
1246         let block_shape = Shape {
1247             width: block_width,
1248             ..shape
1249         };
1250         let mut block_context = context.clone();
1251         block_context.is_if_else_block = self.else_block.is_some();
1252         let block_str = try_opt!(self.block.rewrite(&block_context, block_shape));
1253
1254         let mut result = format!("{}{}", cond_str, block_str);
1255
1256         if let Some(else_block) = self.else_block {
1257             let shape = Shape::indented(shape.indent, context.config);
1258             let mut last_in_chain = false;
1259             let rewrite = match else_block.node {
1260                 // If the else expression is another if-else expression, prevent it
1261                 // from being formatted on a single line.
1262                 // Note how we're passing the original shape, as the
1263                 // cost of "else" should not cascade.
1264                 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1265                     ControlFlow::new_if(
1266                         cond,
1267                         Some(pat),
1268                         if_block,
1269                         next_else_block.as_ref().map(|e| &**e),
1270                         false,
1271                         true,
1272                         mk_sp(else_block.span.lo, self.span.hi),
1273                     ).rewrite(context, shape)
1274                 }
1275                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1276                     ControlFlow::new_if(
1277                         cond,
1278                         None,
1279                         if_block,
1280                         next_else_block.as_ref().map(|e| &**e),
1281                         false,
1282                         true,
1283                         mk_sp(else_block.span.lo, self.span.hi),
1284                     ).rewrite(context, shape)
1285                 }
1286                 _ => {
1287                     last_in_chain = true;
1288                     // When rewriting a block, the width is only used for single line
1289                     // blocks, passing 1 lets us avoid that.
1290                     let else_shape = Shape {
1291                         width: min(1, shape.width),
1292                         ..shape
1293                     };
1294                     else_block.rewrite(context, else_shape)
1295                 }
1296             };
1297
1298             let between_kwd_else_block = mk_sp(
1299                 self.block.span.hi,
1300                 context
1301                     .codemap
1302                     .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1303             );
1304             let between_kwd_else_block_comment =
1305                 extract_comment(between_kwd_else_block, context, shape);
1306
1307             let after_else = mk_sp(
1308                 context
1309                     .codemap
1310                     .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
1311                 else_block.span.lo,
1312             );
1313             let after_else_comment = extract_comment(after_else, context, shape);
1314
1315             let between_sep = match context.config.control_brace_style() {
1316                 ControlBraceStyle::AlwaysNextLine |
1317                 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1318                 ControlBraceStyle::AlwaysSameLine => " ",
1319             };
1320             let after_sep = match context.config.control_brace_style() {
1321                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1322                 _ => " ",
1323             };
1324             try_opt!(
1325                 write!(
1326                     &mut result,
1327                     "{}else{}",
1328                     between_kwd_else_block_comment
1329                         .as_ref()
1330                         .map_or(between_sep, |s| &**s),
1331                     after_else_comment.as_ref().map_or(after_sep, |s| &**s)
1332                 ).ok()
1333             );
1334             result.push_str(&try_opt!(rewrite));
1335         }
1336
1337         Some(result)
1338     }
1339 }
1340
1341 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1342     match label {
1343         Some(ident) => format!("{}: ", ident.node),
1344         None => "".to_owned(),
1345     }
1346 }
1347
1348 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1349     let comment_str = context.snippet(span);
1350     if contains_comment(&comment_str) {
1351         let comment = try_opt!(rewrite_comment(
1352             comment_str.trim(),
1353             false,
1354             shape,
1355             context.config,
1356         ));
1357         Some(format!(
1358             "\n{indent}{}\n{indent}",
1359             comment,
1360             indent = shape.indent.to_string(context.config)
1361         ))
1362     } else {
1363         None
1364     }
1365 }
1366
1367 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1368     let snippet = codemap.span_to_snippet(block.span).unwrap();
1369     contains_comment(&snippet)
1370 }
1371
1372 // Checks that a block contains no statements, an expression and no comments.
1373 // FIXME: incorrectly returns false when comment is contained completely within
1374 // the expression.
1375 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1376     (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1377          !block_contains_comment(block, codemap))
1378 }
1379
1380 /// Checks whether a block contains at most one statement or expression, and no comments.
1381 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1382     block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1383 }
1384
1385 /// Checks whether a block contains no statements, expressions, or comments.
1386 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1387     block.stmts.is_empty() && !block_contains_comment(block, codemap)
1388 }
1389
1390 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1391     match stmt.node {
1392         ast::StmtKind::Expr(..) => true,
1393         _ => false,
1394     }
1395 }
1396
1397 fn is_unsafe_block(block: &ast::Block) -> bool {
1398     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1399         true
1400     } else {
1401         false
1402     }
1403 }
1404
1405 // inter-match-arm-comment-rules:
1406 //  - all comments following a match arm before the start of the next arm
1407 //    are about the second arm
1408 fn rewrite_match_arm_comment(
1409     context: &RewriteContext,
1410     missed_str: &str,
1411     shape: Shape,
1412     arm_indent_str: &str,
1413 ) -> Option<String> {
1414     // The leading "," is not part of the arm-comment
1415     let missed_str = match missed_str.find_uncommented(",") {
1416         Some(n) => &missed_str[n + 1..],
1417         None => &missed_str[..],
1418     };
1419
1420     let mut result = String::new();
1421     // any text not preceeded by a newline is pushed unmodified to the block
1422     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1423     result.push_str(&missed_str[..first_brk]);
1424     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1425
1426     let first = missed_str
1427         .find(|c: char| !c.is_whitespace())
1428         .unwrap_or(missed_str.len());
1429     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1430         // Excessive vertical whitespace before comment should be preserved
1431         // FIXME handle vertical whitespace better
1432         result.push('\n');
1433     }
1434     let missed_str = missed_str[first..].trim();
1435     if !missed_str.is_empty() {
1436         let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1437         result.push('\n');
1438         result.push_str(arm_indent_str);
1439         result.push_str(&comment);
1440     }
1441
1442     Some(result)
1443 }
1444
1445 fn rewrite_match(
1446     context: &RewriteContext,
1447     cond: &ast::Expr,
1448     arms: &[ast::Arm],
1449     shape: Shape,
1450     span: Span,
1451 ) -> Option<String> {
1452     if arms.is_empty() {
1453         return None;
1454     }
1455
1456     // `match `cond` {`
1457     let cond_shape = match context.config.control_style() {
1458         Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
1459         Style::Rfc => try_opt!(shape.offset_left(8)),
1460     };
1461     let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1462     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1463     let block_sep = match context.config.control_brace_style() {
1464         ControlBraceStyle::AlwaysNextLine => alt_block_sep.as_str(),
1465         _ => " ",
1466     };
1467     let mut result = format!("match {}{}{{", cond_str, block_sep);
1468
1469     let arm_shape = if context.config.indent_match_arms() {
1470         shape.block_indent(context.config.tab_spaces())
1471     } else {
1472         shape.block_indent(0)
1473     };
1474
1475     let arm_indent_str = arm_shape.indent.to_string(context.config);
1476
1477     let open_brace_pos = context
1478         .codemap
1479         .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1480
1481     let arm_num = arms.len();
1482     for (i, arm) in arms.iter().enumerate() {
1483         // Make sure we get the stuff between arms.
1484         let missed_str = if i == 0 {
1485             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1486         } else {
1487             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1488         };
1489         let comment = try_opt!(rewrite_match_arm_comment(
1490             context,
1491             &missed_str,
1492             arm_shape,
1493             &arm_indent_str,
1494         ));
1495         result.push_str(&comment);
1496         result.push('\n');
1497         result.push_str(&arm_indent_str);
1498
1499         let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1500         if let Some(ref arm_str) = arm_str {
1501             // Trim the trailing comma if necessary.
1502             if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
1503                 arm_str.ends_with(',')
1504             {
1505                 result.push_str(&arm_str[0..arm_str.len() - 1])
1506             } else {
1507                 result.push_str(arm_str)
1508             }
1509         } else {
1510             // We couldn't format the arm, just reproduce the source.
1511             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1512             result.push_str(&snippet);
1513             if context.config.trailing_comma() != SeparatorTactic::Never {
1514                 result.push_str(arm_comma(context.config, &arm.body))
1515             }
1516         }
1517     }
1518     // BytePos(1) = closing match brace.
1519     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1520     let last_comment = context.snippet(last_span);
1521     let comment = try_opt!(rewrite_match_arm_comment(
1522         context,
1523         &last_comment,
1524         arm_shape,
1525         &arm_indent_str,
1526     ));
1527     result.push_str(&comment);
1528     result.push('\n');
1529     result.push_str(&shape.indent.to_string(context.config));
1530     result.push('}');
1531     Some(result)
1532 }
1533
1534 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1535     let &ast::Arm {
1536         ref attrs,
1537         ref pats,
1538         ..
1539     } = arm;
1540     if !attrs.is_empty() {
1541         return attrs[0].span.lo;
1542     }
1543
1544     pats[0].span.lo
1545 }
1546
1547 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1548     arm.body.span.hi
1549 }
1550
1551 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1552     if config.match_block_trailing_comma() {
1553         ","
1554     } else if let ast::ExprKind::Block(ref block) = body.node {
1555         if let ast::BlockCheckMode::Default = block.rules {
1556             ""
1557         } else {
1558             ","
1559         }
1560     } else {
1561         ","
1562     }
1563 }
1564
1565 // Match arms.
1566 impl Rewrite for ast::Arm {
1567     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1568         debug!("Arm::rewrite {:?} {:?}", self, shape);
1569         let &ast::Arm {
1570             ref attrs,
1571             ref pats,
1572             ref guard,
1573             ref body,
1574         } = self;
1575
1576         let attr_str = if !attrs.is_empty() {
1577             if contains_skip(attrs) {
1578                 return None;
1579             }
1580             format!(
1581                 "{}\n{}",
1582                 try_opt!(attrs.rewrite(context, shape)),
1583                 shape.indent.to_string(context.config)
1584             )
1585         } else {
1586             String::new()
1587         };
1588
1589         // Patterns
1590         // 5 = ` => {`
1591         let pat_shape = try_opt!(shape.sub_width(5));
1592
1593         let pat_strs = try_opt!(
1594             pats.iter()
1595                 .map(|p| p.rewrite(context, pat_shape))
1596                 .collect::<Option<Vec<_>>>()
1597         );
1598
1599         let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1600         let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1601         let fmt = ListFormatting {
1602             tactic: if all_simple {
1603                 DefinitiveListTactic::Mixed
1604             } else {
1605                 DefinitiveListTactic::Vertical
1606             },
1607             separator: " |",
1608             trailing_separator: SeparatorTactic::Never,
1609             shape: pat_shape,
1610             ends_with_newline: false,
1611             config: context.config,
1612         };
1613         let pats_str = try_opt!(write_list(items, &fmt));
1614
1615         let guard_shape = if pats_str.contains('\n') {
1616             shape.with_max_width(context.config)
1617         } else {
1618             shape
1619         };
1620
1621         let guard_str = try_opt!(rewrite_guard(
1622             context,
1623             guard,
1624             guard_shape,
1625             trimmed_last_line_width(&pats_str),
1626         ));
1627
1628         let pats_str = format!("{}{}", pats_str, guard_str);
1629
1630         let (mut extend, body) = match body.node {
1631             ast::ExprKind::Block(ref block)
1632                 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) &&
1633                        context.config.wrap_match_arms() => {
1634                 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1635                     (false, &**expr)
1636                 } else {
1637                     (false, &**body)
1638                 }
1639             }
1640             ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1641             ast::ExprKind::Closure(..) |
1642             ast::ExprKind::Struct(..) |
1643             ast::ExprKind::Tup(..) => (true, &**body),
1644             _ => (false, &**body),
1645         };
1646         extend &= context.use_block_indent();
1647
1648         let comma = arm_comma(&context.config, body);
1649         let alt_block_sep = String::from("\n") +
1650             &shape.indent.block_only().to_string(context.config);
1651
1652         let pat_width = extra_offset(&pats_str, shape);
1653         // Let's try and get the arm body on the same line as the condition.
1654         // 4 = ` => `.len()
1655         if shape.width > pat_width + comma.len() + 4 {
1656             let arm_shape = shape
1657                 .offset_left(pat_width + 4)
1658                 .unwrap()
1659                 .sub_width(comma.len())
1660                 .unwrap();
1661             let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
1662             let is_block = if let ast::ExprKind::Block(..) = body.node {
1663                 true
1664             } else {
1665                 false
1666             };
1667
1668             match rewrite {
1669                 Some(ref body_str)
1670                     if (!body_str.contains('\n') && body_str.len() <= arm_shape.width) ||
1671                            !context.config.wrap_match_arms() ||
1672                            (extend && first_line_width(body_str) <= arm_shape.width) ||
1673                            is_block => {
1674                     let block_sep = match context.config.control_brace_style() {
1675                         ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1676                         _ => " ",
1677                     };
1678
1679                     return Some(format!(
1680                         "{}{} =>{}{}{}",
1681                         attr_str.trim_left(),
1682                         pats_str,
1683                         block_sep,
1684                         body_str,
1685                         comma
1686                     ));
1687                 }
1688                 _ => {}
1689             }
1690         }
1691
1692         // FIXME: we're doing a second rewrite of the expr; This may not be
1693         // necessary.
1694         let body_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
1695         let next_line_body = try_opt!(nop_block_collapse(
1696             body.rewrite(context, body_shape),
1697             body_shape.width,
1698         ));
1699         let indent_str = shape
1700             .indent
1701             .block_indent(context.config)
1702             .to_string(context.config);
1703         let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1704             if context.config.match_block_trailing_comma() {
1705                 ("{", "},")
1706             } else {
1707                 ("{", "}")
1708             }
1709         } else {
1710             ("", ",")
1711         };
1712
1713
1714         let block_sep = match context.config.control_brace_style() {
1715             ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1716             _ if body_prefix.is_empty() => "\n".to_owned(),
1717             _ => " ".to_owned() + body_prefix + "\n",
1718         };
1719
1720         if context.config.wrap_match_arms() {
1721             Some(format!(
1722                 "{}{} =>{}{}{}\n{}{}",
1723                 attr_str.trim_left(),
1724                 pats_str,
1725                 block_sep,
1726                 indent_str,
1727                 next_line_body,
1728                 shape.indent.to_string(context.config),
1729                 body_suffix
1730             ))
1731         } else {
1732             Some(format!(
1733                 "{}{} =>{}{}{}{}",
1734                 attr_str.trim_left(),
1735                 pats_str,
1736                 block_sep,
1737                 indent_str,
1738                 next_line_body,
1739                 body_suffix
1740             ))
1741         }
1742     }
1743 }
1744
1745 // A pattern is simple if it is very short or it is short-ish and just a path.
1746 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1747 fn pat_is_simple(pat_str: &str) -> bool {
1748     pat_str.len() <= 16 ||
1749         (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1750 }
1751
1752 // The `if ...` guard on a match arm.
1753 fn rewrite_guard(
1754     context: &RewriteContext,
1755     guard: &Option<ptr::P<ast::Expr>>,
1756     shape: Shape,
1757     // The amount of space used up on this line for the pattern in
1758     // the arm (excludes offset).
1759     pattern_width: usize,
1760 ) -> Option<String> {
1761     if let Some(ref guard) = *guard {
1762         // First try to fit the guard string on the same line as the pattern.
1763         // 4 = ` if `, 5 = ` => {`
1764         if let Some(cond_shape) = shape
1765             .shrink_left(pattern_width + 4)
1766             .and_then(|s| s.sub_width(5))
1767         {
1768             if let Some(cond_str) = guard
1769                 .rewrite(context, cond_shape)
1770                 .and_then(|s| s.rewrite(context, cond_shape))
1771             {
1772                 if !cond_str.contains('\n') {
1773                     return Some(format!(" if {}", cond_str));
1774                 }
1775             }
1776         }
1777
1778         // Not enough space to put the guard after the pattern, try a newline.
1779         // 3 == `if `
1780         if let Some(cond_shape) = Shape::indented(
1781             shape.indent.block_indent(context.config) + 3,
1782             context.config,
1783         ).sub_width(3)
1784         {
1785             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1786                 return Some(format!(
1787                     "\n{}if {}",
1788                     shape
1789                         .indent
1790                         .block_indent(context.config)
1791                         .to_string(context.config),
1792                     cond_str
1793                 ));
1794             }
1795         }
1796
1797         None
1798     } else {
1799         Some(String::new())
1800     }
1801 }
1802
1803 fn rewrite_pat_expr(
1804     context: &RewriteContext,
1805     pat: Option<&ast::Pat>,
1806     expr: &ast::Expr,
1807     matcher: &str,
1808     // Connecting piece between pattern and expression,
1809     // *without* trailing space.
1810     connector: &str,
1811     keyword: &str,
1812     shape: Shape,
1813 ) -> Option<String> {
1814     debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1815     let mut pat_string = String::new();
1816     let mut result = match pat {
1817         Some(pat) => {
1818             let matcher = if matcher.is_empty() {
1819                 matcher.to_owned()
1820             } else {
1821                 format!("{} ", matcher)
1822             };
1823             let pat_shape =
1824                 try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
1825             pat_string = try_opt!(pat.rewrite(context, pat_shape));
1826             format!("{}{}{}", matcher, pat_string, connector)
1827         }
1828         None => String::new(),
1829     };
1830
1831     // Consider only the last line of the pat string.
1832     let extra_offset = extra_offset(&result, shape);
1833
1834     // The expression may (partially) fit on the current line.
1835     if shape.width > extra_offset + 1 {
1836         let spacer = if pat.is_some() { " " } else { "" };
1837
1838         let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1839         let expr_rewrite = expr.rewrite(context, expr_shape);
1840
1841         if let Some(expr_string) = expr_rewrite {
1842             if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1843                 result.push_str(spacer);
1844                 result.push_str(&expr_string);
1845                 return Some(result);
1846             }
1847         }
1848     }
1849
1850     if pat.is_none() && keyword == "if" {
1851         return None;
1852     }
1853
1854     let nested_indent = shape.indent.block_only().block_indent(context.config);
1855
1856     // The expression won't fit on the current line, jump to next.
1857     result.push('\n');
1858     result.push_str(&nested_indent.to_string(context.config));
1859
1860     let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1861     result.push_str(&try_opt!(expr_rewrite));
1862
1863     Some(result)
1864 }
1865
1866 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1867     let string_lit = context.snippet(span);
1868
1869     if !context.config.format_strings() && !context.config.force_format_strings() {
1870         if string_lit
1871             .lines()
1872             .rev()
1873             .skip(1)
1874             .all(|line| line.ends_with('\\'))
1875         {
1876             let new_indent = shape.visual_indent(1).indent;
1877             return Some(String::from(
1878                 string_lit
1879                     .lines()
1880                     .map(|line| {
1881                         new_indent.to_string(context.config) + line.trim_left()
1882                     })
1883                     .collect::<Vec<_>>()
1884                     .join("\n")
1885                     .trim_left(),
1886             ));
1887         } else {
1888             return Some(string_lit);
1889         }
1890     }
1891
1892     if !context.config.force_format_strings() &&
1893         !string_requires_rewrite(context, span, &string_lit, shape)
1894     {
1895         return Some(string_lit);
1896     }
1897
1898     let fmt = StringFormat {
1899         opener: "\"",
1900         closer: "\"",
1901         line_start: " ",
1902         line_end: "\\",
1903         shape: shape,
1904         trim_end: false,
1905         config: context.config,
1906     };
1907
1908     // Remove the quote characters.
1909     let str_lit = &string_lit[1..string_lit.len() - 1];
1910
1911     rewrite_string(str_lit, &fmt)
1912 }
1913
1914 fn string_requires_rewrite(
1915     context: &RewriteContext,
1916     span: Span,
1917     string: &str,
1918     shape: Shape,
1919 ) -> bool {
1920     if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1921         return true;
1922     }
1923
1924     for (i, line) in string.lines().enumerate() {
1925         if i == 0 {
1926             if line.len() > shape.width {
1927                 return true;
1928             }
1929         } else {
1930             if line.len() > shape.width + shape.indent.width() {
1931                 return true;
1932             }
1933         }
1934     }
1935
1936     false
1937 }
1938
1939 pub fn rewrite_call_with_binary_search<R>(
1940     context: &RewriteContext,
1941     callee: &R,
1942     args: &[&ast::Expr],
1943     span: Span,
1944     shape: Shape,
1945 ) -> Option<String>
1946 where
1947     R: Rewrite,
1948 {
1949     let closure = |callee_max_width| {
1950         // FIXME using byte lens instead of char lens (and probably all over the
1951         // place too)
1952         let callee_shape = Shape {
1953             width: callee_max_width,
1954             ..shape
1955         };
1956         let callee_str = callee
1957             .rewrite(context, callee_shape)
1958             .ok_or(Ordering::Greater)?;
1959
1960         rewrite_call_inner(
1961             context,
1962             &callee_str,
1963             args,
1964             span,
1965             shape,
1966             context.config.fn_call_width(),
1967             false,
1968         )
1969     };
1970
1971     binary_search(1, shape.width, closure)
1972 }
1973
1974 pub fn rewrite_call(
1975     context: &RewriteContext,
1976     callee: &str,
1977     args: &[ptr::P<ast::Expr>],
1978     span: Span,
1979     shape: Shape,
1980 ) -> Option<String> {
1981     rewrite_call_inner(
1982         context,
1983         &callee,
1984         &args.iter().map(|x| &**x).collect::<Vec<_>>(),
1985         span,
1986         shape,
1987         context.config.fn_call_width(),
1988         false,
1989     ).ok()
1990 }
1991
1992 pub fn rewrite_call_inner<'a, T>(
1993     context: &RewriteContext,
1994     callee_str: &str,
1995     args: &[&T],
1996     span: Span,
1997     shape: Shape,
1998     args_max_width: usize,
1999     force_trailing_comma: bool,
2000 ) -> Result<String, Ordering>
2001 where
2002     T: Rewrite + Spanned + ToExpr + 'a,
2003 {
2004     // 2 = `( `, 1 = `(`
2005     let paren_overhead = if context.config.spaces_within_parens() {
2006         2
2007     } else {
2008         1
2009     };
2010     let used_width = extra_offset(&callee_str, shape);
2011     let one_line_width = shape
2012         .width
2013         .checked_sub(used_width + 2 * paren_overhead)
2014         .ok_or(Ordering::Greater)?;
2015
2016     let nested_shape = shape_from_fn_call_style(
2017         context,
2018         shape,
2019         used_width + 2 * paren_overhead,
2020         used_width + paren_overhead,
2021     ).ok_or(Ordering::Greater)?;
2022
2023     let span_lo = context.codemap.span_after(span, "(");
2024     let args_span = mk_sp(span_lo, span.hi);
2025
2026     let (extendable, list_str) = rewrite_call_args(
2027         context,
2028         args,
2029         args_span,
2030         nested_shape,
2031         one_line_width,
2032         args_max_width,
2033         force_trailing_comma,
2034     ).or_else(|| if context.use_block_indent() {
2035         rewrite_call_args(
2036             context,
2037             args,
2038             args_span,
2039             Shape::indented(
2040                 shape.block().indent.block_indent(context.config),
2041                 context.config,
2042             ),
2043             0,
2044             0,
2045             force_trailing_comma,
2046         )
2047     } else {
2048         None
2049     })
2050         .ok_or(Ordering::Less)?;
2051
2052     if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2053         let mut new_context = context.clone();
2054         new_context.use_block = true;
2055         return rewrite_call_inner(
2056             &new_context,
2057             callee_str,
2058             args,
2059             span,
2060             shape,
2061             args_max_width,
2062             force_trailing_comma,
2063         );
2064     }
2065
2066     let args_shape = shape
2067         .sub_width(last_line_width(&callee_str))
2068         .ok_or(Ordering::Less)?;
2069     Ok(format!(
2070         "{}{}",
2071         callee_str,
2072         wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2073     ))
2074 }
2075
2076 fn need_block_indent(s: &str, shape: Shape) -> bool {
2077     s.lines().skip(1).any(|s| {
2078         s.find(|c| !char::is_whitespace(c))
2079             .map_or(false, |w| w + 1 < shape.indent.width())
2080     })
2081 }
2082
2083 fn rewrite_call_args<'a, T>(
2084     context: &RewriteContext,
2085     args: &[&T],
2086     span: Span,
2087     shape: Shape,
2088     one_line_width: usize,
2089     args_max_width: usize,
2090     force_trailing_comma: bool,
2091 ) -> Option<(bool, String)>
2092 where
2093     T: Rewrite + Spanned + ToExpr + 'a,
2094 {
2095     let mut item_context = context.clone();
2096     item_context.inside_macro = false;
2097     let items = itemize_list(
2098         context.codemap,
2099         args.iter(),
2100         ")",
2101         |item| item.span().lo,
2102         |item| item.span().hi,
2103         |item| item.rewrite(&item_context, shape),
2104         span.lo,
2105         span.hi,
2106     );
2107     let mut item_vec: Vec<_> = items.collect();
2108
2109     // Try letting the last argument overflow to the next line with block
2110     // indentation. If its first line fits on one line with the other arguments,
2111     // we format the function arguments horizontally.
2112     let tactic = try_overflow_last_arg(
2113         &item_context,
2114         &mut item_vec,
2115         &args[..],
2116         shape,
2117         one_line_width,
2118         args_max_width,
2119     );
2120
2121     let fmt = ListFormatting {
2122         tactic: tactic,
2123         separator: ",",
2124         trailing_separator: if force_trailing_comma {
2125             SeparatorTactic::Always
2126         } else if context.inside_macro || !context.use_block_indent() {
2127             SeparatorTactic::Never
2128         } else {
2129             context.config.trailing_comma()
2130         },
2131         shape: shape,
2132         ends_with_newline: false,
2133         config: context.config,
2134     };
2135
2136     write_list(&item_vec, &fmt).map(|args_str| {
2137         (tactic != DefinitiveListTactic::Vertical, args_str)
2138     })
2139 }
2140
2141 fn try_overflow_last_arg<'a, T>(
2142     context: &RewriteContext,
2143     item_vec: &mut Vec<ListItem>,
2144     args: &[&T],
2145     shape: Shape,
2146     one_line_width: usize,
2147     args_max_width: usize,
2148 ) -> DefinitiveListTactic
2149 where
2150     T: Rewrite + Spanned + ToExpr + 'a,
2151 {
2152     let overflow_last = can_be_overflowed(&context, args);
2153
2154     // Replace the last item with its first line to see if it fits with
2155     // first arguments.
2156     let (orig_last, placeholder) = if overflow_last {
2157         let mut context = context.clone();
2158         if let Some(expr) = args[args.len() - 1].to_expr() {
2159             match expr.node {
2160                 ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
2161                 _ => (),
2162             }
2163         }
2164         last_arg_shape(&context, &item_vec, shape, args_max_width)
2165             .map_or((None, None), |arg_shape| {
2166                 rewrite_last_arg_with_overflow(
2167                     &context,
2168                     args,
2169                     &mut item_vec[args.len() - 1],
2170                     arg_shape,
2171                 )
2172             })
2173     } else {
2174         (None, None)
2175     };
2176
2177     let tactic = definitive_tactic(
2178         &*item_vec,
2179         ListTactic::LimitedHorizontalVertical(args_max_width),
2180         one_line_width,
2181     );
2182
2183     // Replace the stub with the full overflowing last argument if the rewrite
2184     // succeeded and its first line fits with the other arguments.
2185     match (overflow_last, tactic, placeholder) {
2186         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2187             item_vec[args.len() - 1].item = placeholder;
2188         }
2189         (true, _, _) => {
2190             item_vec[args.len() - 1].item = orig_last;
2191         }
2192         (false, _, _) => {}
2193     }
2194
2195     tactic
2196 }
2197
2198 fn last_arg_shape(
2199     context: &RewriteContext,
2200     items: &Vec<ListItem>,
2201     shape: Shape,
2202     args_max_width: usize,
2203 ) -> Option<Shape> {
2204     let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2205         acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
2206     });
2207     let max_width = min(args_max_width, shape.width);
2208     let arg_indent = if context.use_block_indent() {
2209         shape.block().indent.block_unindent(context.config)
2210     } else {
2211         shape.block().indent
2212     };
2213     Some(Shape {
2214         width: try_opt!(max_width.checked_sub(overhead)),
2215         indent: arg_indent,
2216         offset: 0,
2217     })
2218 }
2219
2220 // Rewriting closure which is placed at the end of the function call's arg.
2221 // Returns `None` if the reformatted closure 'looks bad'.
2222 fn rewrite_last_closure(
2223     context: &RewriteContext,
2224     expr: &ast::Expr,
2225     shape: Shape,
2226 ) -> Option<String> {
2227     if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2228         let body = match body.node {
2229             ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
2230                 stmt_expr(&block.stmts[0]).unwrap_or(body)
2231             }
2232             _ => body,
2233         };
2234         let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
2235             capture,
2236             fn_decl,
2237             body,
2238             expr.span,
2239             context,
2240             shape,
2241         ));
2242         // If the closure goes multi line before its body, do not overflow the closure.
2243         if prefix.contains('\n') {
2244             return None;
2245         }
2246         let body_shape = try_opt!(shape.offset_left(extra_offset));
2247         // When overflowing the closure which consists of a single control flow expression,
2248         // force to use block if its condition uses multi line.
2249         if rewrite_cond(context, body, body_shape)
2250             .map(|cond| cond.contains('\n'))
2251             .unwrap_or(false)
2252         {
2253             return rewrite_closure_with_block(context, body_shape, &prefix, body);
2254         }
2255
2256         // Seems fine, just format the closure in usual manner.
2257         return expr.rewrite(context, shape);
2258     }
2259     None
2260 }
2261
2262 fn rewrite_last_arg_with_overflow<'a, T>(
2263     context: &RewriteContext,
2264     args: &[&T],
2265     last_item: &mut ListItem,
2266     shape: Shape,
2267 ) -> (Option<String>, Option<String>)
2268 where
2269     T: Rewrite + Spanned + ToExpr + 'a,
2270 {
2271     let last_arg = args[args.len() - 1];
2272     let rewrite = if let Some(expr) = last_arg.to_expr() {
2273         match expr.node {
2274             // When overflowing the closure which consists of a single control flow expression,
2275             // force to use block if its condition uses multi line.
2276             ast::ExprKind::Closure(..) => {
2277                 // If the argument consists of multiple closures, we do not overflow
2278                 // the last closure.
2279                 if args.len() > 1 &&
2280                     args.iter()
2281                         .rev()
2282                         .skip(1)
2283                         .filter_map(|arg| arg.to_expr())
2284                         .any(|expr| match expr.node {
2285                             ast::ExprKind::Closure(..) => true,
2286                             _ => false,
2287                         }) {
2288                     None
2289                 } else {
2290                     rewrite_last_closure(context, expr, shape)
2291                 }
2292             }
2293             _ => expr.rewrite(context, shape),
2294         }
2295     } else {
2296         last_arg.rewrite(context, shape)
2297     };
2298     let orig_last = last_item.item.clone();
2299
2300     if let Some(rewrite) = rewrite {
2301         let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2302         last_item.item = rewrite_first_line;
2303         (orig_last, Some(rewrite))
2304     } else {
2305         (orig_last, None)
2306     }
2307 }
2308
2309 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2310 where
2311     T: Rewrite + Spanned + ToExpr + 'a,
2312 {
2313     args.last()
2314         .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2315 }
2316
2317 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2318     match expr.node {
2319         ast::ExprKind::Match(..) => {
2320             (context.use_block_indent() && args_len == 1) ||
2321                 (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2322         }
2323         ast::ExprKind::If(..) |
2324         ast::ExprKind::IfLet(..) |
2325         ast::ExprKind::ForLoop(..) |
2326         ast::ExprKind::Loop(..) |
2327         ast::ExprKind::While(..) |
2328         ast::ExprKind::WhileLet(..) => {
2329             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2330         }
2331         ast::ExprKind::Block(..) |
2332         ast::ExprKind::Closure(..) => {
2333             context.use_block_indent() ||
2334                 context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2335         }
2336         ast::ExprKind::Call(..) |
2337         ast::ExprKind::MethodCall(..) |
2338         ast::ExprKind::Mac(..) |
2339         ast::ExprKind::Struct(..) |
2340         ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2341         ast::ExprKind::AddrOf(_, ref expr) |
2342         ast::ExprKind::Box(ref expr) |
2343         ast::ExprKind::Try(ref expr) |
2344         ast::ExprKind::Unary(_, ref expr) |
2345         ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2346         _ => false,
2347     }
2348 }
2349
2350 fn paren_overhead(context: &RewriteContext) -> usize {
2351     if context.config.spaces_within_parens() {
2352         4
2353     } else {
2354         2
2355     }
2356 }
2357
2358 pub fn wrap_args_with_parens(
2359     context: &RewriteContext,
2360     args_str: &str,
2361     is_extendable: bool,
2362     shape: Shape,
2363     nested_shape: Shape,
2364 ) -> String {
2365     if !context.use_block_indent() ||
2366         (context.inside_macro && !args_str.contains('\n') &&
2367              args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2368     {
2369         if context.config.spaces_within_parens() && args_str.len() > 0 {
2370             format!("( {} )", args_str)
2371         } else {
2372             format!("({})", args_str)
2373         }
2374     } else {
2375         format!(
2376             "(\n{}{}\n{})",
2377             nested_shape.indent.to_string(context.config),
2378             args_str,
2379             shape.block().indent.to_string(context.config)
2380         )
2381     }
2382 }
2383
2384 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2385     debug!("rewrite_paren, shape: {:?}", shape);
2386     let paren_overhead = paren_overhead(context);
2387     let sub_shape = try_opt!(shape.sub_width(paren_overhead / 2)).visual_indent(paren_overhead / 2);
2388
2389     let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
2390         format!("( {} )", s)
2391     } else {
2392         format!("({})", s)
2393     };
2394
2395     let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2396     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2397
2398     if subexpr_str.contains('\n') {
2399         Some(paren_wrapper(&subexpr_str))
2400     } else {
2401         if subexpr_str.len() + paren_overhead <= shape.width {
2402             Some(paren_wrapper(&subexpr_str))
2403         } else {
2404             let sub_shape = try_opt!(shape.offset_left(2));
2405             let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
2406             Some(paren_wrapper(&subexpr_str))
2407         }
2408     }
2409 }
2410
2411 fn rewrite_index(
2412     expr: &ast::Expr,
2413     index: &ast::Expr,
2414     context: &RewriteContext,
2415     shape: Shape,
2416 ) -> Option<String> {
2417     let expr_str = try_opt!(expr.rewrite(context, shape));
2418
2419     let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2420         ("[ ", " ]")
2421     } else {
2422         ("[", "]")
2423     };
2424
2425     let offset = expr_str.len() + lbr.len();
2426     if let Some(index_shape) = shape.visual_indent(offset).sub_width(offset + rbr.len()) {
2427         if let Some(index_str) = index.rewrite(context, index_shape) {
2428             return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2429         }
2430     }
2431
2432     let indent = shape.indent.block_indent(&context.config);
2433     let indent = indent.to_string(&context.config);
2434     // FIXME this is not right, since we don't take into account that shape.width
2435     // might be reduced from max_width by something on the right.
2436     let budget = try_opt!(
2437         context
2438             .config
2439             .max_width()
2440             .checked_sub(indent.len() + lbr.len() + rbr.len())
2441     );
2442     let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
2443     Some(format!(
2444         "{}\n{}{}{}{}",
2445         expr_str,
2446         indent,
2447         lbr,
2448         index_str,
2449         rbr
2450     ))
2451 }
2452
2453 fn rewrite_struct_lit<'a>(
2454     context: &RewriteContext,
2455     path: &ast::Path,
2456     fields: &'a [ast::Field],
2457     base: Option<&'a ast::Expr>,
2458     span: Span,
2459     shape: Shape,
2460 ) -> Option<String> {
2461     debug!("rewrite_struct_lit: shape {:?}", shape);
2462
2463     enum StructLitField<'a> {
2464         Regular(&'a ast::Field),
2465         Base(&'a ast::Expr),
2466     }
2467
2468     // 2 = " {".len()
2469     let path_shape = try_opt!(shape.sub_width(2));
2470     let path_str = try_opt!(rewrite_path(
2471         context,
2472         PathContext::Expr,
2473         None,
2474         path,
2475         path_shape,
2476     ));
2477
2478     if fields.len() == 0 && base.is_none() {
2479         return Some(format!("{} {{}}", path_str));
2480     }
2481
2482     let field_iter = fields
2483         .into_iter()
2484         .map(StructLitField::Regular)
2485         .chain(base.into_iter().map(StructLitField::Base));
2486
2487     // Foo { a: Foo } - indent is +3, width is -5.
2488     let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
2489
2490     let span_lo = |item: &StructLitField| match *item {
2491         StructLitField::Regular(field) => field.span.lo,
2492         StructLitField::Base(expr) => {
2493             let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
2494             let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
2495             let pos = snippet.find_uncommented("..").unwrap();
2496             last_field_hi + BytePos(pos as u32)
2497         }
2498     };
2499     let span_hi = |item: &StructLitField| match *item {
2500         StructLitField::Regular(field) => field.span.hi,
2501         StructLitField::Base(expr) => expr.span.hi,
2502     };
2503     let rewrite = |item: &StructLitField| match *item {
2504         StructLitField::Regular(field) => {
2505             // The 1 taken from the v_budget is for the comma.
2506             rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
2507         }
2508         StructLitField::Base(expr) => {
2509             // 2 = ..
2510             expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
2511                 .map(|s| format!("..{}", s))
2512         }
2513     };
2514
2515     let items = itemize_list(
2516         context.codemap,
2517         field_iter,
2518         "}",
2519         span_lo,
2520         span_hi,
2521         rewrite,
2522         context.codemap.span_after(span, "{"),
2523         span.hi,
2524     );
2525     let item_vec = items.collect::<Vec<_>>();
2526
2527     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2528     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2529     let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2530
2531     let fields_str = try_opt!(write_list(&item_vec, &fmt));
2532     let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
2533         (fields_str.contains('\n') ||
2534              context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
2535              fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0))
2536     {
2537         format!(
2538             "\n{}{}\n{}",
2539             v_shape.indent.to_string(context.config),
2540             fields_str,
2541             shape.indent.to_string(context.config)
2542         )
2543     } else {
2544         // One liner or visual indent.
2545         format!(" {} ", fields_str)
2546     };
2547
2548     Some(format!("{} {{{}}}", path_str, fields_str))
2549
2550     // FIXME if context.config.struct_lit_style() == Visual, but we run out
2551     // of space, we should fall back to BlockIndent.
2552 }
2553
2554 pub fn struct_lit_field_separator(config: &Config) -> &str {
2555     colon_spaces(
2556         config.space_before_struct_lit_field_colon(),
2557         config.space_after_struct_lit_field_colon(),
2558     )
2559 }
2560
2561 fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> {
2562     let name = &field.ident.node.to_string();
2563     if field.is_shorthand {
2564         Some(name.to_string())
2565     } else {
2566         let separator = struct_lit_field_separator(context.config);
2567         let overhead = name.len() + separator.len();
2568         let mut expr_shape = try_opt!(shape.sub_width(overhead));
2569         expr_shape.offset += overhead;
2570         let expr = field.expr.rewrite(context, expr_shape);
2571
2572         let mut attrs_str = try_opt!((*field.attrs).rewrite(context, shape));
2573         if !attrs_str.is_empty() {
2574             attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2575         };
2576
2577         match expr {
2578             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2579             None => {
2580                 let expr_offset = shape.indent.block_indent(context.config);
2581                 let expr = field
2582                     .expr
2583                     .rewrite(context, Shape::indented(expr_offset, context.config));
2584                 expr.map(|s| {
2585                     format!(
2586                         "{}{}:\n{}{}",
2587                         attrs_str,
2588                         name,
2589                         expr_offset.to_string(&context.config),
2590                         s
2591                     )
2592                 })
2593             }
2594         }
2595     }
2596 }
2597
2598 fn shape_from_fn_call_style(
2599     context: &RewriteContext,
2600     shape: Shape,
2601     overhead: usize,
2602     offset: usize,
2603 ) -> Option<Shape> {
2604     if context.use_block_indent() {
2605         // 1 = ","
2606         shape
2607             .block()
2608             .block_indent(context.config.tab_spaces())
2609             .with_max_width(context.config)
2610             .sub_width(1)
2611     } else {
2612         shape.visual_indent(offset).sub_width(overhead)
2613     }
2614 }
2615
2616 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2617     context: &RewriteContext,
2618     items: &[&T],
2619     span: Span,
2620     shape: Shape,
2621 ) -> Option<String>
2622 where
2623     T: Rewrite + Spanned + ToExpr + 'a,
2624 {
2625     let mut items = items.iter();
2626     // In case of length 1, need a trailing comma
2627     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2628     if items.len() == 1 {
2629         // 3 = "(" + ",)"
2630         let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2631         return items.next().unwrap().rewrite(context, nested_shape).map(
2632             |s| if context.config.spaces_within_parens() {
2633                 format!("( {}, )", s)
2634             } else {
2635                 format!("({},)", s)
2636             },
2637         );
2638     }
2639
2640     let list_lo = context.codemap.span_after(span, "(");
2641     let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2642     let items = itemize_list(
2643         context.codemap,
2644         items,
2645         ")",
2646         |item| item.span().lo,
2647         |item| item.span().hi,
2648         |item| item.rewrite(context, nested_shape),
2649         list_lo,
2650         span.hi - BytePos(1),
2651     );
2652     let list_str = try_opt!(format_item_list(items, nested_shape, context.config));
2653
2654     if context.config.spaces_within_parens() && list_str.len() > 0 {
2655         Some(format!("( {} )", list_str))
2656     } else {
2657         Some(format!("({})", list_str))
2658     }
2659 }
2660
2661 pub fn rewrite_tuple<'a, T>(
2662     context: &RewriteContext,
2663     items: &[&T],
2664     span: Span,
2665     shape: Shape,
2666 ) -> Option<String>
2667 where
2668     T: Rewrite + Spanned + ToExpr + 'a,
2669 {
2670     debug!("rewrite_tuple {:?}", shape);
2671     if context.use_block_indent() {
2672         // We use the same rule as funcation call for rewriting tuple.
2673         rewrite_call_inner(
2674             context,
2675             &String::new(),
2676             items,
2677             span,
2678             shape,
2679             context.config.fn_call_width(),
2680             items.len() == 1,
2681         ).ok()
2682     } else {
2683         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2684     }
2685 }
2686
2687 pub fn rewrite_unary_prefix<R: Rewrite>(
2688     context: &RewriteContext,
2689     prefix: &str,
2690     rewrite: &R,
2691     shape: Shape,
2692 ) -> Option<String> {
2693     rewrite
2694         .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2695         .map(|r| format!("{}{}", prefix, r))
2696 }
2697
2698 // FIXME: this is probably not correct for multi-line Rewrites. we should
2699 // subtract suffix.len() from the last line budget, not the first!
2700 pub fn rewrite_unary_suffix<R: Rewrite>(
2701     context: &RewriteContext,
2702     suffix: &str,
2703     rewrite: &R,
2704     shape: Shape,
2705 ) -> Option<String> {
2706     rewrite
2707         .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2708         .map(|mut r| {
2709             r.push_str(suffix);
2710             r
2711         })
2712 }
2713
2714 fn rewrite_unary_op(
2715     context: &RewriteContext,
2716     op: &ast::UnOp,
2717     expr: &ast::Expr,
2718     shape: Shape,
2719 ) -> Option<String> {
2720     // For some reason, an UnOp is not spanned like BinOp!
2721     let operator_str = match *op {
2722         ast::UnOp::Deref => "*",
2723         ast::UnOp::Not => "!",
2724         ast::UnOp::Neg => "-",
2725     };
2726     rewrite_unary_prefix(context, operator_str, expr, shape)
2727 }
2728
2729 fn rewrite_assignment(
2730     context: &RewriteContext,
2731     lhs: &ast::Expr,
2732     rhs: &ast::Expr,
2733     op: Option<&ast::BinOp>,
2734     shape: Shape,
2735 ) -> Option<String> {
2736     let operator_str = match op {
2737         Some(op) => context.snippet(op.span),
2738         None => "=".to_owned(),
2739     };
2740
2741     // 1 = space between lhs and operator.
2742     let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2743     let lhs_str = format!(
2744         "{} {}",
2745         try_opt!(lhs.rewrite(context, lhs_shape)),
2746         operator_str
2747     );
2748
2749     rewrite_assign_rhs(context, lhs_str, rhs, shape)
2750 }
2751
2752 // The left hand side must contain everything up to, and including, the
2753 // assignment operator.
2754 pub fn rewrite_assign_rhs<S: Into<String>>(
2755     context: &RewriteContext,
2756     lhs: S,
2757     ex: &ast::Expr,
2758     shape: Shape,
2759 ) -> Option<String> {
2760     let mut result = lhs.into();
2761     let last_line_width = last_line_width(&result) -
2762         if result.contains('\n') {
2763             shape.indent.width()
2764         } else {
2765             0
2766         };
2767     // 1 = space between operator and rhs.
2768     let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
2769     let rhs = ex.rewrite(context, orig_shape);
2770
2771     fn count_line_breaks(src: &str) -> usize {
2772         src.chars().filter(|&x| x == '\n').count()
2773     }
2774
2775     match rhs {
2776         Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2777             result.push(' ');
2778             result.push_str(new_str);
2779         }
2780         _ => {
2781             // Expression did not fit on the same line as the identifier or is
2782             // at least three lines big. Try splitting the line and see
2783             // if that works better.
2784             let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2785             let new_rhs = ex.rewrite(context, new_shape);
2786
2787             // FIXME: DRY!
2788             match (rhs, new_rhs) {
2789                 (Some(ref orig_rhs), Some(ref replacement_rhs))
2790                     if count_line_breaks(orig_rhs) > count_line_breaks(replacement_rhs) + 1 => {
2791                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2792                     result.push_str(replacement_rhs);
2793                 }
2794                 (None, Some(ref final_rhs)) => {
2795                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2796                     result.push_str(final_rhs);
2797                 }
2798                 (None, None) => return None,
2799                 (Some(ref orig_rhs), _) => {
2800                     result.push(' ');
2801                     result.push_str(orig_rhs);
2802                 }
2803             }
2804         }
2805     }
2806
2807     Some(result)
2808 }
2809
2810 fn rewrite_expr_addrof(
2811     context: &RewriteContext,
2812     mutability: ast::Mutability,
2813     expr: &ast::Expr,
2814     shape: Shape,
2815 ) -> Option<String> {
2816     let operator_str = match mutability {
2817         ast::Mutability::Immutable => "&",
2818         ast::Mutability::Mutable => "&mut ",
2819     };
2820     rewrite_unary_prefix(context, operator_str, expr, shape)
2821 }
2822
2823 pub trait ToExpr {
2824     fn to_expr(&self) -> Option<&ast::Expr>;
2825     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2826 }
2827
2828 impl ToExpr for ast::Expr {
2829     fn to_expr(&self) -> Option<&ast::Expr> {
2830         Some(self)
2831     }
2832
2833     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2834         can_be_overflowed_expr(context, self, len)
2835     }
2836 }
2837
2838 impl ToExpr for ast::Ty {
2839     fn to_expr(&self) -> Option<&ast::Expr> {
2840         None
2841     }
2842
2843     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2844         can_be_overflowed_type(context, self, len)
2845     }
2846 }
2847
2848 impl<'a> ToExpr for TuplePatField<'a> {
2849     fn to_expr(&self) -> Option<&ast::Expr> {
2850         None
2851     }
2852
2853     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2854         can_be_overflowed_pat(context, self, len)
2855     }
2856 }