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