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