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