]> git.lizzy.rs Git - rust.git/blobdiff - src/expr.rs
Implement match_arm_forces_newline option (#2039)
[rust.git] / src / expr.rs
index 0276b68ac9fe3517592198e055e22429d58a084d..51dc7a9bb7a688f0939ded99b0bb74fa9adbb763 100644 (file)
@@ -8,33 +8,34 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::cmp::{min, Ordering};
-use std::fmt::Write;
-use std::iter::ExactSizeIterator;
+use std::cmp::min;
+use std::borrow::Cow;
+use std::iter::{repeat, ExactSizeIterator};
 
 use syntax::{ast, ptr};
 use syntax::codemap::{BytePos, CodeMap, Span};
 use syntax::parse::classify;
 
-use {Indent, Shape, Spanned};
+use spanned::Spanned;
 use chains::rewrite_chain;
 use codemap::{LineRangeUtils, SpanUtils};
 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
-              rewrite_comment, FindUncommented};
+              rewrite_comment, rewrite_missing_comment, FindUncommented};
 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
 use items::{span_hi_for_arg, span_lo_for_arg};
 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
             struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
-            ListItem, ListTactic, Separator, SeparatorTactic};
-use macros::{rewrite_macro, MacroPosition};
+            ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
+use macros::{rewrite_macro, MacroArg, MacroPosition};
 use patterns::{can_be_overflowed_pat, TuplePatField};
 use rewrite::{Rewrite, RewriteContext};
+use shape::{Indent, Shape};
 use string::{rewrite_string, StringFormat};
 use types::{can_be_overflowed_type, rewrite_path, PathContext};
-use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
-            inner_attributes, last_line_extendable, last_line_width, left_most_sub_expr, mk_sp,
-            outer_attributes, paren_overhead, semicolon_for_stmt, stmt_expr,
-            trimmed_last_line_width, wrap_str};
+use utils::{colon_spaces, contains_skip, extra_offset, first_line_width, inner_attributes,
+            last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, outer_attributes,
+            paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, stmt_expr,
+            trimmed_last_line_width};
 use vertical::rewrite_with_alignment;
 use visitor::FmtVisitor;
 
@@ -44,7 +45,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
     }
 }
 
-#[derive(PartialEq)]
+#[derive(Copy, Clone, PartialEq)]
 pub enum ExprType {
     Statement,
     SubExpression,
@@ -65,30 +66,16 @@ pub fn format_expr(
     let expr_rw = match expr.node {
         ast::ExprKind::Array(ref expr_vec) => rewrite_array(
             expr_vec.iter().map(|e| &**e),
-            mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
+            mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
             context,
             shape,
             false,
         ),
-        ast::ExprKind::Lit(ref l) => match l.node {
-            ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
-                rewrite_string_lit(context, l.span, shape)
-            }
-            _ => wrap_str(
-                context.snippet(expr.span),
-                context.config.max_width(),
-                shape,
-            ),
-        },
+        ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
         ast::ExprKind::Call(ref callee, ref args) => {
-            let inner_span = mk_sp(callee.span.hi, expr.span.hi);
-            rewrite_call_with_binary_search(
-                context,
-                &**callee,
-                &args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
-                inner_span,
-                shape,
-            )
+            let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
+            let callee_str = callee.rewrite(context, shape)?;
+            rewrite_call(context, &callee_str, &args, inner_span, shape)
         }
         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
         ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
@@ -101,6 +88,7 @@ pub fn format_expr(
                 "",
                 context,
                 shape,
+                context.config.binop_separator(),
             )
         }
         ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
@@ -112,12 +100,9 @@ pub fn format_expr(
             expr.span,
             shape,
         ),
-        ast::ExprKind::Tup(ref items) => rewrite_tuple(
-            context,
-            &items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
-            expr.span,
-            shape,
-        ),
+        ast::ExprKind::Tup(ref items) => {
+            rewrite_tuple(context, &ptr_vec_to_ref_vec(&items), expr.span, shape)
+        }
         ast::ExprKind::If(..) |
         ast::ExprKind::IfLet(..) |
         ast::ExprKind::ForLoop(..) |
@@ -130,12 +115,11 @@ pub fn format_expr(
                 ExprType::Statement => {
                     if is_unsafe_block(block) {
                         block.rewrite(context, shape)
-                    } else {
+                    } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
                         // Rewrite block without trying to put it in a single line.
-                        if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
-                            return rw;
-                        }
-                        let prefix = try_opt!(block_prefix(context, block, shape));
+                        rw
+                    } else {
+                        let prefix = block_prefix(context, block, shape)?;
                         rewrite_block_with_visitor(context, &prefix, block, shape)
                     }
                 }
@@ -159,11 +143,7 @@ pub fn format_expr(
                 Some(ident) => format!(" {}", ident.node),
                 None => String::new(),
             };
-            wrap_str(
-                format!("continue{}", id_str),
-                context.config.max_width(),
-                shape,
-            )
+            Some(format!("continue{}", id_str))
         }
         ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
             let id_str = match *opt_ident {
@@ -174,13 +154,14 @@ pub fn format_expr(
             if let Some(ref expr) = *opt_expr {
                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
             } else {
-                wrap_str(
-                    format!("break{}", id_str),
-                    context.config.max_width(),
-                    shape,
-                )
+                Some(format!("break{}", id_str))
             }
         }
+        ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
+            rewrite_unary_prefix(context, "yield ", &**expr, shape)
+        } else {
+            Some("yield".to_string())
+        },
         ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
             rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
         }
@@ -191,17 +172,10 @@ pub fn format_expr(
         ast::ExprKind::Mac(ref mac) => {
             // Failure to rewrite a marco should not imply failure to
             // rewrite the expression.
-            rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
-                wrap_str(
-                    context.snippet(expr.span),
-                    context.config.max_width(),
-                    shape,
-                )
-            })
-        }
-        ast::ExprKind::Ret(None) => {
-            wrap_str("return".to_owned(), context.config.max_width(), shape)
+            rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
+                .or_else(|| Some(context.snippet(expr.span)))
         }
+        ast::ExprKind::Ret(None) => Some("return".to_owned()),
         ast::ExprKind::Ret(Some(ref expr)) => {
             rewrite_unary_prefix(context, "return ", &**expr, shape)
         }
@@ -209,12 +183,26 @@ pub fn format_expr(
         ast::ExprKind::AddrOf(mutability, ref expr) => {
             rewrite_expr_addrof(context, mutability, expr, shape)
         }
-        ast::ExprKind::Cast(ref expr, ref ty) => {
-            rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
-        }
-        ast::ExprKind::Type(ref expr, ref ty) => {
-            rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
-        }
+        ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
+            &**expr,
+            &**ty,
+            "",
+            " as ",
+            "",
+            context,
+            shape,
+            SeparatorPlace::Front,
+        ),
+        ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
+            &**expr,
+            &**ty,
+            "",
+            ": ",
+            "",
+            context,
+            shape,
+            SeparatorPlace::Back,
+        ),
         ast::ExprKind::Index(ref expr, ref index) => {
             rewrite_index(&**expr, &**index, context, shape)
         }
@@ -224,12 +212,21 @@ pub fn format_expr(
             } else {
                 ("[", "]")
             };
-            rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
+            rewrite_pair(
+                &**expr,
+                &**repeats,
+                lbr,
+                "; ",
+                rbr,
+                context,
+                shape,
+                SeparatorPlace::Back,
+            )
         }
         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
             let delim = match limits {
                 ast::RangeLimits::HalfOpen => "..",
-                ast::RangeLimits::Closed => "...",
+                ast::RangeLimits::Closed => "..=",
             };
 
             fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
@@ -245,7 +242,7 @@ fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
             }
 
             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
-                (Some(ref lhs), Some(ref rhs)) => {
+                (Some(lhs), Some(rhs)) => {
                     let sp_delim = if context.config.spaces_around_ranges() {
                         format!(" {} ", delim)
                     } else if needs_space_before_range(context, lhs) {
@@ -253,59 +250,66 @@ fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
                     } else {
                         delim.into()
                     };
-                    rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
+                    rewrite_pair(
+                        &*lhs,
+                        &*rhs,
+                        "",
+                        &sp_delim,
+                        "",
+                        context,
+                        shape,
+                        SeparatorPlace::Front,
+                    )
                 }
-                (None, Some(ref rhs)) => {
+                (None, Some(rhs)) => {
                     let sp_delim = if context.config.spaces_around_ranges() {
                         format!("{} ", delim)
                     } else {
                         delim.into()
                     };
-                    rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
+                    rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
                 }
-                (Some(ref lhs), None) => {
+                (Some(lhs), None) => {
                     let sp_delim = if context.config.spaces_around_ranges() {
                         format!(" {}", delim)
                     } else {
                         delim.into()
                     };
-                    rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
+                    rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
                 }
-                (None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
+                (None, None) => Some(delim.into()),
             }
         }
         // We do not format these expressions yet, but they should still
         // satisfy our width restrictions.
-        ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
-            context.snippet(expr.span),
-            context.config.max_width(),
-            shape,
-        ),
+        ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
+            Some(context.snippet(expr.span))
+        }
         ast::ExprKind::Catch(ref block) => {
-            if let rewrite @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape)
-            {
-                return rewrite;
+            if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
+                rw
+            } else {
+                // 9 = `do catch `
+                let budget = shape.width.checked_sub(9).unwrap_or(0);
+                Some(format!(
+                    "{}{}",
+                    "do catch ",
+                    block.rewrite(context, Shape::legacy(budget, shape.indent))?
+                ))
             }
-            // 9 = `do catch `
-            let budget = shape.width.checked_sub(9).unwrap_or(0);
-            Some(format!(
-                "{}{}",
-                "do catch ",
-                try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
-            ))
         }
     };
 
     expr_rw
         .and_then(|expr_str| {
-            recover_comment_removed(expr_str, expr.span, context, shape)
+            recover_comment_removed(expr_str, expr.span, context)
         })
         .and_then(|expr_str| {
             let attrs = outer_attributes(&expr.attrs);
-            let attrs_str = try_opt!(attrs.rewrite(context, shape));
+            let attrs_str = attrs.rewrite(context, shape)?;
             let span = mk_sp(
-                attrs.last().map_or(expr.span.lo, |attr| attr.span.hi),
-                expr.span.lo,
+                attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
+                expr.span.lo(),
             );
             combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
         })
@@ -319,26 +323,27 @@ pub fn rewrite_pair<LHS, RHS>(
     suffix: &str,
     context: &RewriteContext,
     shape: Shape,
+    separator_place: SeparatorPlace,
 ) -> Option<String>
 where
     LHS: Rewrite,
     RHS: Rewrite,
 {
-    let sep = if infix.ends_with(' ') { " " } else { "" };
-    let infix = infix.trim_right();
-    let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
+    let lhs_overhead = match separator_place {
+        SeparatorPlace::Back => shape.used_width() + prefix.len() + infix.trim_right().len(),
+        SeparatorPlace::Front => shape.used_width(),
+    };
     let lhs_shape = Shape {
-        width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
+        width: context.budget(lhs_overhead),
         ..shape
     };
-    let lhs_result = try_opt!(
-        lhs.rewrite(context, lhs_shape)
-            .map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
-    );
+    let lhs_result = lhs.rewrite(context, lhs_shape)
+        .map(|lhs_str| format!("{}{}", prefix, lhs_str))?;
 
     // Try to the both lhs and rhs on the same line.
     let rhs_orig_result = shape
-        .offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
+        .offset_left(last_line_width(&lhs_result) + infix.len())
+        .and_then(|s| s.sub_width(suffix.len()))
         .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
     if let Some(ref rhs_result) = rhs_orig_result {
         // If the rhs looks like block expression, we allow it to stay on the same line
@@ -349,33 +354,53 @@ pub fn rewrite_pair<LHS, RHS>(
             .map(|first_line| first_line.ends_with('{'))
             .unwrap_or(false);
         if !rhs_result.contains('\n') || allow_same_line {
-            return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
+            let one_line_width = last_line_width(&lhs_result) + infix.len()
+                + first_line_width(&rhs_result) + suffix.len();
+            if one_line_width <= shape.width {
+                return Some(format!("{}{}{}{}", lhs_result, infix, rhs_result, suffix));
+            }
         }
     }
 
     // We have to use multiple lines.
     // Re-evaluate the rhs because we have more space now:
-    let rhs_shape = match context.config.control_style() {
-        Style::Legacy => {
-            try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
-        }
+    let mut rhs_shape = match context.config.control_style() {
+        Style::Legacy => shape
+            .sub_width(suffix.len() + prefix.len())?
+            .visual_indent(prefix.len()),
         Style::Rfc => {
             // Try to calculate the initial constraint on the right hand side.
             let rhs_overhead = shape.rhs_overhead(context.config);
-            try_opt!(
-                Shape::indented(shape.indent.block_indent(context.config), context.config)
-                    .sub_width(rhs_overhead)
-            )
+            Shape::indented(shape.indent.block_indent(context.config), context.config)
+                .sub_width(rhs_overhead)?
         }
     };
-    let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
-    Some(format!(
-        "{}\n{}{}{}",
-        lhs_result,
-        rhs_shape.indent.to_string(context.config),
-        rhs_result,
-        suffix
-    ))
+    let infix = match separator_place {
+        SeparatorPlace::Back => infix.trim_right(),
+        SeparatorPlace::Front => infix.trim_left(),
+    };
+    if separator_place == SeparatorPlace::Front {
+        rhs_shape = rhs_shape.offset_left(infix.len())?;
+    }
+    let rhs_result = rhs.rewrite(context, rhs_shape)?;
+    match separator_place {
+        SeparatorPlace::Back => Some(format!(
+            "{}{}\n{}{}{}",
+            lhs_result,
+            infix,
+            rhs_shape.indent.to_string(context.config),
+            rhs_result,
+            suffix
+        )),
+        SeparatorPlace::Front => Some(format!(
+            "{}\n{}{}{}{}",
+            lhs_result,
+            rhs_shape.indent.to_string(context.config),
+            infix,
+            rhs_result,
+            suffix
+        )),
+    }
 }
 
 pub fn rewrite_array<'a, I>(
@@ -395,29 +420,25 @@ pub fn rewrite_array<'a, I>(
     };
 
     let nested_shape = match context.config.array_layout() {
-        IndentStyle::Block => try_opt!(
-            shape
-                .block()
-                .block_indent(context.config.tab_spaces())
-                .with_max_width(context.config)
-                .sub_width(1)
-        ),
-        IndentStyle::Visual => try_opt!(
-            shape
-                .visual_indent(bracket_size)
-                .sub_width(bracket_size * 2)
-        ),
+        IndentStyle::Block => shape
+            .block()
+            .block_indent(context.config.tab_spaces())
+            .with_max_width(context.config)
+            .sub_width(1)?,
+        IndentStyle::Visual => shape
+            .visual_indent(bracket_size)
+            .sub_width(bracket_size * 2)?,
     };
 
     let items = itemize_list(
         context.codemap,
         expr_iter,
         "]",
-        |item| item.span.lo,
-        |item| item.span.hi,
+        |item| item.span.lo(),
+        |item| item.span.hi(),
         |item| item.rewrite(context, nested_shape),
-        span.lo,
-        span.hi,
+        span.lo(),
+        span.hi(),
         false,
     ).collect::<Vec<_>>();
 
@@ -457,8 +478,8 @@ pub fn rewrite_array<'a, I>(
         },
     };
     let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
-    if context.config.array_horizontal_layout_threshold() > 0 &&
-        items.len() > context.config.array_horizontal_layout_threshold()
+    if context.config.array_horizontal_layout_threshold() > 0
+        && items.len() > context.config.array_horizontal_layout_threshold()
     {
         tactic = DefinitiveListTactic::Mixed;
     }
@@ -473,17 +494,18 @@ pub fn rewrite_array<'a, I>(
         } else {
             SeparatorTactic::Vertical
         },
+        separator_place: SeparatorPlace::Back,
         shape: nested_shape,
         ends_with_newline: ends_with_newline,
         preserve_newline: false,
         config: context.config,
     };
-    let list_str = try_opt!(write_list(&items, &fmt));
+    let list_str = write_list(&items, &fmt)?;
 
-    let result = if context.config.array_layout() == IndentStyle::Visual ||
-        tactic == DefinitiveListTactic::Horizontal
+    let result = if context.config.array_layout() == IndentStyle::Visual
+        || tactic == DefinitiveListTactic::Horizontal
     {
-        if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
+        if context.config.spaces_within_square_brackets() && !list_str.is_empty() {
             format!("[ {} ]", list_str)
         } else {
             format!("[{}]", list_str)
@@ -516,12 +538,12 @@ fn rewrite_closure_fn_decl(
     };
     // 4 = "|| {".len(), which is overconservative when the closure consists of
     // a single expression.
-    let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
+    let nested_shape = shape.shrink_left(mover.len())?.sub_width(4)?;
 
     // 1 = |
     let argument_offset = nested_shape.indent + 1;
-    let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
-    let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
+    let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
+    let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
 
     let arg_items = itemize_list(
         context.codemap,
@@ -531,7 +553,7 @@ fn rewrite_closure_fn_decl(
         |arg| span_hi_for_arg(context, arg),
         |arg| arg.rewrite(context, arg_shape),
         context.codemap.span_after(span, "|"),
-        body.span.lo,
+        body.span.lo(),
         false,
     );
     let item_vec = arg_items.collect::<Vec<_>>();
@@ -547,7 +569,7 @@ fn rewrite_closure_fn_decl(
         horizontal_budget,
     );
     let arg_shape = match tactic {
-        DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
+        DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
         _ => arg_shape,
     };
 
@@ -555,15 +577,14 @@ fn rewrite_closure_fn_decl(
         tactic: tactic,
         separator: ",",
         trailing_separator: SeparatorTactic::Never,
+        separator_place: SeparatorPlace::Back,
         shape: arg_shape,
         ends_with_newline: false,
         preserve_newline: true,
         config: context.config,
     };
-    let list_str = try_opt!(write_list(&item_vec, &fmt));
+    let list_str = write_list(&item_vec, &fmt)?;
     let mut prefix = format!("{}|{}|", mover, list_str);
-    // 1 = space between `|...|` and body.
-    let extra_offset = extra_offset(&prefix, shape) + 1;
 
     if !ret_str.is_empty() {
         if prefix.contains('\n') {
@@ -574,6 +595,8 @@ fn rewrite_closure_fn_decl(
         }
         prefix.push_str(&ret_str);
     }
+    // 1 = space between `|...|` and body.
+    let extra_offset = last_line_width(&prefix) + 1;
 
     Some((prefix, extra_offset))
 }
@@ -595,16 +618,10 @@ fn rewrite_closure(
     context: &RewriteContext,
     shape: Shape,
 ) -> Option<String> {
-    let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
-        capture,
-        fn_decl,
-        body,
-        span,
-        context,
-        shape,
-    ));
+    let (prefix, extra_offset) =
+        rewrite_closure_fn_decl(capture, fn_decl, body, span, context, shape)?;
     // 1 = space between `|...|` and body.
-    let body_shape = try_opt!(shape.offset_left(extra_offset));
+    let body_shape = shape.offset_left(extra_offset)?;
 
     if let ast::ExprKind::Block(ref block) = body.node {
         // The body of the closure is an empty block.
@@ -613,10 +630,10 @@ fn rewrite_closure(
         }
 
         // Figure out if the block is necessary.
-        let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
-            context.inside_macro ||
-            block_contains_comment(block, context.codemap) ||
-            prefix.contains('\n');
+        let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1
+            || context.inside_macro
+            || block_contains_comment(block, context.codemap)
+            || prefix.contains('\n');
 
         let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
             true
@@ -624,28 +641,16 @@ fn rewrite_closure(
             false
         };
         if no_return_type && !needs_block {
-            // lock.stmts.len() == 1
-            if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
+            // block.stmts.len() == 1
+            if let Some(expr) = stmt_expr(&block.stmts[0]) {
                 if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
                     return Some(rw);
                 }
             }
         }
 
-        if !needs_block {
-            // We need braces, but we might still prefer a one-liner.
-            let stmt = &block.stmts[0];
-            // 4 = braces and spaces.
-            if let Some(body_shape) = body_shape.sub_width(4) {
-                // Checks if rewrite succeeded and fits on a single line.
-                if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
-                    return Some(format!("{} {{ {} }}", prefix, rewrite));
-                }
-            }
-        }
-
         // Either we require a block, or tried without and failed.
-        rewrite_closure_block(&block, &prefix, context, body_shape)
+        rewrite_closure_block(block, &prefix, context, body_shape)
     } else {
         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
             // The closure originally had a non-block expression, but we can't fit on
@@ -688,6 +693,13 @@ fn rewrite_closure_expr(
     if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
         rewrite = and_one_line(rewrite);
     }
+    rewrite = rewrite.and_then(|rw| {
+        if context.config.multiline_closure_forces_block() && rw.contains('\n') {
+            None
+        } else {
+            Some(rw)
+        }
+    });
     rewrite.map(|rw| format!("{} {}", prefix, rw))
 }
 
@@ -702,13 +714,11 @@ fn rewrite_closure_block(
     // closure is large.
     let block_threshold = context.config.closure_block_indent_threshold();
     if block_threshold >= 0 {
-        if let Some(block_str) = block.rewrite(&context, shape) {
-            if block_str.matches('\n').count() <= block_threshold as usize &&
-                !need_block_indent(&block_str, shape)
+        if let Some(block_str) = block.rewrite(context, shape) {
+            if block_str.matches('\n').count() <= block_threshold as usize
+                && !need_block_indent(&block_str, shape)
             {
-                if let Some(block_str) = block_str.rewrite(context, shape) {
-                    return Some(format!("{} {}", prefix, block_str));
-                }
+                return Some(format!("{} {}", prefix, block_str));
             }
         }
     }
@@ -716,7 +726,7 @@ fn rewrite_closure_block(
     // The body of the closure is big enough to be block indented, that
     // means we must re-format.
     let block_shape = shape.block();
-    let block_str = try_opt!(block.rewrite(&context, block_shape));
+    let block_str = block.rewrite(context, block_shape)?;
     Some(format!("{} {}", prefix, block_str))
 }
 
@@ -727,8 +737,8 @@ fn and_one_line(x: Option<String>) -> Option<String> {
 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
     debug!("nop_block_collapse {:?} {}", block_str, budget);
     block_str.map(|block_str| {
-        if block_str.starts_with('{') && budget >= 2 &&
-            (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
+        if block_str.starts_with('{') && budget >= 2
+            && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
         {
             "{}".to_owned()
         } else {
@@ -752,8 +762,8 @@ fn rewrite_empty_block(
     let user_str = user_str.trim();
     if user_str.starts_with('{') && user_str.ends_with('}') {
         let comment_str = user_str[1..user_str.len() - 1].trim();
-        if block.stmts.is_empty() && !comment_str.contains('\n') &&
-            !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
+        if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
+            && comment_str.len() + 4 <= shape.width
         {
             return Some(format!("{{ {} }}", comment_str));
         }
@@ -766,21 +776,21 @@ fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> O
     Some(match block.rules {
         ast::BlockCheckMode::Unsafe(..) => {
             let snippet = context.snippet(block.span);
-            let open_pos = try_opt!(snippet.find_uncommented("{"));
+            let open_pos = snippet.find_uncommented("{")?;
             // Extract comment between unsafe and block start.
             let trimmed = &snippet[6..open_pos].trim();
 
             if !trimmed.is_empty() {
                 // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
-                let budget = try_opt!(shape.width.checked_sub(9));
+                let budget = shape.width.checked_sub(9)?;
                 format!(
                     "unsafe {} ",
-                    try_opt!(rewrite_comment(
+                    rewrite_comment(
                         trimmed,
                         true,
                         Shape::legacy(budget, shape.indent + 7),
                         context.config,
-                    ))
+                    )?
                 )
             } else {
                 "unsafe ".to_owned()
@@ -798,7 +808,7 @@ fn rewrite_single_line_block(
 ) -> Option<String> {
     if is_simple_block(block, context.codemap) {
         let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
-        let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
+        let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
         let result = format!("{}{{ {} }}", prefix, expr_str);
         if result.len() <= shape.width && !result.contains('\n') {
             return Some(result);
@@ -823,10 +833,10 @@ fn rewrite_block_with_visitor(
     match block.rules {
         ast::BlockCheckMode::Unsafe(..) => {
             let snippet = context.snippet(block.span);
-            let open_pos = try_opt!(snippet.find_uncommented("{"));
-            visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
+            let open_pos = snippet.find_uncommented("{")?;
+            visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
         }
-        ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
+        ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
     }
 
     visitor.visit_block(block, None);
@@ -841,12 +851,18 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             return rw;
         }
 
-        let prefix = try_opt!(block_prefix(context, self, shape));
-        if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
-            return rw;
+        let prefix = block_prefix(context, self, shape)?;
+
+        let result = rewrite_block_with_visitor(context, &prefix, self, shape);
+        if let Some(ref result_str) = result {
+            if result_str.lines().count() <= 3 {
+                if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
+                    return rw;
+                }
+            }
         }
 
-        rewrite_block_with_visitor(context, &prefix, self, shape)
+        result
     }
 }
 
@@ -863,22 +879,12 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                     ""
                 };
 
-                format_expr(
-                    ex,
-                    match self.node {
-                        ast::StmtKind::Expr(_) => ExprType::SubExpression,
-                        ast::StmtKind::Semi(_) => ExprType::Statement,
-                        _ => unreachable!(),
-                    },
-                    context,
-                    try_opt!(shape.sub_width(suffix.len())),
-                ).map(|s| s + suffix)
+                let shape = shape.sub_width(suffix.len())?;
+                format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
             }
             ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
         };
-        result.and_then(|res| {
-            recover_comment_removed(res, self.span(), context, shape)
-        })
+        result.and_then(|res| recover_comment_removed(res, self.span(), context))
     }
 }
 
@@ -888,8 +894,8 @@ fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Opt
         ast::ExprKind::Match(ref cond, _) => {
             // `match `cond` {`
             let cond_shape = match context.config.control_style() {
-                Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
-                Style::Rfc => try_opt!(shape.offset_left(8)),
+                Style::Legacy => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
+                Style::Rfc => shape.offset_left(8)?,
             };
             cond.rewrite(context, cond_shape)
         }
@@ -1063,25 +1069,24 @@ fn rewrite_single_line(
         width: usize,
     ) -> Option<String> {
         assert!(self.allow_single_line);
-        let else_block = try_opt!(self.else_block);
+        let else_block = self.else_block?;
         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
 
         if let ast::ExprKind::Block(ref else_node) = else_block.node {
-            if !is_simple_block(self.block, context.codemap) ||
-                !is_simple_block(else_node, context.codemap) ||
-                pat_expr_str.contains('\n')
+            if !is_simple_block(self.block, context.codemap)
+                || !is_simple_block(else_node, context.codemap)
+                || pat_expr_str.contains('\n')
             {
                 return None;
             }
 
-            let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
+            let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
             let expr = &self.block.stmts[0];
-            let if_str = try_opt!(expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
+            let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
 
-            let new_width = try_opt!(new_width.checked_sub(if_str.len()));
+            let new_width = new_width.checked_sub(if_str.len())?;
             let else_expr = &else_node.stmts[0];
-            let else_str =
-                try_opt!(else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty())));
+            let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
 
             if if_str.contains('\n') || else_str.contains('\n') {
                 return None;
@@ -1125,7 +1130,7 @@ fn rewrite_cond(
         let constr_shape = if self.nested_if {
             // We are part of an if-elseif-else chain. Our constraints are tightened.
             // 7 = "} else " .len()
-            try_opt!(fresh_shape.offset_left(7))
+            fresh_shape.offset_left(7)?
         } else {
             fresh_shape
         };
@@ -1137,10 +1142,10 @@ fn rewrite_cond(
         let pat_expr_string = match self.cond {
             Some(cond) => {
                 let cond_shape = match context.config.control_style() {
-                    Style::Legacy => try_opt!(constr_shape.shrink_left(offset)),
-                    Style::Rfc => try_opt!(constr_shape.offset_left(offset)),
+                    Style::Legacy => constr_shape.shrink_left(offset)?,
+                    Style::Rfc => constr_shape.offset_left(offset)?,
                 };
-                try_opt!(rewrite_pat_expr(
+                rewrite_pat_expr(
                     context,
                     self.pat,
                     cond,
@@ -1148,7 +1153,7 @@ fn rewrite_cond(
                     self.connector,
                     self.keyword,
                     cond_shape,
-                ))
+                )?
             }
             None => String::new(),
         };
@@ -1165,9 +1170,9 @@ fn rewrite_cond(
             .max_width()
             .checked_sub(constr_shape.used_width() + offset + brace_overhead)
             .unwrap_or(0);
-        let force_newline_brace = context.config.control_style() == Style::Rfc &&
-            (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget) &&
-            !last_line_extendable(&pat_expr_string);
+        let force_newline_brace = context.config.control_style() == Style::Rfc
+            && (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget)
+            && !last_line_extendable(&pat_expr_string);
 
         // Try to format if-else on single line.
         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
@@ -1183,15 +1188,19 @@ fn rewrite_cond(
         let cond_span = if let Some(cond) = self.cond {
             cond.span
         } else {
-            mk_sp(self.block.span.lo, self.block.span.lo)
+            mk_sp(self.block.span.lo(), self.block.span.lo())
         };
 
-        // for event in event
+        // `for event in event`
+        // Do not include label in the span.
+        let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
         let between_kwd_cond = mk_sp(
-            context.codemap.span_after(self.span, self.keyword.trim()),
+            context
+                .codemap
+                .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
             self.pat
-                .map_or(cond_span.lo, |p| if self.matcher.is_empty() {
-                    p.span.lo
+                .map_or(cond_span.lo(), |p| if self.matcher.is_empty() {
+                    p.span.lo()
                 } else {
                     context.codemap.span_before(self.span, self.matcher.trim())
                 }),
@@ -1200,12 +1209,12 @@ fn rewrite_cond(
         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
 
         let after_cond_comment =
-            extract_comment(mk_sp(cond_span.hi, self.block.span.lo), context, shape);
+            extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
 
         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
             ""
-        } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine ||
-            force_newline_brace
+        } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
+            || force_newline_brace
         {
             alt_block_sep
         } else {
@@ -1246,7 +1255,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
         let alt_block_sep =
             String::from("\n") + &shape.indent.block_only().to_string(context.config);
-        let (cond_str, used_width) = try_opt!(self.rewrite_cond(context, shape, &alt_block_sep));
+        let (cond_str, used_width) = self.rewrite_cond(context, shape, &alt_block_sep)?;
         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
         if used_width == 0 {
             return Some(cond_str);
@@ -1266,12 +1275,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         };
         let mut block_context = context.clone();
         block_context.is_if_else_block = self.else_block.is_some();
-        let block_str = try_opt!(rewrite_block_with_visitor(
-            &block_context,
-            "",
-            self.block,
-            block_shape,
-        ));
+        let block_str = rewrite_block_with_visitor(&block_context, "", self.block, block_shape)?;
 
         let mut result = format!("{}{}", cond_str, block_str);
 
@@ -1291,7 +1295,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                         next_else_block.as_ref().map(|e| &**e),
                         false,
                         true,
-                        mk_sp(else_block.span.lo, self.span.hi),
+                        mk_sp(else_block.span.lo(), self.span.hi()),
                     ).rewrite(context, shape)
                 }
                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
@@ -1302,7 +1306,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                         next_else_block.as_ref().map(|e| &**e),
                         false,
                         true,
-                        mk_sp(else_block.span.lo, self.span.hi),
+                        mk_sp(else_block.span.lo(), self.span.hi()),
                     ).rewrite(context, shape)
                 }
                 _ => {
@@ -1318,10 +1322,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             };
 
             let between_kwd_else_block = mk_sp(
-                self.block.span.hi,
+                self.block.span.hi(),
                 context
                     .codemap
-                    .span_before(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
+                    .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
             );
             let between_kwd_else_block_comment =
                 extract_comment(between_kwd_else_block, context, shape);
@@ -1329,8 +1333,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             let after_else = mk_sp(
                 context
                     .codemap
-                    .span_after(mk_sp(self.block.span.hi, else_block.span.lo), "else"),
-                else_block.span.lo,
+                    .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
+                else_block.span.lo(),
             );
             let after_else_comment = extract_comment(after_else, context, shape);
 
@@ -1344,46 +1348,36 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
                 _ => " ",
             };
-            try_opt!(
-                write!(
-                    &mut result,
-                    "{}else{}",
-                    between_kwd_else_block_comment
-                        .as_ref()
-                        .map_or(between_sep, |s| &**s),
-                    after_else_comment.as_ref().map_or(after_sep, |s| &**s)
-                ).ok()
-            );
-            result.push_str(&try_opt!(rewrite));
+
+            result.push_str(&format!(
+                "{}else{}",
+                between_kwd_else_block_comment
+                    .as_ref()
+                    .map_or(between_sep, |s| &**s),
+                after_else_comment.as_ref().map_or(after_sep, |s| &**s),
+            ));
+            result.push_str(&rewrite?);
         }
 
         Some(result)
     }
 }
 
-fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
+fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
     match label {
-        Some(ident) => format!("{}: ", ident.node),
-        None => "".to_owned(),
+        Some(ident) => Cow::from(format!("{}: ", ident.node)),
+        None => Cow::from(""),
     }
 }
 
 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
-    let comment_str = context.snippet(span);
-    if contains_comment(&comment_str) {
-        let comment = try_opt!(rewrite_comment(
-            comment_str.trim(),
-            false,
-            shape,
-            context.config,
-        ));
-        Some(format!(
+    match rewrite_missing_comment(span, shape, context) {
+        Some(ref comment) if !comment.is_empty() => Some(format!(
             "\n{indent}{}\n{indent}",
             comment,
             indent = shape.indent.to_string(context.config)
-        ))
-    } else {
-        None
+        )),
+        _ => None,
     }
 }
 
@@ -1396,8 +1390,8 @@ fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
 // FIXME: incorrectly returns false when comment is contained completely within
 // the expression.
 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
-    (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) &&
-        !block_contains_comment(block, codemap))
+    (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
+        && !block_contains_comment(block, codemap))
 }
 
 /// Checks whether a block contains at most one statement or expression, and no comments.
@@ -1425,44 +1419,24 @@ fn is_unsafe_block(block: &ast::Block) -> bool {
     }
 }
 
-// inter-match-arm-comment-rules:
-//  - all comments following a match arm before the start of the next arm
-//    are about the second arm
-fn rewrite_match_arm_comment(
-    context: &RewriteContext,
-    missed_str: &str,
-    shape: Shape,
-    arm_indent_str: &str,
-) -> Option<String> {
-    // The leading "," is not part of the arm-comment
-    let missed_str = match missed_str.find_uncommented(",") {
-        Some(n) => &missed_str[n + 1..],
-        None => &missed_str[..],
-    };
-
-    let mut result = String::new();
-    // any text not preceeded by a newline is pushed unmodified to the block
-    let first_brk = missed_str.find(|c: char| c == '\n').unwrap_or(0);
-    result.push_str(&missed_str[..first_brk]);
-    let missed_str = &missed_str[first_brk..]; // If missed_str had one newline, it starts with it
+// A simple wrapper type against ast::Arm. Used inside write_list().
+struct ArmWrapper<'a> {
+    pub arm: &'a ast::Arm,
+    // True if the arm is the last one in match expression. Used to decide on whether we should add
+    // trailing comma to the match arm when `config.trailing_comma() == Never`.
+    pub is_last: bool,
+}
 
-    let first = missed_str
-        .find(|c: char| !c.is_whitespace())
-        .unwrap_or(missed_str.len());
-    if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
-        // Excessive vertical whitespace before comment should be preserved
-        // FIXME handle vertical whitespace better
-        result.push('\n');
-    }
-    let missed_str = missed_str[first..].trim();
-    if !missed_str.is_empty() {
-        let comment = try_opt!(rewrite_comment(&missed_str, false, shape, context.config));
-        result.push('\n');
-        result.push_str(arm_indent_str);
-        result.push_str(&comment);
+impl<'a> ArmWrapper<'a> {
+    pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
+        ArmWrapper { arm, is_last }
     }
+}
 
-    Some(result)
+impl<'a> Rewrite for ArmWrapper<'a> {
+    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+        rewrite_match_arm(context, self.arm, shape, self.is_last)
+    }
 }
 
 fn rewrite_match(
@@ -1479,17 +1453,17 @@ fn rewrite_match(
 
     // Do not take the rhs overhead from the upper expressions into account
     // when rewriting match condition.
-    let new_width = try_opt!(context.config.max_width().checked_sub(shape.used_width()));
+    let new_width = context.config.max_width().checked_sub(shape.used_width())?;
     let cond_shape = Shape {
         width: new_width,
         ..shape
     };
     // 6 = `match `
     let cond_shape = match context.config.control_style() {
-        Style::Legacy => try_opt!(cond_shape.shrink_left(6)),
-        Style::Rfc => try_opt!(cond_shape.offset_left(6)),
+        Style::Legacy => cond_shape.shrink_left(6)?,
+        Style::Rfc => cond_shape.offset_left(6)?,
     };
-    let cond_str = try_opt!(cond.rewrite(context, cond_shape));
+    let cond_str = cond.rewrite(context, cond_shape)?;
     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
     let block_sep = match context.config.control_brace_style() {
         ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
@@ -1508,39 +1482,40 @@ fn rewrite_match(
     let inner_attrs_str = if inner_attrs.is_empty() {
         String::new()
     } else {
-        try_opt!(
-            inner_attrs
-                .rewrite(context, shape)
-                .map(|s| format!("\n{}{}", nested_indent_str, s))
-        )
+        inner_attrs
+            .rewrite(context, shape)
+            .map(|s| format!("{}{}\n", nested_indent_str, s))?
     };
 
     let open_brace_pos = if inner_attrs.is_empty() {
         context
             .codemap
-            .span_after(mk_sp(cond.span.hi, arms[0].span().lo), "{")
+            .span_after(mk_sp(cond.span.hi(), arms[0].span().lo()), "{")
     } else {
-        inner_attrs[inner_attrs.len() - 1].span().hi
+        inner_attrs[inner_attrs.len() - 1].span().hi()
+    };
+
+    let arm_indent_str = if context.config.indent_match_arms() {
+        nested_indent_str
+    } else {
+        shape.indent.to_string(context.config)
     };
 
     Some(format!(
-        "match {}{}{{{}{}\n{}}}",
+        "match {}{}{{\n{}{}{}\n{}}}",
         cond_str,
         block_sep,
         inner_attrs_str,
-        try_opt!(rewrite_match_arms(
-            context,
-            arms,
-            shape,
-            span,
-            open_brace_pos,
-        )),
+        arm_indent_str,
+        rewrite_match_arms(context, arms, shape, span, open_brace_pos,)?,
         shape.indent.to_string(context.config),
     ))
 }
 
-fn arm_comma(config: &Config, body: &ast::Expr) -> &'static str {
-    if config.match_block_trailing_comma() {
+fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
+    if is_last && config.trailing_comma() == SeparatorTactic::Never {
+        ""
+    } else if config.match_block_trailing_comma() {
         ","
     } else if let ast::ExprKind::Block(ref block) = body.node {
         if let ast::BlockCheckMode::Default = block.rules {
@@ -1560,101 +1535,105 @@ fn rewrite_match_arms(
     span: Span,
     open_brace_pos: BytePos,
 ) -> Option<String> {
-    let mut result = String::new();
-
     let arm_shape = if context.config.indent_match_arms() {
         shape.block_indent(context.config.tab_spaces())
     } else {
         shape.block_indent(0)
     }.with_max_width(context.config);
-    let arm_indent_str = arm_shape.indent.to_string(context.config);
 
-    let arm_num = arms.len();
-    for (i, arm) in arms.iter().enumerate() {
-        // Make sure we get the stuff between arms.
-        let missed_str = if i == 0 {
-            context.snippet(mk_sp(open_brace_pos, arm.span().lo))
-        } else {
-            context.snippet(mk_sp(arms[i - 1].span().hi, arm.span().lo))
-        };
-        let comment = try_opt!(rewrite_match_arm_comment(
-            context,
-            &missed_str,
-            arm_shape,
-            &arm_indent_str,
-        ));
-        if !comment.chars().all(|c| c == ' ') {
-            result.push_str(&comment);
-        }
-        result.push('\n');
-        result.push_str(&arm_indent_str);
-
-        let arm_str = rewrite_match_arm(context, arm, arm_shape);
-        if let Some(ref arm_str) = arm_str {
-            // Trim the trailing comma if necessary.
-            if i == arm_num - 1 && context.config.trailing_comma() == SeparatorTactic::Never &&
-                arm_str.ends_with(',')
-            {
-                result.push_str(&arm_str[0..arm_str.len() - 1])
-            } else {
-                result.push_str(arm_str)
-            }
-        } else {
-            // We couldn't format the arm, just reproduce the source.
-            let snippet = context.snippet(arm.span());
-            result.push_str(&snippet);
-            if context.config.trailing_comma() != SeparatorTactic::Never {
-                result.push_str(arm_comma(context.config, &arm.body))
-            }
-        }
-    }
-    // BytePos(1) = closing match brace.
-    let last_span = mk_sp(arms[arms.len() - 1].span().hi, span.hi - BytePos(1));
-    let last_comment = context.snippet(last_span);
-    let comment = try_opt!(rewrite_match_arm_comment(
-        context,
-        &last_comment,
-        arm_shape,
-        &arm_indent_str,
-    ));
-    result.push_str(&comment);
+    let arm_len = arms.len();
+    let is_last_iter = repeat(false)
+        .take(arm_len.checked_sub(1).unwrap_or(0))
+        .chain(repeat(true));
+    let items = itemize_list(
+        context.codemap,
+        arms.iter()
+            .zip(is_last_iter)
+            .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
+        "}",
+        |arm| arm.arm.span().lo(),
+        |arm| arm.arm.span().hi(),
+        |arm| arm.rewrite(context, arm_shape),
+        open_brace_pos,
+        span.hi(),
+        false,
+    );
+    let arms_vec: Vec<_> = items.collect();
+    let fmt = ListFormatting {
+        tactic: DefinitiveListTactic::Vertical,
+        // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
+        separator: "",
+        trailing_separator: SeparatorTactic::Never,
+        separator_place: SeparatorPlace::Back,
+        shape: arm_shape,
+        ends_with_newline: true,
+        preserve_newline: true,
+        config: context.config,
+    };
 
-    Some(result)
+    write_list(&arms_vec, &fmt)
 }
 
-fn rewrite_match_arm(context: &RewriteContext, arm: &ast::Arm, shape: Shape) -> Option<String> {
-    let attr_str = if !arm.attrs.is_empty() {
+fn rewrite_match_arm(
+    context: &RewriteContext,
+    arm: &ast::Arm,
+    shape: Shape,
+    is_last: bool,
+) -> Option<String> {
+    let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
         if contains_skip(&arm.attrs) {
-            return None;
+            let (_, body) = flatten_arm_body(context, &arm.body);
+            // `arm.span()` does not include trailing comma, add it manually.
+            return Some(format!(
+                "{}{}",
+                context.snippet(arm.span()),
+                arm_comma(context.config, body, is_last),
+            ));
         }
-        format!(
-            "{}\n{}",
-            try_opt!(arm.attrs.rewrite(context, shape)),
-            shape.indent.to_string(context.config)
+        (
+            mk_sp(
+                arm.attrs[arm.attrs.len() - 1].span.hi(),
+                arm.pats[0].span.lo(),
+            ),
+            arm.attrs.rewrite(context, shape)?,
         )
     } else {
-        String::new()
+        (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
     };
-    let pats_str = try_opt!(rewrite_match_pattern(context, &arm.pats, &arm.guard, shape));
-    let pats_str = attr_str + &pats_str;
-    rewrite_match_body(context, &arm.body, &pats_str, shape, arm.guard.is_some())
+    let pats_str =
+        rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
+            combine_strs_with_missing_comments(
+                context,
+                &attrs_str,
+                &pats_str,
+                missing_span,
+                shape,
+                false,
+            )
+        })?;
+    rewrite_match_body(
+        context,
+        &arm.body,
+        &pats_str,
+        shape,
+        arm.guard.is_some(),
+        is_last,
+    )
 }
 
 fn rewrite_match_pattern(
     context: &RewriteContext,
-    pats: &Vec<ptr::P<ast::Pat>>,
+    pats: &[ptr::P<ast::Pat>],
     guard: &Option<ptr::P<ast::Expr>>,
     shape: Shape,
 ) -> Option<String> {
     // Patterns
     // 5 = ` => {`
-    let pat_shape = try_opt!(shape.sub_width(5));
+    let pat_shape = shape.sub_width(5)?;
 
-    let pat_strs = try_opt!(
-        pats.iter()
-            .map(|p| p.rewrite(context, pat_shape))
-            .collect::<Option<Vec<_>>>()
-    );
+    let pat_strs = pats.iter()
+        .map(|p| p.rewrite(context, pat_shape))
+        .collect::<Option<Vec<_>>>()?;
 
     let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
     let tactic = definitive_tactic(
@@ -1667,52 +1646,69 @@ fn rewrite_match_pattern(
         tactic: tactic,
         separator: " |",
         trailing_separator: SeparatorTactic::Never,
+        separator_place: context.config.match_pattern_separator_break_point(),
         shape: pat_shape,
         ends_with_newline: false,
         preserve_newline: false,
         config: context.config,
     };
-    let pats_str = try_opt!(write_list(&items, &fmt));
+    let pats_str = write_list(&items, &fmt)?;
 
     // Guard
-    let guard_str = try_opt!(rewrite_guard(
-        context,
-        guard,
-        shape,
-        trimmed_last_line_width(&pats_str),
-    ));
+    let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
 
     Some(format!("{}{}", pats_str, guard_str))
 }
 
-fn rewrite_match_body(
-    context: &RewriteContext,
-    body: &ptr::P<ast::Expr>,
-    pats_str: &str,
-    shape: Shape,
-    has_guard: bool,
-) -> Option<String> {
-    let (extend, body) = match body.node {
+// (extend, body)
+// @extend: true if the arm body can be put next to `=>`
+// @body: flattened body, if the body is block with a single expression
+fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
+    match body.node {
         ast::ExprKind::Block(ref block)
             if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
         {
             if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
-                (expr.can_be_overflowed(context, 1), &**expr)
+                (
+                    !context.config.multiline_match_arm_forces_block()
+                        && expr.can_be_overflowed(context, 1),
+                    &**expr,
+                )
             } else {
-                (false, &**body)
+                (false, &*body)
             }
         }
-        _ => (body.can_be_overflowed(context, 1), &**body),
-    };
+        _ => (
+            !context.config.multiline_match_arm_forces_block()
+                && body.can_be_overflowed(context, 1),
+            &*body,
+        ),
+    }
+}
 
-    let comma = arm_comma(&context.config, body);
-    let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
-    let alt_block_sep = alt_block_sep.as_str();
+fn rewrite_match_body(
+    context: &RewriteContext,
+    body: &ptr::P<ast::Expr>,
+    pats_str: &str,
+    shape: Shape,
+    has_guard: bool,
+    is_last: bool,
+) -> Option<String> {
+    let (extend, body) = flatten_arm_body(context, body);
     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
         (true, is_empty_block(block, context.codemap))
     } else {
         (false, false)
     };
+    let extend = if context.config.match_arm_forces_newline() {
+        is_block
+    } else {
+        extend
+    };
+
+    let comma = arm_comma(context.config, body, is_last);
+    let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
+    let alt_block_sep = alt_block_sep.as_str();
 
     let combine_orig_body = |body_str: &str| {
         let block_sep = match context.config.control_brace_style() {
@@ -1725,7 +1721,11 @@ fn rewrite_match_body(
 
     let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
     let next_line_indent = if is_block {
-        shape.indent
+        if is_empty_block {
+            shape.indent.block_indent(context.config)
+        } else {
+            shape.indent
+        }
     } else {
         shape.indent.block_indent(context.config)
     };
@@ -1771,7 +1771,7 @@ fn rewrite_match_body(
     // Let's try and get the arm body on the same line as the condition.
     // 4 = ` => `.len()
     let orig_body_shape = shape
-        .offset_left(extra_offset(&pats_str, shape) + 4)
+        .offset_left(extra_offset(pats_str, shape) + 4)
         .and_then(|shape| shape.sub_width(comma.len()));
     let orig_body = if let Some(body_shape) = orig_body_shape {
         let rewrite = nop_block_collapse(
@@ -1781,9 +1781,9 @@ fn rewrite_match_body(
 
         match rewrite {
             Some(ref body_str)
-                if !forbid_same_line &&
-                    (is_block ||
-                        (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
+                if !forbid_same_line && !context.config.match_arm_forces_newline()
+                    && (is_block
+                        || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
             {
                 return combine_orig_body(body_str);
             }
@@ -1880,9 +1880,8 @@ fn rewrite_pat_expr(
         } else {
             format!("{} ", matcher)
         };
-        let pat_shape =
-            try_opt!(try_opt!(shape.offset_left(matcher.len())).sub_width(connector.len()));
-        let pat_string = try_opt!(pat.rewrite(context, pat_shape));
+        let pat_shape = shape.offset_left(matcher.len())?.sub_width(connector.len())?;
+        let pat_string = pat.rewrite(context, pat_shape)?;
         let result = format!("{}{}{}", matcher, pat_string, connector);
         return rewrite_assign_rhs(context, result, expr, shape);
     }
@@ -1903,6 +1902,13 @@ fn rewrite_pat_expr(
         .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
 }
 
+pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
+    match l.node {
+        ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
+        _ => Some(context.snippet(l.span)),
+    }
+}
+
 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
     let string_lit = context.snippet(span);
 
@@ -1918,7 +1924,11 @@ fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Opt
                 string_lit
                     .lines()
                     .map(|line| {
-                        new_indent.to_string(context.config) + line.trim_left()
+                        format!(
+                            "{}{}",
+                            new_indent.to_string(context.config),
+                            line.trim_left()
+                        )
                     })
                     .collect::<Vec<_>>()
                     .join("\n")
@@ -1929,26 +1939,16 @@ fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Opt
         }
     }
 
-    if !context.config.force_format_strings() &&
-        !string_requires_rewrite(context, span, &string_lit, shape)
+    if !context.config.force_format_strings()
+        && !string_requires_rewrite(context, span, &string_lit, shape)
     {
         return Some(string_lit);
     }
 
-    let fmt = StringFormat {
-        opener: "\"",
-        closer: "\"",
-        line_start: " ",
-        line_end: "\\",
-        shape: shape,
-        trim_end: false,
-        config: context.config,
-    };
-
     // Remove the quote characters.
     let str_lit = &string_lit[1..string_lit.len() - 1];
 
-    rewrite_string(str_lit, &fmt)
+    rewrite_string(str_lit, &StringFormat::new(shape, context.config))
 }
 
 fn string_requires_rewrite(
@@ -1957,7 +1957,7 @@ fn string_requires_rewrite(
     string: &str,
     shape: Shape,
 ) -> bool {
-    if context.codemap.lookup_char_pos(span.lo).col.0 != shape.indent.width() {
+    if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
         return true;
     }
 
@@ -1966,56 +1966,14 @@ fn string_requires_rewrite(
             if line.len() > shape.width {
                 return true;
             }
-        } else {
-            if line.len() > shape.width + shape.indent.width() {
-                return true;
-            }
+        } else if line.len() > shape.width + shape.indent.width() {
+            return true;
         }
     }
 
     false
 }
 
-pub fn rewrite_call_with_binary_search<R>(
-    context: &RewriteContext,
-    callee: &R,
-    args: &[&ast::Expr],
-    span: Span,
-    shape: Shape,
-) -> Option<String>
-where
-    R: Rewrite,
-{
-    let force_trailing_comma = if context.inside_macro {
-        span_ends_with_comma(context, span)
-    } else {
-        false
-    };
-    let closure = |callee_max_width| {
-        // FIXME using byte lens instead of char lens (and probably all over the
-        // place too)
-        let callee_shape = Shape {
-            width: callee_max_width,
-            ..shape
-        };
-        let callee_str = callee
-            .rewrite(context, callee_shape)
-            .ok_or(Ordering::Greater)?;
-
-        rewrite_call_inner(
-            context,
-            &callee_str,
-            args,
-            span,
-            shape,
-            context.config.fn_call_width(),
-            force_trailing_comma,
-        )
-    };
-
-    binary_search(1, shape.width, closure)
-}
-
 pub fn rewrite_call(
     context: &RewriteContext,
     callee: &str,
@@ -2030,13 +1988,13 @@ pub fn rewrite_call(
     };
     rewrite_call_inner(
         context,
-        &callee,
-        &args.iter().map(|x| &**x).collect::<Vec<_>>(),
+        callee,
+        &ptr_vec_to_ref_vec(&args),
         span,
         shape,
         context.config.fn_call_width(),
         force_trailing_comma,
-    ).ok()
+    )
 }
 
 pub fn rewrite_call_inner<'a, T>(
@@ -2047,7 +2005,7 @@ pub fn rewrite_call_inner<'a, T>(
     shape: Shape,
     args_max_width: usize,
     force_trailing_comma: bool,
-) -> Result<String, Ordering>
+) -> Option<String>
 where
     T: Rewrite + Spanned + ToExpr + 'a,
 {
@@ -2057,21 +2015,18 @@ pub fn rewrite_call_inner<'a, T>(
     } else {
         1
     };
-    let used_width = extra_offset(&callee_str, shape);
-    let one_line_width = shape
-        .width
-        .checked_sub(used_width + 2 * paren_overhead)
-        .ok_or(Ordering::Greater)?;
+    let used_width = extra_offset(callee_str, shape);
+    let one_line_width = shape.width.checked_sub(used_width + 2 * paren_overhead)?;
 
     let nested_shape = shape_from_fn_call_style(
         context,
         shape,
         used_width + 2 * paren_overhead,
         used_width + paren_overhead,
-    ).ok_or(Ordering::Greater)?;
+    )?;
 
     let span_lo = context.codemap.span_after(span, "(");
-    let args_span = mk_sp(span_lo, span.hi);
+    let args_span = mk_sp(span_lo, span.hi());
 
     let (extendable, list_str) = rewrite_call_args(
         context,
@@ -2081,7 +2036,7 @@ pub fn rewrite_call_inner<'a, T>(
         one_line_width,
         args_max_width,
         force_trailing_comma,
-    ).ok_or(Ordering::Less)?;
+    )?;
 
     if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
         let mut new_context = context.clone();
@@ -2097,10 +2052,8 @@ pub fn rewrite_call_inner<'a, T>(
         );
     }
 
-    let args_shape = shape
-        .sub_width(last_line_width(&callee_str))
-        .ok_or(Ordering::Less)?;
-    Ok(format!(
+    let args_shape = shape.sub_width(last_line_width(callee_str))?;
+    Some(format!(
         "{}{}",
         callee_str,
         wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
@@ -2130,11 +2083,11 @@ fn rewrite_call_args<'a, T>(
         context.codemap,
         args.iter(),
         ")",
-        |item| item.span().lo,
-        |item| item.span().hi,
+        |item| item.span().lo(),
+        |item| item.span().hi(),
         |item| item.rewrite(context, shape),
-        span.lo,
-        span.hi,
+        span.lo(),
+        span.hi(),
         true,
     );
     let mut item_vec: Vec<_> = items.collect();
@@ -2161,6 +2114,7 @@ fn rewrite_call_args<'a, T>(
         } else {
             context.config.trailing_comma()
         },
+        separator_place: SeparatorPlace::Back,
         shape: shape,
         ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
         preserve_newline: false,
@@ -2183,19 +2137,18 @@ fn try_overflow_last_arg<'a, T>(
 where
     T: Rewrite + Spanned + ToExpr + 'a,
 {
-    let overflow_last = can_be_overflowed(&context, args);
+    let overflow_last = can_be_overflowed(context, args);
 
     // Replace the last item with its first line to see if it fits with
     // first arguments.
     let placeholder = if overflow_last {
         let mut context = context.clone();
         if let Some(expr) = args[args.len() - 1].to_expr() {
-            match expr.node {
-                ast::ExprKind::MethodCall(..) => context.force_one_line_chain = true,
-                _ => (),
+            if let ast::ExprKind::MethodCall(..) = expr.node {
+                context.force_one_line_chain = true;
             }
         }
-        last_arg_shape(&context, &item_vec, shape, args_max_width).and_then(|arg_shape| {
+        last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
             rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
         })
     } else {
@@ -2218,12 +2171,23 @@ fn try_overflow_last_arg<'a, T>(
         _ if args.len() >= 1 => {
             item_vec[args.len() - 1].item = args.last()
                 .and_then(|last_arg| last_arg.rewrite(context, shape));
-            tactic = definitive_tactic(
-                &*item_vec,
-                ListTactic::LimitedHorizontalVertical(args_max_width),
-                Separator::Comma,
-                one_line_width,
-            );
+            // Use horizontal layout for a function with a single argument as long as
+            // everything fits in a single line.
+            if args.len() == 1
+                && args_max_width != 0 // Vertical layout is forced.
+                && !item_vec[0].has_comment()
+                && !item_vec[0].inner_as_ref().contains('\n')
+                && ::lists::total_item_width(&item_vec[0]) <= one_line_width
+            {
+                tactic = DefinitiveListTactic::Horizontal;
+            } else {
+                tactic = definitive_tactic(
+                    &*item_vec,
+                    ListTactic::LimitedHorizontalVertical(args_max_width),
+                    Separator::Comma,
+                    one_line_width,
+                );
+            }
         }
         _ => (),
     }
@@ -2233,12 +2197,12 @@ fn try_overflow_last_arg<'a, T>(
 
 fn last_arg_shape(
     context: &RewriteContext,
-    items: &Vec<ListItem>,
+    items: &[ListItem],
     shape: Shape,
     args_max_width: usize,
 ) -> Option<Shape> {
     let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
-        acc + i.item.as_ref().map_or(0, |s| first_line_width(&s))
+        acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
     });
     let max_width = min(args_max_width, shape.width);
     let arg_indent = if context.use_block_indent() {
@@ -2247,7 +2211,7 @@ fn last_arg_shape(
         shape.block().indent
     };
     Some(Shape {
-        width: try_opt!(max_width.checked_sub(overhead)),
+        width: max_width.checked_sub(overhead)?,
         indent: arg_indent,
         offset: 0,
     })
@@ -2267,19 +2231,13 @@ fn rewrite_last_closure(
             }
             _ => body,
         };
-        let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
-            capture,
-            fn_decl,
-            body,
-            expr.span,
-            context,
-            shape,
-        ));
+        let (prefix, extra_offset) =
+            rewrite_closure_fn_decl(capture, fn_decl, body, expr.span, context, shape)?;
         // If the closure goes multi line before its body, do not overflow the closure.
         if prefix.contains('\n') {
             return None;
         }
-        let body_shape = try_opt!(shape.offset_left(extra_offset));
+        let body_shape = shape.offset_left(extra_offset)?;
         // When overflowing the closure which consists of a single control flow expression,
         // force to use block if its condition uses multi line.
         let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
@@ -2312,8 +2270,8 @@ fn rewrite_last_arg_with_overflow<'a, T>(
             ast::ExprKind::Closure(..) => {
                 // If the argument consists of multiple closures, we do not overflow
                 // the last closure.
-                if args.len() > 1 &&
-                    args.iter()
+                if args.len() > 1
+                    && args.iter()
                         .rev()
                         .skip(1)
                         .filter_map(|arg| arg.to_expr())
@@ -2352,8 +2310,8 @@ fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
     match expr.node {
         ast::ExprKind::Match(..) => {
-            (context.use_block_indent() && args_len == 1) ||
-                (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
+            (context.use_block_indent() && args_len == 1)
+                || (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
         }
         ast::ExprKind::If(..) |
         ast::ExprKind::IfLet(..) |
@@ -2364,8 +2322,8 @@ pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_l
             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
         }
         ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
-            context.use_block_indent() ||
-                context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
+            context.use_block_indent()
+                || context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
         }
         ast::ExprKind::Array(..) |
         ast::ExprKind::Call(..) |
@@ -2389,11 +2347,11 @@ pub fn wrap_args_with_parens(
     shape: Shape,
     nested_shape: Shape,
 ) -> String {
-    if !context.use_block_indent() ||
-        (context.inside_macro && !args_str.contains('\n') &&
-            args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
+    if !context.use_block_indent()
+        || (context.inside_macro && !args_str.contains('\n')
+            && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
     {
-        if context.config.spaces_within_parens() && args_str.len() > 0 {
+        if context.config.spaces_within_parens() && !args_str.is_empty() {
             format!("( {} )", args_str)
         } else {
             format!("({})", args_str)
@@ -2419,23 +2377,21 @@ fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) ->
     debug!("rewrite_paren, shape: {:?}", shape);
     let total_paren_overhead = paren_overhead(context);
     let paren_overhead = total_paren_overhead / 2;
-    let sub_shape = try_opt!(
-        shape
-            .offset_left(paren_overhead)
-            .and_then(|s| s.sub_width(paren_overhead))
-    );
+    let sub_shape = shape
+        .offset_left(paren_overhead)
+        .and_then(|s| s.sub_width(paren_overhead))?;
 
-    let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && s.len() > 0 {
+    let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() {
         format!("( {} )", s)
     } else {
         format!("({})", s)
     };
 
-    let subexpr_str = try_opt!(subexpr.rewrite(context, sub_shape));
+    let subexpr_str = subexpr.rewrite(context, sub_shape)?;
     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
 
-    if subexpr_str.contains('\n') ||
-        first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
+    if subexpr_str.contains('\n')
+        || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
     {
         Some(paren_wrapper(&subexpr_str))
     } else {
@@ -2449,7 +2405,7 @@ fn rewrite_index(
     context: &RewriteContext,
     shape: Shape,
 ) -> Option<String> {
-    let expr_str = try_opt!(expr.rewrite(context, shape));
+    let expr_str = expr.rewrite(context, shape)?;
 
     let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
         ("[ ", " ]")
@@ -2478,14 +2434,14 @@ fn rewrite_index(
 
     // Try putting index on the next line and see if it fits in a single line.
     let indent = shape.indent.block_indent(context.config);
-    let index_shape = try_opt!(Shape::indented(indent, context.config).offset_left(lbr.len()));
-    let index_shape = try_opt!(index_shape.sub_width(rbr.len() + rhs_overhead));
+    let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
+    let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
     let new_index_rw = index.rewrite(context, index_shape);
     match (orig_index_rw, new_index_rw) {
         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
             "{}\n{}{}{}{}",
             expr_str,
-            indent.to_string(&context.config),
+            indent.to_string(context.config),
             lbr,
             new_index_str,
             rbr
@@ -2493,7 +2449,7 @@ fn rewrite_index(
         (None, Some(ref new_index_str)) => Some(format!(
             "{}\n{}{}{}{}",
             expr_str,
-            indent.to_string(&context.config),
+            indent.to_string(context.config),
             lbr,
             new_index_str,
             rbr
@@ -2527,34 +2483,28 @@ enum StructLitField<'a> {
     }
 
     // 2 = " {".len()
-    let path_shape = try_opt!(shape.sub_width(2));
-    let path_str = try_opt!(rewrite_path(
-        context,
-        PathContext::Expr,
-        None,
-        path,
-        path_shape,
-    ));
+    let path_shape = shape.sub_width(2)?;
+    let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
 
-    if fields.len() == 0 && base.is_none() {
+    if fields.is_empty() && base.is_none() {
         return Some(format!("{} {{}}", path_str));
     }
 
     // Foo { a: Foo } - indent is +3, width is -5.
-    let (h_shape, v_shape) = try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, 2));
+    let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
 
     let one_line_width = h_shape.map_or(0, |shape| shape.width);
     let body_lo = context.codemap.span_after(span, "{");
-    let fields_str = if struct_lit_can_be_aligned(fields, &base) &&
-        context.config.struct_field_align_threshold() > 0
+    let fields_str = if struct_lit_can_be_aligned(fields, &base)
+        && context.config.struct_field_align_threshold() > 0
     {
-        try_opt!(rewrite_with_alignment(
+        rewrite_with_alignment(
             fields,
             context,
             shape,
-            mk_sp(body_lo, span.hi),
+            mk_sp(body_lo, span.hi()),
             one_line_width,
-        ))
+        )?
     } else {
         let field_iter = fields
             .into_iter()
@@ -2562,26 +2512,26 @@ enum StructLitField<'a> {
             .chain(base.into_iter().map(StructLitField::Base));
 
         let span_lo = |item: &StructLitField| match *item {
-            StructLitField::Regular(field) => field.span().lo,
+            StructLitField::Regular(field) => field.span().lo(),
             StructLitField::Base(expr) => {
-                let last_field_hi = fields.last().map_or(span.lo, |field| field.span.hi);
-                let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo));
+                let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
+                let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
                 let pos = snippet.find_uncommented("..").unwrap();
                 last_field_hi + BytePos(pos as u32)
             }
         };
         let span_hi = |item: &StructLitField| match *item {
-            StructLitField::Regular(field) => field.span().hi,
-            StructLitField::Base(expr) => expr.span.hi,
+            StructLitField::Regular(field) => field.span().hi(),
+            StructLitField::Base(expr) => expr.span.hi(),
         };
         let rewrite = |item: &StructLitField| match *item {
             StructLitField::Regular(field) => {
                 // The 1 taken from the v_budget is for the comma.
-                rewrite_field(context, field, try_opt!(v_shape.sub_width(1)), 0)
+                rewrite_field(context, field, v_shape.sub_width(1)?, 0)
             }
             StructLitField::Base(expr) => {
                 // 2 = ..
-                expr.rewrite(context, try_opt!(v_shape.offset_left(2)))
+                expr.rewrite(context, v_shape.offset_left(2)?)
                     .map(|s| format!("..{}", s))
             }
         };
@@ -2594,7 +2544,7 @@ enum StructLitField<'a> {
             span_hi,
             rewrite,
             body_lo,
-            span.hi,
+            span.hi(),
             false,
         );
         let item_vec = items.collect::<Vec<_>>();
@@ -2603,7 +2553,7 @@ enum StructLitField<'a> {
         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
         let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
 
-        try_opt!(write_list(&item_vec, &fmt))
+        write_list(&item_vec, &fmt)?
     };
 
     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
@@ -2620,10 +2570,10 @@ pub fn wrap_struct_field(
     nested_shape: Shape,
     one_line_width: usize,
 ) -> String {
-    if context.config.struct_lit_style() == IndentStyle::Block &&
-        (fields_str.contains('\n') ||
-            context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti ||
-            fields_str.len() > one_line_width)
+    if context.config.struct_lit_style() == IndentStyle::Block
+        && (fields_str.contains('\n')
+            || context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti
+            || fields_str.len() > one_line_width)
     {
         format!(
             "\n{}{}\n{}",
@@ -2651,11 +2601,7 @@ pub fn rewrite_field(
     prefix_max_width: usize,
 ) -> Option<String> {
     if contains_skip(&field.attrs) {
-        return wrap_str(
-            context.snippet(field.span()),
-            context.config.max_width(),
-            shape,
-        );
+        return Some(context.snippet(field.span()));
     }
     let name = &field.ident.node.to_string();
     if field.is_shorthand {
@@ -2666,10 +2612,10 @@ pub fn rewrite_field(
             separator.push(' ');
         }
         let overhead = name.len() + separator.len();
-        let expr_shape = try_opt!(shape.offset_left(overhead));
+        let expr_shape = shape.offset_left(overhead)?;
         let expr = field.expr.rewrite(context, expr_shape);
 
-        let mut attrs_str = try_opt!(field.attrs.rewrite(context, shape));
+        let mut attrs_str = field.attrs.rewrite(context, shape)?;
         if !attrs_str.is_empty() {
             attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
         };
@@ -2686,7 +2632,7 @@ pub fn rewrite_field(
                         "{}{}:\n{}{}",
                         attrs_str,
                         name,
-                        expr_offset.to_string(&context.config),
+                        expr_offset.to_string(context.config),
                         s
                     )
                 })
@@ -2727,7 +2673,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T>(
     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
     if items.len() == 1 {
         // 3 = "(" + ",)"
-        let nested_shape = try_opt!(shape.sub_width(3)).visual_indent(1);
+        let nested_shape = shape.sub_width(3)?.visual_indent(1);
         return items.next().unwrap().rewrite(context, nested_shape).map(
             |s| if context.config.spaces_within_parens() {
                 format!("( {}, )", s)
@@ -2738,16 +2684,16 @@ fn rewrite_tuple_in_visual_indent_style<'a, T>(
     }
 
     let list_lo = context.codemap.span_after(span, "(");
-    let nested_shape = try_opt!(shape.sub_width(2)).visual_indent(1);
+    let nested_shape = shape.sub_width(2)?.visual_indent(1);
     let items = itemize_list(
         context.codemap,
         items,
         ")",
-        |item| item.span().lo,
-        |item| item.span().hi,
+        |item| item.span().lo(),
+        |item| item.span().hi(),
         |item| item.rewrite(context, nested_shape),
         list_lo,
-        span.hi - BytePos(1),
+        span.hi() - BytePos(1),
         false,
     );
     let item_vec: Vec<_> = items.collect();
@@ -2761,14 +2707,15 @@ fn rewrite_tuple_in_visual_indent_style<'a, T>(
         tactic: tactic,
         separator: ",",
         trailing_separator: SeparatorTactic::Never,
+        separator_place: SeparatorPlace::Back,
         shape: shape,
         ends_with_newline: false,
         preserve_newline: false,
         config: context.config,
     };
-    let list_str = try_opt!(write_list(&item_vec, &fmt));
+    let list_str = write_list(&item_vec, &fmt)?;
 
-    if context.config.spaces_within_parens() && list_str.len() > 0 {
+    if context.config.spaces_within_parens() && !list_str.is_empty() {
         Some(format!("( {} )", list_str))
     } else {
         Some(format!("({})", list_str))
@@ -2786,7 +2733,7 @@ pub fn rewrite_tuple<'a, T>(
 {
     debug!("rewrite_tuple {:?}", shape);
     if context.use_block_indent() {
-        // We use the same rule as funcation call for rewriting tuple.
+        // We use the same rule as function calls for rewriting tuples.
         let force_trailing_comma = if context.inside_macro {
             span_ends_with_comma(context, span)
         } else {
@@ -2800,7 +2747,7 @@ pub fn rewrite_tuple<'a, T>(
             shape,
             context.config.fn_call_width(),
             force_trailing_comma,
-        ).ok()
+        )
     } else {
         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
     }
@@ -2813,7 +2760,7 @@ pub fn rewrite_unary_prefix<R: Rewrite>(
     shape: Shape,
 ) -> Option<String> {
     rewrite
-        .rewrite(context, try_opt!(shape.offset_left(prefix.len())))
+        .rewrite(context, shape.offset_left(prefix.len())?)
         .map(|r| format!("{}{}", prefix, r))
 }
 
@@ -2826,7 +2773,7 @@ pub fn rewrite_unary_suffix<R: Rewrite>(
     shape: Shape,
 ) -> Option<String> {
     rewrite
-        .rewrite(context, try_opt!(shape.sub_width(suffix.len())))
+        .rewrite(context, shape.sub_width(suffix.len())?)
         .map(|mut r| {
             r.push_str(suffix);
             r
@@ -2861,12 +2808,8 @@ fn rewrite_assignment(
     };
 
     // 1 = space between lhs and operator.
-    let lhs_shape = try_opt!(shape.sub_width(operator_str.len() + 1));
-    let lhs_str = format!(
-        "{} {}",
-        try_opt!(lhs.rewrite(context, lhs_shape)),
-        operator_str
-    );
+    let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
+    let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
 
     rewrite_assign_rhs(context, lhs_str, rhs, shape)
 }
@@ -2886,13 +2829,8 @@ pub fn rewrite_assign_rhs<S: Into<String>>(
         0
     };
     // 1 = space between operator and rhs.
-    let orig_shape = try_opt!(shape.offset_left(last_line_width + 1));
-    let rhs = try_opt!(choose_rhs(
-        context,
-        ex,
-        shape,
-        ex.rewrite(context, orig_shape)
-    ));
+    let orig_shape = shape.offset_left(last_line_width + 1)?;
+    let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
     Some(lhs + &rhs)
 }
 
@@ -2903,16 +2841,16 @@ fn choose_rhs(
     orig_rhs: Option<String>,
 ) -> Option<String> {
     match orig_rhs {
-        Some(ref new_str) if !new_str.contains('\n') => Some(format!(" {}", new_str)),
+        Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
+            Some(format!(" {}", new_str))
+        }
         _ => {
             // Expression did not fit on the same line as the identifier.
             // Try splitting the line and see if that works better.
-            let new_shape = try_opt!(
-                Shape::indented(
-                    shape.block().indent.block_indent(context.config),
-                    context.config,
-                ).sub_width(shape.rhs_overhead(context.config))
-            );
+            let new_shape = Shape::indented(
+                shape.block().indent.block_indent(context.config),
+                context.config,
+            ).sub_width(shape.rhs_overhead(context.config))?;
             let new_rhs = expr.rewrite(context, new_shape);
             let new_indent_str = &new_shape.indent.to_string(context.config);
 
@@ -2933,8 +2871,8 @@ fn count_line_breaks(src: &str) -> usize {
         src.chars().filter(|&x| x == '\n').count()
     }
 
-    !next_line_rhs.contains('\n') ||
-        count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
+    !next_line_rhs.contains('\n')
+        || count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
 }
 
 fn rewrite_expr_addrof(
@@ -2994,3 +2932,20 @@ fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
         false
     }
 }
+
+impl<'a> ToExpr for MacroArg {
+    fn to_expr(&self) -> Option<&ast::Expr> {
+        match *self {
+            MacroArg::Expr(ref expr) => Some(expr),
+            _ => None,
+        }
+    }
+
+    fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
+        match *self {
+            MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
+            MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
+            MacroArg::Pat(..) => false,
+        }
+    }
+}