]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
ad0d654175de754dfe63e31398fac441ed214962
[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::{Ordering, min};
12 use std::mem::swap;
13 use std::ops::Deref;
14 use std::iter::ExactSizeIterator;
15 use std::fmt::Write;
16
17 use {Indent, Shape, Spanned};
18 use codemap::SpanUtils;
19 use rewrite::{Rewrite, RewriteContext};
20 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
21             DefinitiveListTactic, definitive_tactic, ListItem, format_item_list, struct_lit_shape,
22             struct_lit_tactic, shape_for_tactic, struct_lit_formatting};
23 use string::{StringFormat, rewrite_string};
24 use utils::{extra_offset, last_line_width, wrap_str, binary_search, first_line_width,
25             semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr,
26             colon_spaces};
27 use visitor::FmtVisitor;
28 use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle, Style};
29 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
30 use types::{rewrite_path, PathContext};
31 use items::{span_lo_for_arg, span_hi_for_arg};
32 use chains::rewrite_chain;
33 use macros::{rewrite_macro, MacroPosition};
34
35 use syntax::{ast, ptr};
36 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
37 use syntax::parse::classify;
38
39 impl Rewrite for ast::Expr {
40     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
41         format_expr(self, ExprType::SubExpression, context, shape)
42     }
43 }
44
45 #[derive(PartialEq)]
46 enum ExprType {
47     Statement,
48     SubExpression,
49 }
50
51 fn format_expr(expr: &ast::Expr,
52                expr_type: ExprType,
53                context: &RewriteContext,
54                shape: Shape)
55                -> Option<String> {
56     let result = match expr.node {
57         ast::ExprKind::Array(ref expr_vec) => {
58             rewrite_array(expr_vec.iter().map(|e| &**e),
59                           mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
60                           context,
61                           shape)
62         }
63         ast::ExprKind::Lit(ref l) => {
64             match l.node {
65                 ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
66                     rewrite_string_lit(context, l.span, shape)
67                 }
68                 _ => {
69                     wrap_str(context.snippet(expr.span),
70                              context.config.max_width(),
71                              shape)
72                 }
73             }
74         }
75         ast::ExprKind::Call(ref callee, ref args) => {
76             let inner_span = mk_sp(callee.span.hi, expr.span.hi);
77             rewrite_call(context, &**callee, args, inner_span, shape)
78         }
79         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
80         ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
81             // FIXME: format comments between operands and operator
82             rewrite_pair(&**lhs,
83                          &**rhs,
84                          "",
85                          &format!(" {} ", context.snippet(op.span)),
86                          "",
87                          context,
88                          shape)
89         }
90         ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
91         ast::ExprKind::Struct(ref path, ref fields, ref base) => {
92             rewrite_struct_lit(context,
93                                path,
94                                fields,
95                                base.as_ref().map(|e| &**e),
96                                expr.span,
97                                shape)
98         }
99         ast::ExprKind::Tup(ref items) => rewrite_tuple(context, items, expr.span, shape),
100         ast::ExprKind::While(ref cond, ref block, label) => {
101             ControlFlow::new_while(None, cond, block, label, expr.span).rewrite(context, shape)
102         }
103         ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => {
104             ControlFlow::new_while(Some(pat), cond, block, label, expr.span).rewrite(context, shape)
105         }
106         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
107             ControlFlow::new_for(pat, cond, block, label, expr.span).rewrite(context, shape)
108         }
109         ast::ExprKind::Loop(ref block, label) => {
110             ControlFlow::new_loop(block, label, expr.span).rewrite(context, shape)
111         }
112         ast::ExprKind::Block(ref block) => block.rewrite(context, shape),
113         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
114             ControlFlow::new_if(cond,
115                                 None,
116                                 if_block,
117                                 else_block.as_ref().map(|e| &**e),
118                                 expr_type == ExprType::SubExpression,
119                                 false,
120                                 expr.span)
121                 .rewrite(context, shape)
122         }
123         ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
124             ControlFlow::new_if(cond,
125                                 Some(pat),
126                                 if_block,
127                                 else_block.as_ref().map(|e| &**e),
128                                 expr_type == ExprType::SubExpression,
129                                 false,
130                                 expr.span)
131                 .rewrite(context, shape)
132         }
133         ast::ExprKind::Match(ref cond, ref arms) => {
134             rewrite_match(context, cond, arms, shape, expr.span)
135         }
136         ast::ExprKind::Path(ref qself, ref path) => {
137             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
138         }
139         ast::ExprKind::Assign(ref lhs, ref rhs) => {
140             rewrite_assignment(context, lhs, rhs, None, shape)
141         }
142         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
143             rewrite_assignment(context, lhs, rhs, Some(op), shape)
144         }
145         ast::ExprKind::Continue(ref opt_ident) => {
146             let id_str = match *opt_ident {
147                 Some(ident) => format!(" {}", ident.node),
148                 None => String::new(),
149             };
150             wrap_str(format!("continue{}", id_str),
151                      context.config.max_width(),
152                      shape)
153         }
154         ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
155             let id_str = match *opt_ident {
156                 Some(ident) => format!(" {}", ident.node),
157                 None => String::new(),
158             };
159
160             if let Some(ref expr) = *opt_expr {
161                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
162             } else {
163                 wrap_str(format!("break{}", id_str),
164                          context.config.max_width(),
165                          shape)
166             }
167         }
168         ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
169             rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
170         }
171         ast::ExprKind::Try(..) |
172         ast::ExprKind::Field(..) |
173         ast::ExprKind::TupField(..) |
174         ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
175         ast::ExprKind::Mac(ref mac) => {
176             // Failure to rewrite a marco should not imply failure to
177             // rewrite the expression.
178             rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
179                 wrap_str(context.snippet(expr.span),
180                          context.config.max_width(),
181                          shape)
182             })
183         }
184         ast::ExprKind::Ret(None) => {
185             wrap_str("return".to_owned(), context.config.max_width(), shape)
186         }
187         ast::ExprKind::Ret(Some(ref expr)) => {
188             rewrite_unary_prefix(context, "return ", &**expr, shape)
189         }
190         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
191         ast::ExprKind::AddrOf(mutability, ref expr) => {
192             rewrite_expr_addrof(context, mutability, expr, shape)
193         }
194         ast::ExprKind::Cast(ref expr, ref ty) => {
195             rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
196         }
197         ast::ExprKind::Type(ref expr, ref ty) => {
198             rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
199         }
200         ast::ExprKind::Index(ref expr, ref index) => {
201             rewrite_index(&**expr, &**index, context, shape)
202         }
203         ast::ExprKind::Repeat(ref expr, ref repeats) => {
204             let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
205                 ("[ ", " ]")
206             } else {
207                 ("[", "]")
208             };
209             rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
210         }
211         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
212             let delim = match limits {
213                 ast::RangeLimits::HalfOpen => "..",
214                 ast::RangeLimits::Closed => "...",
215             };
216
217             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
218                 (Some(ref lhs), Some(ref rhs)) => {
219                     let sp_delim = if context.config.spaces_around_ranges() {
220                         format!(" {} ", delim)
221                     } else {
222                         delim.into()
223                     };
224                     rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
225                 }
226                 (None, Some(ref rhs)) => {
227                     let sp_delim = if context.config.spaces_around_ranges() {
228                         format!("{} ", delim)
229                     } else {
230                         delim.into()
231                     };
232                     rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
233                 }
234                 (Some(ref lhs), None) => {
235                     let sp_delim = if context.config.spaces_around_ranges() {
236                         format!(" {}", delim)
237                     } else {
238                         delim.into()
239                     };
240                     rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
241                 }
242                 (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
243             }
244         }
245         // We do not format these expressions yet, but they should still
246         // satisfy our width restrictions.
247         ast::ExprKind::InPlace(..) |
248         ast::ExprKind::InlineAsm(..) => {
249             wrap_str(context.snippet(expr.span),
250                      context.config.max_width(),
251                      shape)
252         }
253     };
254     result.and_then(|res| recover_comment_removed(res, expr.span, context, shape))
255 }
256
257 pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
258                               rhs: &RHS,
259                               prefix: &str,
260                               infix: &str,
261                               suffix: &str,
262                               context: &RewriteContext,
263                               shape: Shape)
264                               -> Option<String>
265     where LHS: Rewrite,
266           RHS: Rewrite
267 {
268     // Get "full width" rhs and see if it fits on the current line. This
269     // usually works fairly well since it tends to place operands of
270     // operations with high precendence close together.
271     // Note that this is non-conservative, but its just to see if it's even
272     // worth trying to put everything on one line.
273     let rhs_shape = try_opt!(shape.sub_width(suffix.len()));
274     let rhs_result = rhs.rewrite(context, rhs_shape);
275
276     if let Some(rhs_result) = rhs_result {
277         // This is needed in case of line break not caused by a
278         // shortage of space, but by end-of-line comments, for example.
279         if !rhs_result.contains('\n') {
280             let lhs_shape = try_opt!(shape.sub_width(prefix.len() + infix.len()));
281             let lhs_result = lhs.rewrite(context, lhs_shape);
282             if let Some(lhs_result) = lhs_result {
283                 let mut result = format!("{}{}{}", prefix, lhs_result, infix);
284
285                 let remaining_width = shape
286                     .width
287                     .checked_sub(last_line_width(&result) + suffix.len())
288                     .unwrap_or(0);
289
290                 if rhs_result.len() <= remaining_width {
291                     result.push_str(&rhs_result);
292                     result.push_str(suffix);
293                     return Some(result);
294                 }
295
296                 // Try rewriting the rhs into the remaining space.
297                 let rhs_shape = shape.shrink_left(last_line_width(&result) + suffix.len());
298                 if let Some(rhs_shape) = rhs_shape {
299                     if let Some(rhs_result) = rhs.rewrite(context, rhs_shape) {
300                         // FIXME this should always hold.
301                         if rhs_result.len() <= remaining_width {
302                             result.push_str(&rhs_result);
303                             result.push_str(suffix);
304                             return Some(result);
305                         }
306                     }
307                 }
308             }
309         }
310     }
311
312     // We have to use multiple lines.
313
314     // Re-evaluate the rhs because we have more space now:
315     let infix = infix.trim_right();
316     let lhs_budget = try_opt!(context
317                                   .config
318                                   .max_width()
319                                   .checked_sub(shape.used_width() + prefix.len() +
320                                                infix.len()));
321     let rhs_shape = match context.config.control_style() {
322         Style::Default => {
323             try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
324         }
325         Style::Rfc => try_opt!(shape.block_left(context.config.tab_spaces())),
326     };
327
328     let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
329     let lhs_result = try_opt!(lhs.rewrite(context,
330                                           Shape {
331                                               width: lhs_budget,
332                                               ..shape
333                                           }));
334     Some(format!("{}{}{}\n{}{}{}",
335                  prefix,
336                  lhs_result,
337                  infix,
338                  rhs_shape.indent.to_string(context.config),
339                  rhs_result,
340                  suffix))
341 }
342
343 pub fn rewrite_array<'a, I>(expr_iter: I,
344                             span: Span,
345                             context: &RewriteContext,
346                             shape: Shape)
347                             -> Option<String>
348     where I: Iterator<Item = &'a ast::Expr>
349 {
350     let bracket_size = if context.config.spaces_within_square_brackets() {
351         2 // "[ "
352     } else {
353         1 // "["
354     };
355
356     let nested_shape = match context.config.array_layout() {
357         IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
358         IndentStyle::Visual => {
359             try_opt!(shape
360                          .visual_indent(bracket_size)
361                          .sub_width(bracket_size * 2))
362         }
363     };
364
365     let items = itemize_list(context.codemap,
366                              expr_iter,
367                              "]",
368                              |item| item.span.lo,
369                              |item| item.span.hi,
370                              |item| item.rewrite(context, nested_shape),
371                              span.lo,
372                              span.hi)
373         .collect::<Vec<_>>();
374
375     if items.is_empty() {
376         if context.config.spaces_within_square_brackets() {
377             return Some("[ ]".to_string());
378         } else {
379             return Some("[]".to_string());
380         }
381     }
382
383     let has_long_item = try_opt!(items
384                                      .iter()
385                                      .map(|li| li.item.as_ref().map(|s| s.len() > 10))
386                                      .fold(Some(false),
387                                            |acc, x| acc.and_then(|y| x.map(|x| x || y))));
388
389     let tactic = match context.config.array_layout() {
390         IndentStyle::Block => {
391             // FIXME wrong shape in one-line case
392             match shape.width.checked_sub(2 * bracket_size) {
393                 Some(width) => {
394                     let tactic =
395                         ListTactic::LimitedHorizontalVertical(context.config.array_width());
396                     definitive_tactic(&items, tactic, width)
397                 }
398                 None => DefinitiveListTactic::Vertical,
399             }
400         }
401         IndentStyle::Visual => {
402             if has_long_item || items.iter().any(ListItem::is_multiline) {
403                 definitive_tactic(&items,
404                                   ListTactic::LimitedHorizontalVertical(context
405                                                                             .config
406                                                                             .array_width()),
407                                   nested_shape.width)
408             } else {
409                 DefinitiveListTactic::Mixed
410             }
411         }
412     };
413
414     let fmt = ListFormatting {
415         tactic: tactic,
416         separator: ",",
417         trailing_separator: SeparatorTactic::Never,
418         shape: nested_shape,
419         ends_with_newline: false,
420         config: context.config,
421     };
422     let list_str = try_opt!(write_list(&items, &fmt));
423
424     let result = if context.config.array_layout() == IndentStyle::Visual ||
425                     tactic != DefinitiveListTactic::Vertical {
426         if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
427             format!("[ {} ]", list_str)
428         } else {
429             format!("[{}]", list_str)
430         }
431     } else {
432         format!("[\n{}{},\n{}]",
433                 nested_shape.indent.to_string(context.config),
434                 list_str,
435                 shape.block().indent.to_string(context.config))
436     };
437
438     Some(result)
439 }
440
441 // This functions is pretty messy because of the rules around closures and blocks:
442 // FIXME - the below is probably no longer true in full.
443 //   * if there is a return type, then there must be braces,
444 //   * given a closure with braces, whether that is parsed to give an inner block
445 //     or not depends on if there is a return type and if there are statements
446 //     in that block,
447 //   * if the first expression in the body ends with a block (i.e., is a
448 //     statement without needing a semi-colon), then adding or removing braces
449 //     can change whether it is treated as an expression or statement.
450 fn rewrite_closure(capture: ast::CaptureBy,
451                    fn_decl: &ast::FnDecl,
452                    body: &ast::Expr,
453                    span: Span,
454                    context: &RewriteContext,
455                    shape: Shape)
456                    -> Option<String> {
457     let mover = if capture == ast::CaptureBy::Value {
458         "move "
459     } else {
460         ""
461     };
462     // 4 = "|| {".len(), which is overconservative when the closure consists of
463     // a single expression.
464     let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
465
466     // 1 = |
467     let argument_offset = nested_shape.indent + 1;
468     let arg_shape = try_opt!(nested_shape.shrink_left(1)).visual_indent(0);
469     let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
470
471     let arg_items = itemize_list(context.codemap,
472                                  fn_decl.inputs.iter(),
473                                  "|",
474                                  |arg| span_lo_for_arg(arg),
475                                  |arg| span_hi_for_arg(arg),
476                                  |arg| arg.rewrite(context, arg_shape),
477                                  context.codemap.span_after(span, "|"),
478                                  body.span.lo);
479     let item_vec = arg_items.collect::<Vec<_>>();
480     // 1 = space between arguments and return type.
481     let horizontal_budget = nested_shape
482         .width
483         .checked_sub(ret_str.len() + 1)
484         .unwrap_or(0);
485     let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
486     let arg_shape = match tactic {
487         DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
488         _ => arg_shape,
489     };
490
491     let fmt = ListFormatting {
492         tactic: tactic,
493         separator: ",",
494         trailing_separator: SeparatorTactic::Never,
495         shape: arg_shape,
496         ends_with_newline: false,
497         config: context.config,
498     };
499     let list_str = try_opt!(write_list(&item_vec, &fmt));
500     let mut prefix = format!("{}|{}|", mover, list_str);
501
502     if !ret_str.is_empty() {
503         if prefix.contains('\n') {
504             prefix.push('\n');
505             prefix.push_str(&argument_offset.to_string(context.config));
506         } else {
507             prefix.push(' ');
508         }
509         prefix.push_str(&ret_str);
510     }
511
512     // 1 = space between `|...|` and body.
513     let extra_offset = extra_offset(&prefix, shape) + 1;
514     let body_shape = try_opt!(shape.sub_width(extra_offset)).add_offset(extra_offset);
515
516     if let ast::ExprKind::Block(ref block) = body.node {
517         // The body of the closure is an empty block.
518         if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
519             return Some(format!("{} {{}}", prefix));
520         }
521
522         // Figure out if the block is necessary.
523         let needs_block = block.rules != ast::BlockCheckMode::Default ||
524                           block.stmts.len() > 1 || context.inside_macro ||
525                           block_contains_comment(block, context.codemap) ||
526                           prefix.contains('\n');
527
528         if ret_str.is_empty() && !needs_block {
529             // lock.stmts.len() == 1
530             if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
531                 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
532                     return Some(rw);
533                 }
534             }
535         }
536
537         if !needs_block {
538             // We need braces, but we might still prefer a one-liner.
539             let stmt = &block.stmts[0];
540             // 4 = braces and spaces.
541             if let Some(body_shape) = body_shape.sub_width(4) {
542                 // Checks if rewrite succeeded and fits on a single line.
543                 if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
544                     return Some(format!("{} {{ {} }}", prefix, rewrite));
545                 }
546             }
547         }
548
549         // Either we require a block, or tried without and failed.
550         return rewrite_closure_block(&block, prefix, context, body_shape);
551     }
552
553     if let Some(rw) = rewrite_closure_expr(body, &prefix, context, body_shape) {
554         return Some(rw);
555     }
556
557     // The closure originally had a non-block expression, but we can't fit on
558     // one line, so we'll insert a block.
559     let block = ast::Block {
560         stmts: vec![ast::Stmt {
561                         id: ast::NodeId::new(0),
562                         node: ast::StmtKind::Expr(ptr::P(body.clone())),
563                         span: body.span,
564                     }],
565         id: ast::NodeId::new(0),
566         rules: ast::BlockCheckMode::Default,
567         span: body.span,
568     };
569     return rewrite_closure_block(&block, prefix, context, body_shape);
570
571     fn rewrite_closure_expr(expr: &ast::Expr,
572                             prefix: &str,
573                             context: &RewriteContext,
574                             shape: Shape)
575                             -> Option<String> {
576         let mut rewrite = expr.rewrite(context, shape);
577         if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
578             rewrite = and_one_line(rewrite);
579         }
580         rewrite.map(|rw| format!("{} {}", prefix, rw))
581     }
582
583     fn rewrite_closure_block(block: &ast::Block,
584                              prefix: String,
585                              context: &RewriteContext,
586                              shape: Shape)
587                              -> Option<String> {
588         // Start with visual indent, then fall back to block indent if the
589         // closure is large.
590         if let Some(block_str) = block.rewrite(&context, shape) {
591             let block_threshold = context.config.closure_block_indent_threshold();
592             if block_threshold < 0 || block_str.matches('\n').count() <= block_threshold as usize {
593                 if let Some(block_str) = block_str.rewrite(context, shape) {
594                     return Some(format!("{} {}", prefix, block_str));
595                 }
596             }
597         }
598
599         // The body of the closure is big enough to be block indented, that
600         // means we must re-format.
601         let block_shape = shape.block().with_max_width(context.config);
602         let block_str = try_opt!(block.rewrite(&context, block_shape));
603         Some(format!("{} {}",
604                      prefix,
605                      try_opt!(block_str.rewrite(context, block_shape))))
606     }
607 }
608
609 fn and_one_line(x: Option<String>) -> Option<String> {
610     x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
611 }
612
613 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
614     debug!("nop_block_collapse {:?} {}", block_str, budget);
615     block_str.map(|block_str| if block_str.starts_with('{') && budget >= 2 &&
616                                  (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() ==
617                                   block_str.len() - 2) {
618                       "{}".to_owned()
619                   } else {
620                       block_str.to_owned()
621                   })
622 }
623
624 impl Rewrite for ast::Block {
625     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
626         // shape.width is used only for the single line case: either the empty block `{}`,
627         // or an unsafe expression `unsafe { e }`.
628
629         if self.stmts.is_empty() && !block_contains_comment(self, context.codemap) &&
630            shape.width >= 2 {
631             return Some("{}".to_owned());
632         }
633
634         // If a block contains only a single-line comment, then leave it on one line.
635         let user_str = context.snippet(self.span);
636         let user_str = user_str.trim();
637         if user_str.starts_with('{') && user_str.ends_with('}') {
638             let comment_str = user_str[1..user_str.len() - 1].trim();
639             if self.stmts.is_empty() && !comment_str.contains('\n') &&
640                !comment_str.starts_with("//") &&
641                comment_str.len() + 4 <= shape.width {
642                 return Some(format!("{{ {} }}", comment_str));
643             }
644         }
645
646         let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
647         visitor.block_indent = shape.indent;
648
649         let prefix = match self.rules {
650             ast::BlockCheckMode::Unsafe(..) => {
651                 let snippet = context.snippet(self.span);
652                 let open_pos = try_opt!(snippet.find_uncommented("{"));
653                 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
654
655                 // Extract comment between unsafe and block start.
656                 let trimmed = &snippet[6..open_pos].trim();
657
658                 let prefix = if !trimmed.is_empty() {
659                     // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
660                     let budget = try_opt!(shape.width.checked_sub(9));
661                     format!("unsafe {} ",
662                             try_opt!(rewrite_comment(trimmed,
663                                                      true,
664                                                      Shape::legacy(budget, shape.indent + 7),
665                                                      context.config)))
666                 } else {
667                     "unsafe ".to_owned()
668                 };
669
670                 if is_simple_block(self, context.codemap) && prefix.len() < shape.width {
671                     let expr_str =
672                         self.stmts[0].rewrite(context,
673                                               Shape::legacy(shape.width - prefix.len(),
674                                                             shape.indent));
675                     let expr_str = try_opt!(expr_str);
676                     let result = format!("{}{{ {} }}", prefix, expr_str);
677                     if result.len() <= shape.width && !result.contains('\n') {
678                         return Some(result);
679                     }
680                 }
681
682                 prefix
683             }
684             ast::BlockCheckMode::Default => {
685                 visitor.last_pos = self.span.lo;
686
687                 String::new()
688             }
689         };
690
691         visitor.visit_block(self);
692         if visitor.failed && shape.indent.alignment != 0 {
693             self.rewrite(context,
694                          Shape::indented(shape.indent.block_only(), context.config))
695         } else {
696             Some(format!("{}{}", prefix, visitor.buffer))
697         }
698     }
699 }
700
701 impl Rewrite for ast::Stmt {
702     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
703         let result = match self.node {
704             ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
705             ast::StmtKind::Expr(ref ex) |
706             ast::StmtKind::Semi(ref ex) => {
707                 let suffix = if semicolon_for_stmt(self) { ";" } else { "" };
708
709                 format_expr(ex,
710                             match self.node {
711                                 ast::StmtKind::Expr(_) => ExprType::SubExpression,
712                                 ast::StmtKind::Semi(_) => ExprType::Statement,
713                                 _ => unreachable!(),
714                             },
715                             context,
716                             try_opt!(shape.sub_width(suffix.len())))
717                     .map(|s| s + suffix)
718             }
719             ast::StmtKind::Mac(..) |
720             ast::StmtKind::Item(..) => None,
721         };
722         result.and_then(|res| recover_comment_removed(res, self.span, context, shape))
723     }
724 }
725
726 // Abstraction over control flow expressions
727 #[derive(Debug)]
728 struct ControlFlow<'a> {
729     cond: Option<&'a ast::Expr>,
730     block: &'a ast::Block,
731     else_block: Option<&'a ast::Expr>,
732     label: Option<ast::SpannedIdent>,
733     pat: Option<&'a ast::Pat>,
734     keyword: &'a str,
735     matcher: &'a str,
736     connector: &'a str,
737     allow_single_line: bool,
738     // True if this is an `if` expression in an `else if` :-( hacky
739     nested_if: bool,
740     span: Span,
741 }
742
743 impl<'a> ControlFlow<'a> {
744     fn new_if(cond: &'a ast::Expr,
745               pat: Option<&'a ast::Pat>,
746               block: &'a ast::Block,
747               else_block: Option<&'a ast::Expr>,
748               allow_single_line: bool,
749               nested_if: bool,
750               span: Span)
751               -> ControlFlow<'a> {
752         ControlFlow {
753             cond: Some(cond),
754             block: block,
755             else_block: else_block,
756             label: None,
757             pat: pat,
758             keyword: "if",
759             matcher: match pat {
760                 Some(..) => "let",
761                 None => "",
762             },
763             connector: " =",
764             allow_single_line: allow_single_line,
765             nested_if: nested_if,
766             span: span,
767         }
768     }
769
770     fn new_loop(block: &'a ast::Block,
771                 label: Option<ast::SpannedIdent>,
772                 span: Span)
773                 -> ControlFlow<'a> {
774         ControlFlow {
775             cond: None,
776             block: block,
777             else_block: None,
778             label: label,
779             pat: None,
780             keyword: "loop",
781             matcher: "",
782             connector: "",
783             allow_single_line: false,
784             nested_if: false,
785             span: span,
786         }
787     }
788
789     fn new_while(pat: Option<&'a ast::Pat>,
790                  cond: &'a ast::Expr,
791                  block: &'a ast::Block,
792                  label: Option<ast::SpannedIdent>,
793                  span: Span)
794                  -> ControlFlow<'a> {
795         ControlFlow {
796             cond: Some(cond),
797             block: block,
798             else_block: None,
799             label: label,
800             pat: pat,
801             keyword: "while",
802             matcher: match pat {
803                 Some(..) => "let",
804                 None => "",
805             },
806             connector: " =",
807             allow_single_line: false,
808             nested_if: false,
809             span: span,
810         }
811     }
812
813     fn new_for(pat: &'a ast::Pat,
814                cond: &'a ast::Expr,
815                block: &'a ast::Block,
816                label: Option<ast::SpannedIdent>,
817                span: Span)
818                -> ControlFlow<'a> {
819         ControlFlow {
820             cond: Some(cond),
821             block: block,
822             else_block: None,
823             label: label,
824             pat: Some(pat),
825             keyword: "for",
826             matcher: "",
827             connector: " in",
828             allow_single_line: false,
829             nested_if: false,
830             span: span,
831         }
832     }
833
834     fn rewrite_single_line(&self,
835                            pat_expr_str: &str,
836                            context: &RewriteContext,
837                            width: usize)
838                            -> Option<String> {
839         assert!(self.allow_single_line);
840         let else_block = try_opt!(self.else_block);
841         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
842
843         if let ast::ExprKind::Block(ref else_node) = else_block.node {
844             if !is_simple_block(self.block, context.codemap) ||
845                !is_simple_block(else_node, context.codemap) ||
846                pat_expr_str.contains('\n') {
847                 return None;
848             }
849
850             let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
851             let expr = &self.block.stmts[0];
852             let if_str = try_opt!(expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
853
854             let new_width = try_opt!(new_width.checked_sub(if_str.len()));
855             let else_expr = &else_node.stmts[0];
856             let else_str = try_opt!(else_expr.rewrite(context,
857                                                       Shape::legacy(new_width, Indent::empty())));
858
859             if if_str.contains('\n') || else_str.contains('\n') {
860                 return None;
861             }
862
863             let result = format!("{} {} {{ {} }} else {{ {} }}",
864                                  self.keyword,
865                                  pat_expr_str,
866                                  if_str,
867                                  else_str);
868
869             if result.len() <= width {
870                 return Some(result);
871             }
872         }
873
874         None
875     }
876 }
877
878 impl<'a> Rewrite for ControlFlow<'a> {
879     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
880         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
881         let constr_shape = if self.nested_if {
882             // We are part of an if-elseif-else chain. Our constraints are tightened.
883             // 7 = "} else " .len()
884             try_opt!(shape.shrink_left(7))
885         } else {
886             shape
887         };
888
889         let label_string = rewrite_label(self.label);
890         // 1 = space after keyword.
891         let add_offset = self.keyword.len() + label_string.len() + 1;
892
893         let pat_expr_string = match self.cond {
894             Some(cond) => {
895                 let mut cond_shape = match context.config.control_style() {
896                     Style::Default => try_opt!(constr_shape.shrink_left(add_offset)),
897                     Style::Rfc => constr_shape,
898                 };
899                 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
900                     // 2 = " {".len()
901                     cond_shape = try_opt!(cond_shape.sub_width(2));
902                 }
903
904                 try_opt!(rewrite_pat_expr(context,
905                                           self.pat,
906                                           cond,
907                                           self.matcher,
908                                           self.connector,
909                                           cond_shape))
910             }
911             None => String::new(),
912         };
913
914         let force_newline_brace = context.config.control_style() == Style::Rfc &&
915                                   pat_expr_string.contains('\n');
916
917         // Try to format if-else on single line.
918         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
919             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
920
921             if trial.is_some() &&
922                trial.as_ref().unwrap().len() <= context.config.single_line_if_else_max_width() {
923                 return trial;
924             }
925         }
926
927         let used_width = if pat_expr_string.contains('\n') {
928             last_line_width(&pat_expr_string)
929         } else {
930             // 2 = spaces after keyword and condition.
931             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
932         };
933
934         let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
935         // This is used only for the empty block case: `{}`. So, we use 1 if we know
936         // we should avoid the single line case.
937         let block_width = if self.else_block.is_some() || self.nested_if {
938             min(1, block_width)
939         } else {
940             block_width
941         };
942
943         let block_shape = Shape {
944             width: block_width,
945             ..shape
946         };
947         let block_str = try_opt!(self.block.rewrite(context, block_shape));
948
949         let cond_span = if let Some(cond) = self.cond {
950             cond.span
951         } else {
952             mk_sp(self.block.span.lo, self.block.span.lo)
953         };
954
955         // for event in event
956         let between_kwd_cond =
957             mk_sp(context.codemap.span_after(self.span, self.keyword.trim()),
958                   self.pat
959                       .map_or(cond_span.lo, |p| if self.matcher.is_empty() {
960                 p.span.lo
961             } else {
962                 context.codemap.span_before(self.span, self.matcher.trim())
963             }));
964
965         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
966
967         let after_cond_comment =
968             extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
969
970         let alt_block_sep = String::from("\n") +
971                             &shape.indent.block_only().to_string(context.config);
972         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
973             ""
974         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
975                   force_newline_brace {
976             alt_block_sep.as_str()
977         } else {
978             " "
979         };
980
981         let mut result = format!("{}{}{}{}{}{}",
982                                  label_string,
983                                  self.keyword,
984                                  between_kwd_cond_comment
985                                      .as_ref()
986                                      .map_or(if pat_expr_string.is_empty() ||
987                                                 pat_expr_string.starts_with('\n') {
988                                                  ""
989                                              } else {
990                                                  " "
991                                              },
992                                              |s| &**s),
993                                  pat_expr_string,
994                                  after_cond_comment.as_ref().map_or(block_sep, |s| &**s),
995                                  block_str);
996
997         if let Some(else_block) = self.else_block {
998             let shape = Shape::indented(shape.indent, context.config);
999             let mut last_in_chain = false;
1000             let rewrite = match else_block.node {
1001                 // If the else expression is another if-else expression, prevent it
1002                 // from being formatted on a single line.
1003                 // Note how we're passing the original shape, as the
1004                 // cost of "else" should not cascade.
1005                 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1006                     ControlFlow::new_if(cond,
1007                                         Some(pat),
1008                                         if_block,
1009                                         next_else_block.as_ref().map(|e| &**e),
1010                                         false,
1011                                         true,
1012                                         mk_sp(else_block.span.lo, self.span.hi))
1013                         .rewrite(context, shape)
1014                 }
1015                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1016                     ControlFlow::new_if(cond,
1017                                         None,
1018                                         if_block,
1019                                         next_else_block.as_ref().map(|e| &**e),
1020                                         false,
1021                                         true,
1022                                         mk_sp(else_block.span.lo, self.span.hi))
1023                         .rewrite(context, shape)
1024                 }
1025                 _ => {
1026                     last_in_chain = true;
1027                     // When rewriting a block, the width is only used for single line
1028                     // blocks, passing 1 lets us avoid that.
1029                     let else_shape = Shape {
1030                         width: min(1, shape.width),
1031                         ..shape
1032                     };
1033                     else_block.rewrite(context, else_shape)
1034                 }
1035             };
1036
1037             let between_kwd_else_block =
1038                 mk_sp(self.block.span.hi,
1039                       context
1040                           .codemap
1041                           .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"));
1042             let between_kwd_else_block_comment =
1043                 extract_comment(between_kwd_else_block, context, shape);
1044
1045             let after_else = mk_sp(context.codemap.span_after(mk_sp(self.block.span.hi,
1046                                                                     else_block.span.lo),
1047                                                               "else"),
1048                                    else_block.span.lo);
1049             let after_else_comment = extract_comment(after_else, context, shape);
1050
1051             let between_sep = match context.config.control_brace_style() {
1052                 ControlBraceStyle::AlwaysNextLine |
1053                 ControlBraceStyle::ClosingNextLine => &*alt_block_sep,
1054                 ControlBraceStyle::AlwaysSameLine => " ",
1055             };
1056             let after_sep = match context.config.control_brace_style() {
1057                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1058                 _ => " ",
1059             };
1060             try_opt!(write!(&mut result,
1061                             "{}else{}",
1062                             between_kwd_else_block_comment
1063                                 .as_ref()
1064                                 .map_or(between_sep, |s| &**s),
1065                             after_else_comment.as_ref().map_or(after_sep, |s| &**s))
1066                          .ok());
1067             result.push_str(&try_opt!(rewrite));
1068         }
1069
1070         Some(result)
1071     }
1072 }
1073
1074 fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
1075     match label {
1076         Some(ident) => format!("{}: ", ident.node),
1077         None => "".to_owned(),
1078     }
1079 }
1080
1081 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1082     let comment_str = context.snippet(span);
1083     if contains_comment(&comment_str) {
1084         let comment = try_opt!(rewrite_comment(comment_str.trim(), false, shape, context.config));
1085         Some(format!("\n{indent}{}\n{indent}",
1086                      comment,
1087                      indent = shape.indent.to_string(context.config)))
1088     } else {
1089         None
1090     }
1091 }
1092
1093 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1094     let snippet = codemap.span_to_snippet(block.span).unwrap();
1095     contains_comment(&snippet)
1096 }
1097
1098 // Checks that a block contains no statements, an expression and no comments.
1099 // FIXME: incorrectly returns false when comment is contained completely within
1100 // the expression.
1101 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1102     (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
1103      !block_contains_comment(block, codemap))
1104 }
1105
1106 /// Checks whether a block contains at most one statement or expression, and no comments.
1107 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1108     block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1109 }
1110
1111 /// Checks whether a block contains no statements, expressions, or comments.
1112 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1113     block.stmts.is_empty() && !block_contains_comment(block, codemap)
1114 }
1115
1116 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1117     match stmt.node {
1118         ast::StmtKind::Expr(..) => true,
1119         _ => false,
1120     }
1121 }
1122
1123 fn is_unsafe_block(block: &ast::Block) -> bool {
1124     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1125         true
1126     } else {
1127         false
1128     }
1129 }
1130
1131 // inter-match-arm-comment-rules:
1132 //  - all comments following a match arm before the start of the next arm
1133 //    are about the second arm
1134 fn rewrite_match_arm_comment(context: &RewriteContext,
1135                              missed_str: &str,
1136                              shape: Shape,
1137                              arm_indent_str: &str)
1138                              -> Option<String> {
1139     // The leading "," is not part of the arm-comment
1140     let missed_str = match missed_str.find_uncommented(",") {
1141         Some(n) => &missed_str[n + 1..],
1142         None => &missed_str[..],
1143     };
1144
1145     let mut result = String::new();
1146     // any text not preceeded by a newline is pushed unmodified to the block
1147     let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
1148     result.push_str(&missed_str[..first_brk]);
1149     let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
1150
1151     let first = missed_str
1152         .find(|c: char| !c.is_whitespace())
1153         .unwrap_or(missed_str.len());
1154     if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
1155         // Excessive vertical whitespace before comment should be preserved
1156         // FIXME handle vertical whitespace better
1157         result.push('\n');
1158     }
1159     let missed_str = missed_str[first..].trim();
1160     if !missed_str.is_empty() {
1161         let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
1162         result.push('\n');
1163         result.push_str(arm_indent_str);
1164         result.push_str(&comment);
1165     }
1166
1167     Some(result)
1168 }
1169
1170 fn rewrite_match(context: &RewriteContext,
1171                  cond: &ast::Expr,
1172                  arms: &[ast::Arm],
1173                  shape: Shape,
1174                  span: Span)
1175                  -> Option<String> {
1176     if arms.is_empty() {
1177         return None;
1178     }
1179
1180     // `match `cond` {`
1181     let cond_shape = try_opt!(shape.shrink_left(6));
1182     let cond_shape = try_opt!(cond_shape.sub_width(2));
1183     let cond_str = try_opt!(cond.rewrite(context, cond_shape));
1184     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1185     let block_sep = match context.config.control_brace_style() {
1186         ControlBraceStyle::AlwaysSameLine => " ",
1187         _ => alt_block_sep.as_str(),
1188     };
1189     let mut result = format!("match {}{}{{", cond_str, block_sep);
1190
1191     let arm_shape = if context.config.indent_match_arms() {
1192         shape.block_indent(context.config.tab_spaces())
1193     } else {
1194         shape.block_indent(0)
1195     };
1196
1197     let arm_indent_str = arm_shape.indent.to_string(context.config);
1198
1199     let open_brace_pos = context
1200         .codemap
1201         .span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");
1202
1203     for (i, arm) in arms.iter().enumerate() {
1204         // Make sure we get the stuff between arms.
1205         let missed_str = if i == 0 {
1206             context.snippet(mk_sp(open_brace_pos, arm_start_pos(arm)))
1207         } else {
1208             context.snippet(mk_sp(arm_end_pos(&arms[i - 1]), arm_start_pos(arm)))
1209         };
1210         let comment =
1211             try_opt!(rewrite_match_arm_comment(context, &missed_str, arm_shape, &arm_indent_str));
1212         result.push_str(&comment);
1213         result.push('\n');
1214         result.push_str(&arm_indent_str);
1215
1216         let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
1217         if let Some(ref arm_str) = arm_str {
1218             result.push_str(arm_str);
1219         } else {
1220             // We couldn't format the arm, just reproduce the source.
1221             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
1222             result.push_str(&snippet);
1223             result.push_str(arm_comma(context.config, &arm.body));
1224         }
1225     }
1226     // BytePos(1) = closing match brace.
1227     let last_span = mk_sp(arm_end_pos(&arms[arms.len() - 1]), span.hi - BytePos(1));
1228     let last_comment = context.snippet(last_span);
1229     let comment =
1230         try_opt!(rewrite_match_arm_comment(context, &last_comment, arm_shape, &arm_indent_str));
1231     result.push_str(&comment);
1232     result.push('\n');
1233     result.push_str(&shape.indent.to_string(context.config));
1234     result.push('}');
1235     Some(result)
1236 }
1237
1238 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
1239     let &ast::Arm {
1240         ref attrs,
1241         ref pats,
1242         ..
1243     } = arm;
1244     if !attrs.is_empty() {
1245         return attrs[0].span.lo;
1246     }
1247
1248     pats[0].span.lo
1249 }
1250
1251 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
1252     arm.body.span.hi
1253 }
1254
1255 fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
1256     if config.match_block_trailing_comma() {
1257         ","
1258     } else if let ast::ExprKind::Block(ref block) = body.node {
1259         if let ast::BlockCheckMode::Default = block.rules {
1260             ""
1261         } else {
1262             ","
1263         }
1264     } else {
1265         ","
1266     }
1267 }
1268
1269 // Match arms.
1270 impl Rewrite for ast::Arm {
1271     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1272         debug!("Arm::rewrite {:?} {:?}", self, shape);
1273         let &ast::Arm {
1274             ref attrs,
1275             ref pats,
1276             ref guard,
1277             ref body,
1278         } = self;
1279
1280         // FIXME this is all a bit grotty, would be nice to abstract out the
1281         // treatment of attributes.
1282         let attr_str = if !attrs.is_empty() {
1283             // We only use this visitor for the attributes, should we use it for
1284             // more?
1285             let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1286             attr_visitor.block_indent = shape.indent.block_only();
1287             attr_visitor.last_pos = attrs[0].span.lo;
1288             if attr_visitor.visit_attrs(attrs) {
1289                 // Attributes included a skip instruction.
1290                 return None;
1291             }
1292             attr_visitor.format_missing(pats[0].span.lo);
1293             attr_visitor.buffer.to_string()
1294         } else {
1295             String::new()
1296         };
1297
1298         // Patterns
1299         // 5 = ` => {`
1300         let pat_shape = try_opt!(shape.sub_width(5));
1301
1302         let pat_strs = try_opt!(pats.iter()
1303                                     .map(|p| p.rewrite(context, pat_shape))
1304                                     .collect::<Option<Vec<_>>>());
1305
1306         let all_simple = pat_strs.iter().all(|p| pat_is_simple(p));
1307         let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1308         let fmt = ListFormatting {
1309             tactic: if all_simple {
1310                 DefinitiveListTactic::Mixed
1311             } else {
1312                 DefinitiveListTactic::Vertical
1313             },
1314             separator: " |",
1315             trailing_separator: SeparatorTactic::Never,
1316             shape: pat_shape,
1317             ends_with_newline: false,
1318             config: context.config,
1319         };
1320         let pats_str = try_opt!(write_list(items, &fmt));
1321
1322         let guard_shape = if pats_str.contains('\n') {
1323             shape.with_max_width(context.config)
1324         } else {
1325             shape
1326         };
1327
1328         let guard_str = try_opt!(rewrite_guard(context,
1329                                                guard,
1330                                                guard_shape,
1331                                                trimmed_last_line_width(&pats_str)));
1332
1333         let pats_str = format!("{}{}", pats_str, guard_str);
1334
1335         let (mut extend, body) = match body.node {
1336             ast::ExprKind::Block(ref block) if !is_unsafe_block(block) &&
1337                                                is_simple_block(block, context.codemap) &&
1338                                                context.config.wrap_match_arms() => {
1339                 if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1340                     (false, &**expr)
1341                 } else {
1342                     (false, &**body)
1343                 }
1344             }
1345             ast::ExprKind::Call(_, ref args) => (args.len() == 1, &**body),
1346             ast::ExprKind::Closure(..) |
1347             ast::ExprKind::Struct(..) |
1348             ast::ExprKind::Tup(..) => (true, &**body),
1349             _ => (false, &**body),
1350         };
1351         extend &= context.config.fn_call_style() == IndentStyle::Block;
1352
1353         let comma = arm_comma(&context.config, body);
1354         let alt_block_sep = String::from("\n") +
1355                             &shape.indent.block_only().to_string(context.config);
1356
1357         let pat_width = extra_offset(&pats_str, shape);
1358         // Let's try and get the arm body on the same line as the condition.
1359         // 4 = ` => `.len()
1360         if shape.width > pat_width + comma.len() + 4 {
1361             let arm_shape = shape
1362                 .offset_left(pat_width + 4)
1363                 .unwrap()
1364                 .sub_width(comma.len())
1365                 .unwrap();
1366             let rewrite = nop_block_collapse(body.rewrite(context, arm_shape), arm_shape.width);
1367             let is_block = if let ast::ExprKind::Block(..) = body.node {
1368                 true
1369             } else {
1370                 false
1371             };
1372
1373             match rewrite {
1374                 Some(ref body_str) if (!body_str.contains('\n') &&
1375                                        body_str.len() <= arm_shape.width) ||
1376                                       !context.config.wrap_match_arms() ||
1377                                       (extend && first_line_width(body_str) <= arm_shape.width) ||
1378                                       is_block => {
1379                     let block_sep = match context.config.control_brace_style() {
1380                         ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep.as_str(),
1381                         _ => " ",
1382                     };
1383
1384                     return Some(format!("{}{} =>{}{}{}",
1385                                         attr_str.trim_left(),
1386                                         pats_str,
1387                                         block_sep,
1388                                         body_str,
1389                                         comma));
1390                 }
1391                 _ => {}
1392             }
1393         }
1394
1395         // FIXME: we're doing a second rewrite of the expr; This may not be
1396         // necessary.
1397         let body_shape = try_opt!(shape.sub_width(context.config.tab_spaces()))
1398             .block_indent(context.config.tab_spaces());
1399         let next_line_body = try_opt!(nop_block_collapse(body.rewrite(context, body_shape),
1400                                                          body_shape.width));
1401         let indent_str = shape
1402             .indent
1403             .block_indent(context.config)
1404             .to_string(context.config);
1405         let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1406             if context.config.match_block_trailing_comma() {
1407                 ("{", "},")
1408             } else {
1409                 ("{", "}")
1410             }
1411         } else {
1412             ("", ",")
1413         };
1414
1415
1416         let block_sep = match context.config.control_brace_style() {
1417             ControlBraceStyle::AlwaysNextLine => alt_block_sep + body_prefix + "\n",
1418             _ if body_prefix.is_empty() => "\n".to_owned(),
1419             _ => " ".to_owned() + body_prefix + "\n",
1420         };
1421
1422         if context.config.wrap_match_arms() {
1423             Some(format!("{}{} =>{}{}{}\n{}{}",
1424                          attr_str.trim_left(),
1425                          pats_str,
1426                          block_sep,
1427                          indent_str,
1428                          next_line_body,
1429                          shape.indent.to_string(context.config),
1430                          body_suffix))
1431         } else {
1432             Some(format!("{}{} =>{}{}{}{}",
1433                          attr_str.trim_left(),
1434                          pats_str,
1435                          block_sep,
1436                          indent_str,
1437                          next_line_body,
1438                          body_suffix))
1439         }
1440     }
1441 }
1442
1443 // A pattern is simple if it is very short or it is short-ish and just a path.
1444 // E.g. `Foo::Bar` is simple, but `Foo(..)` is not.
1445 fn pat_is_simple(pat_str: &str) -> bool {
1446     pat_str.len() <= 16 ||
1447     (pat_str.len() <= 24 && pat_str.chars().all(|c| c.is_alphabetic() || c == ':'))
1448 }
1449
1450 // The `if ...` guard on a match arm.
1451 fn rewrite_guard(context: &RewriteContext,
1452                  guard: &Option<ptr::P<ast::Expr>>,
1453                  shape: Shape,
1454                  // The amount of space used up on this line for the pattern in
1455                  // the arm (excludes offset).
1456                  pattern_width: usize)
1457                  -> Option<String> {
1458     if let Some(ref guard) = *guard {
1459         // First try to fit the guard string on the same line as the pattern.
1460         // 4 = ` if `, 5 = ` => {`
1461         let overhead = pattern_width + 4 + 5;
1462         if overhead < shape.width {
1463             let cond_shape = shape
1464                 .shrink_left(pattern_width + 4)
1465                 .unwrap()
1466                 .sub_width(5)
1467                 .unwrap();
1468             let cond_str = guard.rewrite(context, cond_shape);
1469             if let Some(cond_str) = cond_str {
1470                 return Some(format!(" if {}", cond_str));
1471             }
1472         }
1473
1474         // Not enough space to put the guard after the pattern, try a newline.
1475         let overhead = shape.indent.block_indent(context.config).width() + 4 + 5;
1476         if overhead < shape.width {
1477             let cond_str = guard.rewrite(context,
1478                                          Shape::legacy(shape.width - overhead,
1479                                                        // 3 == `if `
1480                                                        shape.indent.block_indent(context.config) +
1481                                                        3));
1482             if let Some(cond_str) = cond_str {
1483                 return Some(format!("\n{}if {}",
1484                                     shape
1485                                         .indent
1486                                         .block_indent(context.config)
1487                                         .to_string(context.config),
1488                                     cond_str));
1489             }
1490         }
1491
1492         None
1493     } else {
1494         Some(String::new())
1495     }
1496 }
1497
1498 fn rewrite_pat_expr(context: &RewriteContext,
1499                     pat: Option<&ast::Pat>,
1500                     expr: &ast::Expr,
1501                     matcher: &str,
1502                     // Connecting piece between pattern and expression,
1503                     // *without* trailing space.
1504                     connector: &str,
1505                     shape: Shape)
1506                     -> Option<String> {
1507     debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1508     let mut pat_string = String::new();
1509     let mut result = match pat {
1510         Some(pat) => {
1511             let matcher = if matcher.is_empty() {
1512                 matcher.to_owned()
1513             } else {
1514                 format!("{} ", matcher)
1515             };
1516             let pat_shape = try_opt!(try_opt!(shape.shrink_left(matcher.len()))
1517                                          .sub_width(connector.len()));
1518             pat_string = try_opt!(pat.rewrite(context, pat_shape));
1519             format!("{}{}{}", matcher, pat_string, connector)
1520         }
1521         None => String::new(),
1522     };
1523
1524     // Consider only the last line of the pat string.
1525     let extra_offset = extra_offset(&result, shape);
1526
1527     // The expression may (partially) fit on the current line.
1528     if shape.width > extra_offset + 1 {
1529         let spacer = if pat.is_some() { " " } else { "" };
1530
1531         let expr_shape = try_opt!(shape.offset_left(extra_offset + spacer.len()));
1532         let expr_rewrite = expr.rewrite(context, expr_shape);
1533
1534         if let Some(expr_string) = expr_rewrite {
1535             if pat.is_none() || pat_is_simple(&pat_string) || !expr_string.contains('\n') {
1536                 result.push_str(spacer);
1537                 result.push_str(&expr_string);
1538                 return Some(result);
1539             }
1540         }
1541     }
1542
1543     let nested_indent = shape.indent.block_only().block_indent(context.config);
1544
1545     // The expression won't fit on the current line, jump to next.
1546     result.push('\n');
1547     result.push_str(&nested_indent.to_string(context.config));
1548
1549     let expr_rewrite = expr.rewrite(&context, Shape::indented(nested_indent, context.config));
1550     result.push_str(&try_opt!(expr_rewrite));
1551
1552     Some(result)
1553 }
1554
1555 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1556     let string_lit = context.snippet(span);
1557
1558     if !context.config.format_strings() && !context.config.force_format_strings() {
1559         return Some(string_lit);
1560     }
1561
1562     if !context.config.force_format_strings() &&
1563        !string_requires_rewrite(context, span, &string_lit, shape) {
1564         return Some(string_lit);
1565     }
1566
1567     let fmt = StringFormat {
1568         opener: "\"",
1569         closer: "\"",
1570         line_start: " ",
1571         line_end: "\\",
1572         shape: shape,
1573         trim_end: false,
1574         config: context.config,
1575     };
1576
1577     // Remove the quote characters.
1578     let str_lit = &string_lit[1..string_lit.len() - 1];
1579
1580     rewrite_string(str_lit, &fmt)
1581 }
1582
1583 fn string_requires_rewrite(context: &RewriteContext,
1584                            span: Span,
1585                            string: &str,
1586                            shape: Shape)
1587                            -> bool {
1588     if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
1589         return true;
1590     }
1591
1592     for (i, line) in string.lines().enumerate() {
1593         if i == 0 {
1594             if line.len() > shape.width {
1595                 return true;
1596             }
1597         } else {
1598             if line.len() > shape.width + shape.indent.width() {
1599                 return true;
1600             }
1601         }
1602     }
1603
1604     false
1605 }
1606
1607 pub fn rewrite_call<R>(context: &RewriteContext,
1608                        callee: &R,
1609                        args: &[ptr::P<ast::Expr>],
1610                        span: Span,
1611                        shape: Shape)
1612                        -> Option<String>
1613     where R: Rewrite
1614 {
1615     let closure = |callee_max_width| {
1616         rewrite_call_inner(context, callee, callee_max_width, args, span, shape, false)
1617     };
1618
1619     binary_search(1, shape.width, closure)
1620 }
1621
1622 fn rewrite_call_inner<R>(context: &RewriteContext,
1623                          callee: &R,
1624                          max_callee_width: usize,
1625                          args: &[ptr::P<ast::Expr>],
1626                          span: Span,
1627                          shape: Shape,
1628                          force_trailing_comma: bool)
1629                          -> Result<String, Ordering>
1630     where R: Rewrite
1631 {
1632     // FIXME using byte lens instead of char lens (and probably all over the
1633     // place too)
1634     let callee_shape = Shape {
1635         width: max_callee_width,
1636         ..shape
1637     };
1638     let callee_str = callee
1639         .rewrite(context, callee_shape)
1640         .ok_or(Ordering::Greater)?;
1641
1642     // 2 = `( `, 1 = `(`
1643     let paren_overhead = if context.config.spaces_within_parens() {
1644         2
1645     } else {
1646         1
1647     };
1648     let used_width = extra_offset(&callee_str, shape);
1649     let one_line_width = shape
1650         .width
1651         .checked_sub(used_width + 2 * paren_overhead)
1652         .ok_or(Ordering::Greater)?;
1653
1654     let nested_shape = shape_from_fn_call_style(context,
1655                                                 shape,
1656                                                 used_width + 2 * paren_overhead,
1657                                                 used_width + paren_overhead)
1658         .ok_or(Ordering::Greater)?;
1659
1660     let span_lo = context.codemap.span_after(span, "(");
1661     let span = mk_sp(span_lo, span.hi);
1662
1663     let (extendable, list_str) = rewrite_call_args(context,
1664                                                    args,
1665                                                    span,
1666                                                    nested_shape,
1667                                                    one_line_width,
1668                                                    force_trailing_comma)
1669         .ok_or(Ordering::Less)?;
1670     let arg_one_line_budget = min(one_line_width, context.config.fn_call_width());
1671     Ok(format!("{}{}",
1672                callee_str,
1673                wrap_args_with_parens(context,
1674                                      &list_str,
1675                                      extendable,
1676                                      arg_one_line_budget,
1677                                      shape,
1678                                      nested_shape)))
1679 }
1680
1681 fn rewrite_call_args(context: &RewriteContext,
1682                      args: &[ptr::P<ast::Expr>],
1683                      span: Span,
1684                      shape: Shape,
1685                      one_line_width: usize,
1686                      force_trailing_comma: bool)
1687                      -> Option<(bool, String)> {
1688     let items = itemize_list(context.codemap,
1689                              args.iter(),
1690                              ")",
1691                              |item| item.span.lo,
1692                              |item| item.span.hi,
1693                              |item| item.rewrite(context, shape),
1694                              span.lo,
1695                              span.hi);
1696     let mut item_vec: Vec<_> = items.collect();
1697
1698     // Try letting the last argument overflow to the next line with block
1699     // indentation. If its first line fits on one line with the other arguments,
1700     // we format the function arguments horizontally.
1701     let overflow_last = can_be_overflowed(context, args);
1702
1703     let mut orig_last = None;
1704     let mut placeholder = None;
1705
1706     // Replace the last item with its first line to see if it fits with
1707     // first arguments.
1708     if overflow_last {
1709         let arg_shape = if context.config.fn_call_style() == IndentStyle::Block &&
1710                            is_extendable(args) {
1711             Shape {
1712                 width: context.config.fn_call_width(),
1713                 indent: shape.block().indent.block_unindent(context.config),
1714                 offset: 0,
1715             }
1716         } else {
1717             shape.block()
1718         };
1719         let rewrite = args.last().unwrap().rewrite(context, arg_shape);
1720         swap(&mut item_vec[args.len() - 1].item, &mut orig_last);
1721
1722         if let Some(rewrite) = rewrite {
1723             let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
1724             placeholder = Some(rewrite);
1725
1726             item_vec[args.len() - 1].item = rewrite_first_line;
1727         }
1728     }
1729
1730     let one_line_shape = Shape {
1731         width: one_line_width,
1732         ..shape
1733     };
1734
1735     let tactic =
1736         definitive_tactic(&item_vec,
1737                           ListTactic::LimitedHorizontalVertical(context.config.fn_call_width()),
1738                           one_line_width);
1739
1740     // Replace the stub with the full overflowing last argument if the rewrite
1741     // succeeded and its first line fits with the other arguments.
1742     match (overflow_last, tactic, placeholder) {
1743         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
1744             item_vec[args.len() - 1].item = placeholder;
1745         }
1746         (true, _, _) => {
1747             item_vec[args.len() - 1].item = orig_last;
1748         }
1749         (false, _, _) => {}
1750     }
1751
1752     let mut fmt = ListFormatting {
1753         tactic: tactic,
1754         separator: ",",
1755         trailing_separator: if force_trailing_comma {
1756             SeparatorTactic::Always
1757         } else if context.inside_macro || context.config.fn_call_style() == IndentStyle::Visual ||
1758                   args.len() <= 1 {
1759             SeparatorTactic::Never
1760         } else {
1761             context.config.trailing_comma()
1762         },
1763         shape: one_line_shape,
1764         ends_with_newline: false,
1765         config: context.config,
1766     };
1767
1768     let args_in_single_line =
1769         item_vec
1770             .iter()
1771             .rev()
1772             .skip(1)
1773             .all(|item| item.item.as_ref().map_or(false, |s| !s.contains('\n')));
1774
1775     match write_list(&item_vec, &fmt) {
1776         // If arguments do not fit in a single line and do not contain newline,
1777         // try to put it on the next line. Try this only when we are in block mode
1778         // and not rewriting macro.
1779         Some(ref s) if context.config.fn_call_style() == IndentStyle::Block &&
1780                        !context.inside_macro &&
1781                        (!can_be_overflowed(context, args) && args.len() == 1 && s.contains('\n') ||
1782                         first_line_width(s) > one_line_width ||
1783                         first_line_width(s) > context.config.fn_call_width()) => {
1784             fmt.trailing_separator = SeparatorTactic::Vertical;
1785             fmt.tactic = DefinitiveListTactic::Vertical;
1786             write_list(&item_vec, &fmt).map(|rw| (false, rw))
1787         }
1788         rewrite @ _ => rewrite.map(|rw| (args_in_single_line && is_extendable(args), rw)),
1789     }
1790 }
1791
1792 fn can_be_overflowed(context: &RewriteContext, args: &[ptr::P<ast::Expr>]) -> bool {
1793     match args.last().map(|x| &x.node) {
1794         Some(&ast::ExprKind::Block(..)) |
1795         Some(&ast::ExprKind::Match(..)) => {
1796             (context.config.fn_call_style() == IndentStyle::Block && args.len() == 1) ||
1797             (context.config.fn_call_style() == IndentStyle::Visual && args.len() > 1)
1798         }
1799         Some(&ast::ExprKind::Closure(..)) => {
1800             context.config.fn_call_style() == IndentStyle::Block ||
1801             context.config.fn_call_style() == IndentStyle::Visual && args.len() > 1
1802         }
1803         Some(&ast::ExprKind::Call(..)) |
1804         Some(&ast::ExprKind::Struct(..)) => {
1805             context.config.fn_call_style() == IndentStyle::Block && args.len() == 1
1806         }
1807         Some(&ast::ExprKind::Tup(..)) => context.config.fn_call_style() == IndentStyle::Block,
1808         _ => false,
1809     }
1810 }
1811
1812 fn is_extendable(args: &[ptr::P<ast::Expr>]) -> bool {
1813     if args.len() == 1 {
1814         match args[0].node {
1815             ast::ExprKind::Block(..) |
1816             ast::ExprKind::Call(..) |
1817             ast::ExprKind::Closure(..) |
1818             ast::ExprKind::Match(..) |
1819             ast::ExprKind::Struct(..) |
1820             ast::ExprKind::Tup(..) => true,
1821             _ => false,
1822         }
1823     } else if args.len() > 1 {
1824         match args[args.len() - 1].node {
1825             ast::ExprKind::Closure(..) |
1826             ast::ExprKind::Tup(..) => true,
1827             _ => false,
1828         }
1829     } else {
1830         false
1831     }
1832 }
1833
1834 fn wrap_args_with_parens(context: &RewriteContext,
1835                          args_str: &str,
1836                          is_extendable: bool,
1837                          one_line_budget: usize,
1838                          shape: Shape,
1839                          nested_shape: Shape)
1840                          -> String {
1841     if context.config.fn_call_style() == IndentStyle::Visual ||
1842        (context.inside_macro && !args_str.contains('\n')) ||
1843        ((is_extendable || !args_str.contains('\n')) &&
1844         first_line_width(&args_str) <= one_line_budget) {
1845         if context.config.spaces_within_parens() && args_str.len() > 0 {
1846             format!("( {} )", args_str)
1847         } else {
1848             format!("({})", args_str)
1849         }
1850     } else {
1851         format!("(\n{}{}\n{})",
1852                 nested_shape.indent.to_string(context.config),
1853                 args_str,
1854                 shape.block().indent.to_string(context.config))
1855     }
1856 }
1857
1858 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
1859     debug!("rewrite_paren, shape: {:?}", shape);
1860     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1861     // paren on the same line as the subexpr.
1862     let sub_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
1863     let subexpr_str = subexpr.rewrite(context, sub_shape);
1864     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1865
1866     subexpr_str.map(|s| if context.config.spaces_within_parens() && s.len() > 0 {
1867                         format!("( {} )", s)
1868                     } else {
1869                         format!("({})", s)
1870                     })
1871 }
1872
1873 fn rewrite_index(expr: &ast::Expr,
1874                  index: &ast::Expr,
1875                  context: &RewriteContext,
1876                  shape: Shape)
1877                  -> Option<String> {
1878     let expr_str = try_opt!(expr.rewrite(context, shape));
1879
1880     let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
1881         ("[ ", " ]")
1882     } else {
1883         ("[", "]")
1884     };
1885
1886     let budget = shape
1887         .width
1888         .checked_sub(expr_str.len() + lbr.len() + rbr.len())
1889         .unwrap_or(0);
1890     let index_str = index.rewrite(context, Shape::legacy(budget, shape.indent));
1891     if let Some(index_str) = index_str {
1892         return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
1893     }
1894
1895     let indent = shape.indent.block_indent(&context.config);
1896     let indent = indent.to_string(&context.config);
1897     // FIXME this is not right, since we don't take into account that shape.width
1898     // might be reduced from max_width by something on the right.
1899     let budget = try_opt!(context
1900                               .config
1901                               .max_width()
1902                               .checked_sub(indent.len() + lbr.len() + rbr.len()));
1903     let index_str = try_opt!(index.rewrite(context, Shape::legacy(budget, shape.indent)));
1904     Some(format!("{}\n{}{}{}{}", expr_str, indent, lbr, index_str, rbr))
1905 }
1906
1907 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1908                           path: &ast::Path,
1909                           fields: &'a [ast::Field],
1910                           base: Option<&'a ast::Expr>,
1911                           span: Span,
1912                           shape: Shape)
1913                           -> Option<String> {
1914     debug!("rewrite_struct_lit: shape {:?}", shape);
1915
1916     enum StructLitField<'a> {
1917         Regular(&'a ast::Field),
1918         Base(&'a ast::Expr),
1919     }
1920
1921     // 2 = " {".len()
1922     let path_shape = try_opt!(shape.sub_width(2));
1923     let path_str = try_opt!(rewrite_path(context, PathContext::Expr, None, path, path_shape));
1924
1925     if fields.len() == 0 && base.is_none() {
1926         return Some(format!("{} {{}}", path_str));
1927     }
1928
1929     let field_iter = fields
1930         .into_iter()
1931         .map(StructLitField::Regular)
1932         .chain(base.into_iter().map(StructLitField::Base));
1933
1934     // Foo { a: Foo } - indent is +3, width is -5.
1935     let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
1936
1937     let span_lo = |item: &StructLitField| match *item {
1938         StructLitField::Regular(field) => field.span.lo,
1939         StructLitField::Base(expr) => {
1940             let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
1941             let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
1942             let pos = snippet.find_uncommented("..").unwrap();
1943             last_field_hi + BytePos(pos as u32)
1944         }
1945     };
1946     let span_hi = |item: &StructLitField| match *item {
1947         StructLitField::Regular(field) => field.span.hi,
1948         StructLitField::Base(expr) => expr.span.hi,
1949     };
1950     let rewrite = |item: &StructLitField| match *item {
1951         StructLitField::Regular(field) => {
1952             // The 1 taken from the v_budget is for the comma.
1953             rewrite_field(context, field, try_opt!(v_shape.sub_width(1)))
1954         }
1955         StructLitField::Base(expr) => {
1956             // 2 = ..
1957             expr.rewrite(context, try_opt!(v_shape.shrink_left(2)))
1958                 .map(|s| format!("..{}", s))
1959         }
1960     };
1961
1962     let items = itemize_list(context.codemap,
1963                              field_iter,
1964                              "}",
1965                              span_lo,
1966                              span_hi,
1967                              rewrite,
1968                              context.codemap.span_after(span, "{"),
1969                              span.hi);
1970     let item_vec = items.collect::<Vec<_>>();
1971
1972     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1973     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1974     let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
1975
1976     let fields_str = try_opt!(write_list(&item_vec, &fmt));
1977     let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
1978                         (fields_str.contains('\n') ||
1979                          context.config.struct_lit_multiline_style() ==
1980                          MultilineStyle::ForceMulti ||
1981                          fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) {
1982         format!("\n{}{}\n{}",
1983                 v_shape.indent.to_string(context.config),
1984                 fields_str,
1985                 shape.indent.to_string(context.config))
1986     } else {
1987         // One liner or visual indent.
1988         format!(" {} ", fields_str)
1989     };
1990
1991     Some(format!("{} {{{}}}", path_str, fields_str))
1992
1993     // FIXME if context.config.struct_lit_style() == Visual, but we run out
1994     // of space, we should fall back to BlockIndent.
1995 }
1996
1997 pub fn type_annotation_separator(config: &Config) -> &str {
1998     colon_spaces(config.space_before_type_annotation(),
1999                  config.space_after_type_annotation_colon())
2000 }
2001
2002 fn rewrite_field(context: &RewriteContext, field: &ast::Field, shape: Shape) -> Option<String> {
2003     let name = &field.ident.node.to_string();
2004     if field.is_shorthand {
2005         Some(name.to_string())
2006     } else {
2007         let separator = type_annotation_separator(context.config);
2008         let overhead = name.len() + separator.len();
2009         let mut expr_shape = try_opt!(shape.sub_width(overhead));
2010         expr_shape.offset += overhead;
2011         let expr = field.expr.rewrite(context, expr_shape);
2012
2013         let mut attrs_str = try_opt!((*field.attrs).rewrite(context, shape));
2014         if !attrs_str.is_empty() {
2015             attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2016         };
2017
2018         match expr {
2019             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2020             None => {
2021                 let expr_offset = shape.indent.block_indent(context.config);
2022                 let expr = field
2023                     .expr
2024                     .rewrite(context, Shape::indented(expr_offset, context.config));
2025                 expr.map(|s| {
2026                              format!("{}{}:\n{}{}",
2027                                      attrs_str,
2028                                      name,
2029                                      expr_offset.to_string(&context.config),
2030                                      s)
2031                          })
2032             }
2033         }
2034     }
2035 }
2036
2037 fn shape_from_fn_call_style(context: &RewriteContext,
2038                             shape: Shape,
2039                             overhead: usize,
2040                             offset: usize)
2041                             -> Option<Shape> {
2042     match context.config.fn_call_style() {
2043         IndentStyle::Block => Some(shape.block().block_indent(context.config.tab_spaces())),
2044         IndentStyle::Visual => shape.visual_indent(offset).sub_width(overhead),
2045     }
2046 }
2047
2048 pub fn rewrite_tuple_type<'a, I>(context: &RewriteContext,
2049                                  mut items: I,
2050                                  span: Span,
2051                                  shape: Shape)
2052                                  -> Option<String>
2053     where I: ExactSizeIterator,
2054           <I as Iterator>::Item: Deref,
2055           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
2056 {
2057     // In case of length 1, need a trailing comma
2058     debug!("rewrite_tuple_type {:?}", shape);
2059     if items.len() == 1 {
2060         // 3 = "(" + ",)"
2061         let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
2062         return items
2063             .next()
2064             .unwrap()
2065             .rewrite(context, nested_shape)
2066             .map(|s| if context.config.spaces_within_parens() {
2067                      format!("( {}, )", s)
2068                  } else {
2069                      format!("({},)", s)
2070                  });
2071     }
2072
2073     let list_lo = context.codemap.span_after(span, "(");
2074     let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
2075     let items = itemize_list(context.codemap,
2076                              items,
2077                              ")",
2078                              |item| item.span().lo,
2079                              |item| item.span().hi,
2080                              |item| item.rewrite(context, nested_shape),
2081                              list_lo,
2082                              span.hi - BytePos(1));
2083     let list_str = try_opt!(format_item_list(items, nested_shape, context.config));
2084
2085     if context.config.spaces_within_parens() && list_str.len() > 0 {
2086         Some(format!("( {} )", list_str))
2087     } else {
2088         Some(format!("({})", list_str))
2089     }
2090 }
2091
2092 pub fn rewrite_tuple(context: &RewriteContext,
2093                      items: &[ptr::P<ast::Expr>],
2094                      span: Span,
2095                      shape: Shape)
2096                      -> Option<String> {
2097     debug!("rewrite_tuple {:?}", shape);
2098     // Use old `rewrite_tuple`
2099     if context.config.fn_call_style() == IndentStyle::Visual {
2100         return rewrite_tuple_type(context, items.iter().map(|x| &**x), span, shape);
2101     }
2102
2103     // We use the same rule as funcation call for rewriting tuple.
2104     // 1 = ","
2105     rewrite_call_inner(context,
2106                        &String::new(),
2107                        shape.width.checked_sub(1).unwrap_or(0),
2108                        items,
2109                        span,
2110                        shape,
2111                        items.len() == 1)
2112         .ok()
2113 }
2114
2115 pub fn rewrite_unary_prefix<R: Rewrite>(context: &RewriteContext,
2116                                         prefix: &str,
2117                                         rewrite: &R,
2118                                         shape: Shape)
2119                                         -> Option<String> {
2120     rewrite
2121         .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
2122         .map(|r| format!("{}{}", prefix, r))
2123 }
2124
2125 // FIXME: this is probably not correct for multi-line Rewrites. we should
2126 // subtract suffix.len() from the last line budget, not the first!
2127 pub fn rewrite_unary_suffix<R: Rewrite>(context: &RewriteContext,
2128                                         suffix: &str,
2129                                         rewrite: &R,
2130                                         shape: Shape)
2131                                         -> Option<String> {
2132     rewrite
2133         .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
2134         .map(|mut r| {
2135                  r.push_str(suffix);
2136                  r
2137              })
2138 }
2139
2140 fn rewrite_unary_op(context: &RewriteContext,
2141                     op: &ast::UnOp,
2142                     expr: &ast::Expr,
2143                     shape: Shape)
2144                     -> Option<String> {
2145     // For some reason, an UnOp is not spanned like BinOp!
2146     let operator_str = match *op {
2147         ast::UnOp::Deref => "*",
2148         ast::UnOp::Not => "!",
2149         ast::UnOp::Neg => "-",
2150     };
2151     rewrite_unary_prefix(context, operator_str, expr, shape)
2152 }
2153
2154 fn rewrite_assignment(context: &RewriteContext,
2155                       lhs: &ast::Expr,
2156                       rhs: &ast::Expr,
2157                       op: Option<&ast::BinOp>,
2158                       shape: Shape)
2159                       -> Option<String> {
2160     let operator_str = match op {
2161         Some(op) => context.snippet(op.span),
2162         None => "=".to_owned(),
2163     };
2164
2165     // 1 = space between lhs and operator.
2166     let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
2167     let lhs_str = format!("{} {}",
2168                           try_opt!(lhs.rewrite(context, lhs_shape)),
2169                           operator_str);
2170
2171     rewrite_assign_rhs(context, lhs_str, rhs, shape)
2172 }
2173
2174 // The left hand side must contain everything up to, and including, the
2175 // assignment operator.
2176 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
2177                                            lhs: S,
2178                                            ex: &ast::Expr,
2179                                            shape: Shape)
2180                                            -> Option<String> {
2181     let mut result = lhs.into();
2182     let last_line_width = last_line_width(&result) -
2183                           if result.contains('\n') {
2184                               shape.indent.width()
2185                           } else {
2186                               0
2187                           };
2188     // 1 = space between operator and rhs.
2189     let orig_shape = try_opt!(shape.block_indent(0).offset_left(last_line_width + 1));
2190     let rhs = match ex.node {
2191         ast::ExprKind::Mac(ref mac) => {
2192             match rewrite_macro(mac, None, context, orig_shape, MacroPosition::Expression) {
2193                 None if !context.snippet(ex.span).contains("\n") => {
2194                     context.snippet(ex.span).rewrite(context, orig_shape)
2195                 }
2196                 rhs @ _ => rhs,
2197             }
2198         }
2199         _ => ex.rewrite(context, orig_shape),
2200     };
2201
2202     fn count_line_breaks(src: &str) -> usize {
2203         src.chars().filter(|&x| x == '\n').count()
2204     }
2205
2206     match rhs {
2207         Some(ref new_str) if count_line_breaks(new_str) < 2 => {
2208             result.push(' ');
2209             result.push_str(new_str);
2210         }
2211         _ => {
2212             // Expression did not fit on the same line as the identifier or is
2213             // at least three lines big. Try splitting the line and see
2214             // if that works better.
2215             let new_shape = try_opt!(shape.block_left(context.config.tab_spaces()));
2216             let new_rhs = ex.rewrite(context, new_shape);
2217
2218             // FIXME: DRY!
2219             match (rhs, new_rhs) {
2220                 (Some(ref orig_rhs), Some(ref replacement_rhs))
2221                     if count_line_breaks(orig_rhs) > count_line_breaks(replacement_rhs) + 1 ||
2222                        (orig_rhs.rewrite(context, shape).is_none() &&
2223                         replacement_rhs.rewrite(context, new_shape).is_some()) => {
2224                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2225                     result.push_str(replacement_rhs);
2226                 }
2227                 (None, Some(ref final_rhs)) => {
2228                     result.push_str(&format!("\n{}", new_shape.indent.to_string(context.config)));
2229                     result.push_str(final_rhs);
2230                 }
2231                 (None, None) => return None,
2232                 (Some(ref orig_rhs), _) => {
2233                     result.push(' ');
2234                     result.push_str(orig_rhs);
2235                 }
2236             }
2237         }
2238     }
2239
2240     Some(result)
2241 }
2242
2243 fn rewrite_expr_addrof(context: &RewriteContext,
2244                        mutability: ast::Mutability,
2245                        expr: &ast::Expr,
2246                        shape: Shape)
2247                        -> Option<String> {
2248     let operator_str = match mutability {
2249         ast::Mutability::Immutable => "&",
2250         ast::Mutability::Mutable => "&mut ",
2251     };
2252     rewrite_unary_prefix(context, operator_str, expr, shape)
2253 }