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