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