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