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