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