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