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