]> git.lizzy.rs Git - rust.git/blobdiff - src/expr.rs
Fixed comment dropped between & and type issue (#4482)
[rust.git] / src / expr.rs
index 973c72d871f09694d6119c7722a91961df6a15d6..71446ce1ab0b1ec1d6c19e98045aea85bbdccb0c 100644 (file)
@@ -1,67 +1,57 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
 use std::borrow::Cow;
 use std::cmp::min;
 
-use config::lists::*;
-use syntax::parse::token::DelimToken;
-use syntax::source_map::{BytePos, SourceMap, Span};
-use syntax::{ast, ptr};
+use itertools::Itertools;
+use rustc_ast::token::{DelimToken, LitKind};
+use rustc_ast::{ast, ptr};
+use rustc_span::{BytePos, Span};
 
-use chains::rewrite_chain;
-use closures;
-use comment::{
-    combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
-    rewrite_missing_comment, CharClasses, FindUncommented,
+use crate::chains::rewrite_chain;
+use crate::closures;
+use crate::comment::{
+    combine_strs_with_missing_comments, comment_style, contains_comment, recover_comment_removed,
+    rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented,
 };
-use config::{Config, ControlBraceStyle, IndentStyle};
-use lists::{
+use crate::config::lists::*;
+use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
+use crate::lists::{
     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
-    struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
+    struct_lit_tactic, write_list, ListFormatting, Separator,
 };
-use macros::{rewrite_macro, MacroPosition};
-use matches::rewrite_match;
-use overflow::{self, IntoOverflowableItem, OverflowableItem};
-use pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
-use patterns::is_short_pattern;
-use rewrite::{Rewrite, RewriteContext};
-use shape::{Indent, Shape};
-use source_map::{LineRangeUtils, SpanUtils};
-use spanned::Spanned;
-use string::{rewrite_string, StringFormat};
-use types::{rewrite_path, PathContext};
-use utils::{
+use crate::macros::{rewrite_macro, MacroPosition};
+use crate::matches::rewrite_match;
+use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
+use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
+use crate::rewrite::{Rewrite, RewriteContext};
+use crate::shape::{Indent, Shape};
+use crate::source_map::{LineRangeUtils, SpanUtils};
+use crate::spanned::Spanned;
+use crate::string::{rewrite_string, StringFormat};
+use crate::types::{rewrite_path, PathContext};
+use crate::utils::{
     colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
-    last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
-    semicolon_for_stmt, wrap_str,
+    last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
+    unicode_str_width, wrap_str,
 };
-use vertical::rewrite_with_alignment;
-use visitor::FmtVisitor;
+use crate::vertical::rewrite_with_alignment;
+use crate::visitor::FmtVisitor;
 
 impl Rewrite for ast::Expr {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         format_expr(self, ExprType::SubExpression, context, shape)
     }
 }
 
 #[derive(Copy, Clone, PartialEq)]
-pub enum ExprType {
+pub(crate) enum ExprType {
     Statement,
     SubExpression,
 }
 
-pub fn format_expr(
+pub(crate) fn format_expr(
     expr: &ast::Expr,
     expr_type: ExprType,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     skip_out_of_file_lines_range!(context, expr.span);
@@ -69,8 +59,13 @@ pub fn format_expr(
     if contains_skip(&*expr.attrs) {
         return Some(context.snippet(expr.span()).to_owned());
     }
+    let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
+        shape.sub_width(1)?
+    } else {
+        shape
+    };
 
-    let expr_rw = match expr.node {
+    let expr_rw = match expr.kind {
         ast::ExprKind::Array(ref expr_vec) => rewrite_array(
             "",
             expr_vec.iter(),
@@ -80,7 +75,17 @@ pub fn format_expr(
             choose_separator_tactic(context, expr.span),
             None,
         ),
-        ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
+        ast::ExprKind::Lit(ref l) => {
+            if let Some(expr_rw) = rewrite_literal(context, l, shape) {
+                Some(expr_rw)
+            } else {
+                if let LitKind::StrRaw(_) = l.token.kind {
+                    Some(context.snippet(l.span).trim().into())
+                } else {
+                    None
+                }
+            }
+        }
         ast::ExprKind::Call(ref callee, ref args) => {
             let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
             let callee_str = callee.rewrite(context, shape)?;
@@ -101,24 +106,27 @@ pub fn format_expr(
             })
         }
         ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
-        ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
+        ast::ExprKind::Struct(ref path, ref fields, ref struct_rest) => rewrite_struct_lit(
             context,
             path,
             fields,
-            base.as_ref().map(|e| &**e),
+            struct_rest,
+            &expr.attrs,
             expr.span,
             shape,
         ),
         ast::ExprKind::Tup(ref items) => {
             rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
         }
+        ast::ExprKind::Let(..) => None,
         ast::ExprKind::If(..)
-        | ast::ExprKind::IfLet(..)
         | ast::ExprKind::ForLoop(..)
         | ast::ExprKind::Loop(..)
-        | ast::ExprKind::While(..)
-        | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
+        | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
             .and_then(|control_flow| control_flow.rewrite(context, shape)),
+        ast::ExprKind::ConstBlock(ref anon_const) => {
+            Some(format!("const {}", anon_const.rewrite(context, shape)?))
+        }
         ast::ExprKind::Block(ref block, opt_label) => {
             match expr_type {
                 ExprType::Statement => {
@@ -154,7 +162,7 @@ pub fn format_expr(
         ast::ExprKind::Path(ref qself, ref path) => {
             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
         }
-        ast::ExprKind::Assign(ref lhs, ref rhs) => {
+        ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
             rewrite_assignment(context, lhs, rhs, None, shape)
         }
         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
@@ -186,15 +194,15 @@ pub fn format_expr(
                 Some("yield".to_string())
             }
         }
-        ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) => {
+        ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
             closures::rewrite_closure(
-                capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
+                capture, is_async, movability, fn_decl, body, expr.span, context, shape,
             )
         }
         ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
             rewrite_chain(expr, context, shape)
         }
-        ast::ExprKind::Mac(ref mac) => {
+        ast::ExprKind::MacCall(ref mac) => {
             rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
                 wrap_str(
                     context.snippet(expr.span).to_owned(),
@@ -208,8 +216,8 @@ pub fn format_expr(
             rewrite_unary_prefix(context, "return ", &**expr, shape)
         }
         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
-        ast::ExprKind::AddrOf(mutability, ref expr) => {
-            rewrite_expr_addrof(context, mutability, expr, shape)
+        ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
+            rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
         }
         ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
             &**expr,
@@ -244,20 +252,21 @@ pub fn format_expr(
                 ast::RangeLimits::Closed => "..=",
             };
 
-            fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
-                match lhs.node {
-                    ast::ExprKind::Lit(ref lit) => match lit.node {
-                        ast::LitKind::FloatUnsuffixed(..) => {
+            fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
+                match lhs.kind {
+                    ast::ExprKind::Lit(ref lit) => match lit.kind {
+                        ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
                             context.snippet(lit.span).ends_with('.')
                         }
                         _ => false,
                     },
+                    ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
                     _ => false,
                 }
             }
 
             fn needs_space_after_range(rhs: &ast::Expr) -> bool {
-                match rhs.node {
+                match rhs.kind {
                     // Don't format `.. ..` into `....`, which is invalid.
                     //
                     // This check is unnecessary for `lhs`, because a range
@@ -316,7 +325,11 @@ fn needs_space_after_range(rhs: &ast::Expr) -> bool {
         }
         // We do not format these expressions yet, but they should still
         // satisfy our width restrictions.
-        ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
+        // Style Guide RFC for InlineAsm variant pending
+        // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
+        ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
+            Some(context.snippet(expr.span).to_owned())
+        }
         ast::ExprKind::TryBlock(ref block) => {
             if let rw @ Some(_) =
                 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
@@ -338,10 +351,6 @@ fn needs_space_after_range(rhs: &ast::Expr) -> bool {
                 ))
             }
         }
-        ast::ExprKind::ObsoleteInPlace(ref lhs, ref rhs) => lhs
-            .rewrite(context, shape)
-            .map(|s| s + " <-")
-            .and_then(|lhs| rewrite_assign_rhs(context, lhs, &**rhs, shape)),
         ast::ExprKind::Async(capture_by, _node_id, ref block) => {
             let mover = if capture_by == ast::CaptureBy::Value {
                 "move "
@@ -374,6 +383,9 @@ fn needs_space_after_range(rhs: &ast::Expr) -> bool {
                 ))
             }
         }
+        ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
+        ast::ExprKind::Underscore => Some("_".to_owned()),
+        ast::ExprKind::Err => None,
     };
 
     expr_rw
@@ -389,11 +401,11 @@ fn needs_space_after_range(rhs: &ast::Expr) -> bool {
         })
 }
 
-pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
+pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
     name: &'a str,
     exprs: impl Iterator<Item = &'a T>,
     span: Span,
-    context: &'a RewriteContext,
+    context: &'a RewriteContext<'_>,
     shape: Shape,
     force_separator_tactic: Option<SeparatorTactic>,
     delim_token: Option<DelimToken>,
@@ -410,22 +422,23 @@ pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
 }
 
 fn rewrite_empty_block(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
     label: Option<ast::Label>,
     prefix: &str,
     shape: Shape,
 ) -> Option<String> {
+    if !block.stmts.is_empty() {
+        return None;
+    }
+
     let label_str = rewrite_label(label);
     if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
         return None;
     }
 
-    if block.stmts.is_empty()
-        && !block_contains_comment(block, context.source_map)
-        && shape.width >= 2
-    {
+    if !block_contains_comment(context, block) && shape.width >= 2 {
         return Some(format!("{}{}{{}}", prefix, label_str));
     }
 
@@ -446,7 +459,7 @@ fn rewrite_empty_block(
     None
 }
 
-fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
+fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
     Some(match block.rules {
         ast::BlockCheckMode::Unsafe(..) => {
             let snippet = context.snippet(block.span);
@@ -475,14 +488,14 @@ fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> O
 }
 
 fn rewrite_single_line_block(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     prefix: &str,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
     label: Option<ast::Label>,
     shape: Shape,
 ) -> Option<String> {
-    if is_simple_block(block, attrs, context.source_map) {
+    if is_simple_block(context, block, attrs) {
         let expr_shape = shape.offset_left(last_line_width(prefix))?;
         let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
         let label_str = rewrite_label(label);
@@ -494,8 +507,8 @@ fn rewrite_single_line_block(
     None
 }
 
-pub fn rewrite_block_with_visitor(
-    context: &RewriteContext,
+pub(crate) fn rewrite_block_with_visitor(
+    context: &RewriteContext<'_>,
     prefix: &str,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
@@ -510,23 +523,28 @@ pub fn rewrite_block_with_visitor(
     let mut visitor = FmtVisitor::from_context(context);
     visitor.block_indent = shape.indent;
     visitor.is_if_else_block = context.is_if_else_block();
-    match block.rules {
-        ast::BlockCheckMode::Unsafe(..) => {
+    match (block.rules, label) {
+        (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
             let snippet = context.snippet(block.span);
             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, None) => visitor.last_pos = block.span.lo(),
     }
 
     let inner_attrs = attrs.map(inner_attributes);
     let label_str = rewrite_label(label);
     visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
+    let visitor_context = visitor.get_context();
+    context
+        .skipped_range
+        .borrow_mut()
+        .append(&mut visitor_context.skipped_range.borrow_mut());
     Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
 }
 
 impl Rewrite for ast::Block {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         rewrite_block(self, None, None, context, shape)
     }
 }
@@ -535,7 +553,7 @@ fn rewrite_block(
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
     label: Option<ast::Label>,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     let prefix = block_prefix(context, block, shape)?;
@@ -560,31 +578,13 @@ fn rewrite_block(
     result
 }
 
-impl Rewrite for ast::Stmt {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        skip_out_of_file_lines_range!(context, self.span());
-
-        let result = match self.node {
-            ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
-            ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
-                let suffix = if semicolon_for_stmt(context, self) {
-                    ";"
-                } else {
-                    ""
-                };
-
-                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))
-    }
-}
-
 // Rewrite condition if the given expression has one.
-pub fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
-    match expr.node {
+pub(crate) fn rewrite_cond(
+    context: &RewriteContext<'_>,
+    expr: &ast::Expr,
+    shape: Shape,
+) -> Option<String> {
+    match expr.kind {
         ast::ExprKind::Match(ref cond, _) => {
             // `match `cond` {`
             let cond_shape = match context.config.indent_style() {
@@ -610,31 +610,31 @@ struct ControlFlow<'a> {
     block: &'a ast::Block,
     else_block: Option<&'a ast::Expr>,
     label: Option<ast::Label>,
-    pats: Vec<&'a ast::Pat>,
+    pat: Option<&'a ast::Pat>,
     keyword: &'a str,
     matcher: &'a str,
     connector: &'a str,
     allow_single_line: bool,
-    // True if this is an `if` expression in an `else if` :-( hacky
+    // HACK: `true` if this is an `if` expression in an `else if`.
     nested_if: bool,
     span: Span,
 }
 
-fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow> {
-    match expr.node {
-        ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
-            cond,
-            vec![],
-            if_block,
-            else_block.as_ref().map(|e| &**e),
-            expr_type == ExprType::SubExpression,
-            false,
-            expr.span,
-        )),
-        ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
+fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
+    match expr.kind {
+        ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
+        _ => (None, expr),
+    }
+}
+
+// FIXME: Refactor this.
+fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
+    match expr.kind {
+        ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
+            let (pat, cond) = extract_pats_and_cond(cond);
             Some(ControlFlow::new_if(
                 cond,
-                ptr_vec_to_ref_vec(pat),
+                pat,
                 if_block,
                 else_block.as_ref().map(|e| &**e),
                 expr_type == ExprType::SubExpression,
@@ -648,45 +648,35 @@ fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow>
         ast::ExprKind::Loop(ref block, label) => {
             Some(ControlFlow::new_loop(block, label, expr.span))
         }
-        ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
-            vec![],
-            cond,
-            block,
-            label,
-            expr.span,
-        )),
-        ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
-            ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
-        ),
+        ast::ExprKind::While(ref cond, ref block, label) => {
+            let (pat, cond) = extract_pats_and_cond(cond);
+            Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
+        }
         _ => None,
     }
 }
 
-fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
-    if pats.is_empty() {
-        ""
-    } else {
-        "let"
-    }
+fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
+    pat.map_or("", |_| "let")
 }
 
 impl<'a> ControlFlow<'a> {
     fn new_if(
         cond: &'a ast::Expr,
-        pats: Vec<&'a ast::Pat>,
+        pat: Option<&'a ast::Pat>,
         block: &'a ast::Block,
         else_block: Option<&'a ast::Expr>,
         allow_single_line: bool,
         nested_if: bool,
         span: Span,
     ) -> ControlFlow<'a> {
-        let matcher = choose_matcher(&pats);
+        let matcher = choose_matcher(pat);
         ControlFlow {
             cond: Some(cond),
             block,
             else_block,
             label: None,
-            pats,
+            pat,
             keyword: "if",
             matcher,
             connector: " =",
@@ -702,7 +692,7 @@ fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> Con
             block,
             else_block: None,
             label,
-            pats: vec![],
+            pat: None,
             keyword: "loop",
             matcher: "",
             connector: "",
@@ -713,19 +703,19 @@ fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> Con
     }
 
     fn new_while(
-        pats: Vec<&'a ast::Pat>,
+        pat: Option<&'a ast::Pat>,
         cond: &'a ast::Expr,
         block: &'a ast::Block,
         label: Option<ast::Label>,
         span: Span,
     ) -> ControlFlow<'a> {
-        let matcher = choose_matcher(&pats);
+        let matcher = choose_matcher(pat);
         ControlFlow {
             cond: Some(cond),
             block,
             else_block: None,
             label,
-            pats,
+            pat,
             keyword: "while",
             matcher,
             connector: " =",
@@ -747,7 +737,7 @@ fn new_for(
             block,
             else_block: None,
             label,
-            pats: vec![pat],
+            pat: Some(pat),
             keyword: "for",
             matcher: "",
             connector: " in",
@@ -760,16 +750,16 @@ fn new_for(
     fn rewrite_single_line(
         &self,
         pat_expr_str: &str,
-        context: &RewriteContext,
+        context: &RewriteContext<'_>,
         width: usize,
     ) -> Option<String> {
         assert!(self.allow_single_line);
         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, None, context.source_map)
-                || !is_simple_block(else_node, None, context.source_map)
+        if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
+            if !is_simple_block(context, self.block, None)
+                || !is_simple_block(context, else_node, None)
                 || pat_expr_str.contains('\n')
             {
                 return None;
@@ -801,7 +791,7 @@ fn rewrite_single_line(
     }
 }
 
-/// Returns true if the last line of pat_str has leading whitespace and it is wider than the
+/// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
 /// shape's indent.
 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
     let mut leading_whitespaces = 0;
@@ -818,15 +808,15 @@ fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
 impl<'a> ControlFlow<'a> {
     fn rewrite_pat_expr(
         &self,
-        context: &RewriteContext,
+        context: &RewriteContext<'_>,
         expr: &ast::Expr,
         shape: Shape,
         offset: usize,
     ) -> Option<String> {
-        debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
+        debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
 
         let cond_shape = shape.offset_left(offset)?;
-        if !self.pats.is_empty() {
+        if let Some(pat) = self.pat {
             let matcher = if self.matcher.is_empty() {
                 self.matcher.to_owned()
             } else {
@@ -835,8 +825,41 @@ fn rewrite_pat_expr(
             let pat_shape = cond_shape
                 .offset_left(matcher.len())?
                 .sub_width(self.connector.len())?;
-            let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
-            let result = format!("{}{}{}", matcher, pat_string, self.connector);
+            let pat_string = pat.rewrite(context, pat_shape)?;
+            let comments_lo = context
+                .snippet_provider
+                .span_after(self.span, self.connector.trim());
+            let missing_comments = if let Some(comment) =
+                rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
+            {
+                if !self.connector.is_empty() && !comment.is_empty() {
+                    if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
+                        let newline = &pat_shape
+                            .indent
+                            .block_indent(context.config)
+                            .to_string_with_newline(context.config);
+                        // An extra space is added when the lhs and rhs are joined
+                        // so we need to remove one space from the end to ensure
+                        // the comment and rhs are aligned.
+                        let mut suffix = newline.as_ref().to_string();
+                        if !suffix.is_empty() {
+                            suffix.truncate(suffix.len() - 1);
+                        }
+                        format!("{}{}{}", newline, comment, suffix)
+                    } else {
+                        format!(" {}", comment)
+                    }
+                } else {
+                    comment
+                }
+            } else {
+                "".to_owned()
+            };
+
+            let result = format!(
+                "{}{}{}{}",
+                matcher, pat_string, self.connector, missing_comments
+            );
             return rewrite_assign_rhs(context, result, expr, cond_shape);
         }
 
@@ -858,7 +881,7 @@ fn rewrite_pat_expr(
 
     fn rewrite_cond(
         &self,
-        context: &RewriteContext,
+        context: &RewriteContext<'_>,
         shape: Shape,
         alt_block_sep: &str,
     ) -> Option<(String, usize)> {
@@ -939,10 +962,10 @@ fn rewrite_cond(
             context
                 .snippet_provider
                 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
-            if self.pats.is_empty() {
+            if self.pat.is_none() {
                 cond_span.lo()
             } else if self.matcher.is_empty() {
-                self.pats[0].span.lo()
+                self.pat.unwrap().span.lo()
             } else {
                 context
                     .snippet_provider
@@ -994,7 +1017,7 @@ fn rewrite_cond(
 }
 
 impl<'a> Rewrite for ControlFlow<'a> {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
 
         let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
@@ -1029,27 +1052,16 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         if let Some(else_block) = self.else_block {
             let shape = Shape::indented(shape.indent, context.config);
             let mut last_in_chain = false;
-            let rewrite = match else_block.node {
+            let rewrite = match else_block.kind {
                 // If the else expression is another if-else expression, prevent it
                 // from being formatted on a single line.
                 // Note how we're passing the original shape, as the
                 // cost of "else" should not cascade.
-                ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
-                    ControlFlow::new_if(
-                        cond,
-                        ptr_vec_to_ref_vec(pat),
-                        if_block,
-                        next_else_block.as_ref().map(|e| &**e),
-                        false,
-                        true,
-                        mk_sp(else_block.span.lo(), self.span.hi()),
-                    )
-                    .rewrite(context, shape)
-                }
                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
+                    let (pats, cond) = extract_pats_and_cond(cond);
                     ControlFlow::new_if(
                         cond,
-                        vec![],
+                        pats,
                         if_block,
                         next_else_block.as_ref().map(|e| &**e),
                         false,
@@ -1119,7 +1131,7 @@ fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
     }
 }
 
-fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
+fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
     match rewrite_missing_comment(span, shape, context) {
         Some(ref comment) if !comment.is_empty() => Some(format!(
             "{indent}{}{indent}",
@@ -1130,58 +1142,57 @@ fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option
     }
 }
 
-pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
-    let snippet = source_map.span_to_snippet(block.span).unwrap();
-    contains_comment(&snippet)
+pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
+    contains_comment(context.snippet(block.span))
 }
 
 // Checks that a block contains no statements, an expression and no comments or
 // attributes.
 // FIXME: incorrectly returns false when comment is contained completely within
 // the expression.
-pub fn is_simple_block(
+pub(crate) fn is_simple_block(
+    context: &RewriteContext<'_>,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
-    source_map: &SourceMap,
 ) -> bool {
-    (block.stmts.len() == 1
+    block.stmts.len() == 1
         && stmt_is_expr(&block.stmts[0])
-        && !block_contains_comment(block, source_map)
-        && attrs.map_or(true, |a| a.is_empty()))
+        && !block_contains_comment(context, block)
+        && attrs.map_or(true, |a| a.is_empty())
 }
 
 /// Checks whether a block contains at most one statement or expression, and no
 /// comments or attributes.
-pub fn is_simple_block_stmt(
+pub(crate) fn is_simple_block_stmt(
+    context: &RewriteContext<'_>,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
-    source_map: &SourceMap,
 ) -> bool {
     block.stmts.len() <= 1
-        && !block_contains_comment(block, source_map)
+        && !block_contains_comment(context, block)
         && attrs.map_or(true, |a| a.is_empty())
 }
 
 /// Checks whether a block contains no statements, expressions, comments, or
 /// inner attributes.
-pub fn is_empty_block(
+pub(crate) fn is_empty_block(
+    context: &RewriteContext<'_>,
     block: &ast::Block,
     attrs: Option<&[ast::Attribute]>,
-    source_map: &SourceMap,
 ) -> bool {
     block.stmts.is_empty()
-        && !block_contains_comment(block, source_map)
+        && !block_contains_comment(context, block)
         && attrs.map_or(true, |a| inner_attributes(a).is_empty())
 }
 
-pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
-    match stmt.node {
+pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
+    match stmt.kind {
         ast::StmtKind::Expr(..) => true,
         _ => false,
     }
 }
 
-pub fn is_unsafe_block(block: &ast::Block) -> bool {
+pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
         true
     } else {
@@ -1189,41 +1200,12 @@ pub fn is_unsafe_block(block: &ast::Block) -> bool {
     }
 }
 
-pub fn rewrite_multiple_patterns(
-    context: &RewriteContext,
-    pats: &[&ast::Pat],
+pub(crate) fn rewrite_literal(
+    context: &RewriteContext<'_>,
+    l: &ast::Lit,
     shape: Shape,
 ) -> Option<String> {
-    let pat_strs = pats
-        .iter()
-        .map(|p| p.rewrite(context, shape))
-        .collect::<Option<Vec<_>>>()?;
-
-    let use_mixed_layout = pats
-        .iter()
-        .zip(pat_strs.iter())
-        .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
-    let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
-    let tactic = if use_mixed_layout {
-        DefinitiveListTactic::Mixed
-    } else {
-        definitive_tactic(
-            &items,
-            ListTactic::HorizontalVertical,
-            Separator::VerticalBar,
-            shape.width,
-        )
-    };
-    let fmt = ListFormatting::new(shape, context.config)
-        .tactic(tactic)
-        .separator(" |")
-        .separator_place(context.config.binop_separator())
-        .ends_with_newline(false);
-    write_list(&items, &fmt)
-}
-
-pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
-    match l.node {
+    match l.kind {
         ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
         _ => wrap_str(
             context.snippet(l.span).to_owned(),
@@ -1233,32 +1215,17 @@ pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) ->
     }
 }
 
-fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
+fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
     let string_lit = context.snippet(span);
 
     if !context.config.format_strings() {
         if string_lit
             .lines()
-            .rev()
-            .skip(1)
+            .dropping_back(1)
             .all(|line| line.ends_with('\\'))
+            && context.config.version() == Version::Two
         {
-            let new_indent = shape.visual_indent(1).indent;
-            let indented_string_lit = String::from(
-                string_lit
-                    .lines()
-                    .map(|line| {
-                        format!(
-                            "{}{}",
-                            new_indent.to_string(context.config),
-                            line.trim_left()
-                        )
-                    })
-                    .collect::<Vec<_>>()
-                    .join("\n")
-                    .trim_left(),
-            );
-            return wrap_str(indented_string_lit, context.config.max_width(), shape);
+            return Some(string_lit.to_owned());
         } else {
             return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
         }
@@ -1274,7 +1241,7 @@ fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Opt
     )
 }
 
-fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<SeparatorTactic> {
+fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
     if context.inside_macro() {
         if span_ends_with_comma(context, span) {
             Some(SeparatorTactic::Always)
@@ -1286,8 +1253,8 @@ fn choose_separator_tactic(context: &RewriteContext, span: Span) -> Option<Separ
     }
 }
 
-pub fn rewrite_call(
-    context: &RewriteContext,
+pub(crate) fn rewrite_call(
+    context: &RewriteContext<'_>,
     callee: &str,
     args: &[ptr::P<ast::Expr>],
     span: Span,
@@ -1304,11 +1271,11 @@ pub fn rewrite_call(
     )
 }
 
-pub fn is_simple_expr(expr: &ast::Expr) -> bool {
-    match expr.node {
+pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
+    match expr.kind {
         ast::ExprKind::Lit(..) => true,
         ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
-        ast::ExprKind::AddrOf(_, ref expr)
+        ast::ExprKind::AddrOf(_, _, ref expr)
         | ast::ExprKind::Box(ref expr)
         | ast::ExprKind::Cast(ref expr, _)
         | ast::ExprKind::Field(ref expr, _)
@@ -1322,36 +1289,44 @@ pub fn is_simple_expr(expr: &ast::Expr) -> bool {
     }
 }
 
-pub fn is_every_expr_simple(lists: &[OverflowableItem]) -> bool {
+pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
     lists.iter().all(OverflowableItem::is_simple)
 }
 
-pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
-    match expr.node {
+pub(crate) fn can_be_overflowed_expr(
+    context: &RewriteContext<'_>,
+    expr: &ast::Expr,
+    args_len: usize,
+) -> bool {
+    match expr.kind {
+        _ if !expr.attrs.is_empty() => false,
         ast::ExprKind::Match(..) => {
             (context.use_block_indent() && args_len == 1)
                 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
+                || context.config.overflow_delimited_expr()
         }
         ast::ExprKind::If(..)
-        | ast::ExprKind::IfLet(..)
         | ast::ExprKind::ForLoop(..)
         | ast::ExprKind::Loop(..)
-        | ast::ExprKind::While(..)
-        | ast::ExprKind::WhileLet(..) => {
+        | ast::ExprKind::While(..) => {
             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
         }
 
         // Handle always block-like expressions
-        ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
+        ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
 
         // Handle `[]` and `{}`-like expressions
         ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
             context.config.overflow_delimited_expr()
                 || (context.use_block_indent() && args_len == 1)
         }
-        ast::ExprKind::Mac(ref macro_) => {
-            match (macro_.node.delim, context.config.overflow_delimited_expr()) {
-                (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
+        ast::ExprKind::MacCall(ref mac) => {
+            match (
+                rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
+                context.config.overflow_delimited_expr(),
+            ) {
+                (Some(ast::MacDelimiter::Bracket), true)
+                | (Some(ast::MacDelimiter::Brace), true) => true,
                 _ => context.use_block_indent() && args_len == 1,
             }
         }
@@ -1362,7 +1337,7 @@ pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_l
         }
 
         // Handle unary-like expressions
-        ast::ExprKind::AddrOf(_, ref expr)
+        ast::ExprKind::AddrOf(_, _, ref expr)
         | ast::ExprKind::Box(ref expr)
         | ast::ExprKind::Try(ref expr)
         | ast::ExprKind::Unary(_, ref expr)
@@ -1371,10 +1346,10 @@ pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_l
     }
 }
 
-pub fn is_nested_call(expr: &ast::Expr) -> bool {
-    match expr.node {
-        ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
-        ast::ExprKind::AddrOf(_, ref expr)
+pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
+    match expr.kind {
+        ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
+        ast::ExprKind::AddrOf(_, _, ref expr)
         | ast::ExprKind::Box(ref expr)
         | ast::ExprKind::Try(ref expr)
         | ast::ExprKind::Unary(_, ref expr)
@@ -1383,10 +1358,10 @@ pub fn is_nested_call(expr: &ast::Expr) -> bool {
     }
 }
 
-/// Return true if a function call or a method call represented by the given span ends with a
+/// Returns `true` if a function call or a method call represented by the given span ends with a
 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
 /// comma from macro can potentially break the code.
-pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
+pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
     let mut result: bool = Default::default();
     let mut prev_char: char = Default::default();
     let closing_delimiters = &[')', '}', ']'];
@@ -1407,7 +1382,7 @@ pub fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
 }
 
 fn rewrite_paren(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     mut subexpr: &ast::Expr,
     shape: Shape,
     mut span: Span,
@@ -1428,7 +1403,7 @@ fn rewrite_paren(
         post_comment = rewrite_missing_comment(post_span, shape, context)?;
 
         // Remove nested parens if there are no comments.
-        if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
+        if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
             if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
                 span = subexpr.span;
                 subexpr = subsubexpr;
@@ -1444,14 +1419,14 @@ fn rewrite_paren(
     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
     let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
     if fits_single_line {
-        Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
+        Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
     } else {
         rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
     }
 }
 
 fn rewrite_paren_in_multi_line(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     subexpr: &ast::Expr,
     shape: Shape,
     pre_span: Span,
@@ -1484,7 +1459,7 @@ fn rewrite_paren_in_multi_line(
 fn rewrite_index(
     expr: &ast::Expr,
     index: &ast::Expr,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
 ) -> Option<String> {
     let expr_str = expr.rewrite(context, shape)?;
@@ -1536,19 +1511,16 @@ fn rewrite_index(
     }
 }
 
-fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
-    if base.is_some() {
-        return false;
-    }
-
-    fields.iter().all(|field| !field.is_shorthand)
+fn struct_lit_can_be_aligned(fields: &[ast::Field], has_base: bool) -> bool {
+    !has_base && fields.iter().all(|field| !field.is_shorthand)
 }
 
 fn rewrite_struct_lit<'a>(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     path: &ast::Path,
     fields: &'a [ast::Field],
-    base: Option<&'a ast::Expr>,
+    struct_rest: &ast::StructRest,
+    attrs: &[ast::Attribute],
     span: Span,
     shape: Shape,
 ) -> Option<String> {
@@ -1557,22 +1529,28 @@ fn rewrite_struct_lit<'a>(
     enum StructLitField<'a> {
         Regular(&'a ast::Field),
         Base(&'a ast::Expr),
+        Rest(&'a Span),
     }
 
     // 2 = " {".len()
     let path_shape = shape.sub_width(2)?;
     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
 
-    if fields.is_empty() && base.is_none() {
-        return Some(format!("{} {{}}", path_str));
-    }
+    let has_base = match struct_rest {
+        ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
+        ast::StructRest::Rest(_) if fields.is_empty() => {
+            return Some(format!("{} {{ .. }}", path_str));
+        }
+        ast::StructRest::Base(_) => true,
+        _ => false,
+    };
 
     // Foo { a: Foo } - indent is +3, width is -5.
     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.snippet_provider.span_after(span, "{");
-    let fields_str = if struct_lit_can_be_aligned(fields, base)
+    let fields_str = if struct_lit_can_be_aligned(fields, has_base)
         && context.config.struct_field_align_threshold() > 0
     {
         rewrite_with_alignment(
@@ -1583,12 +1561,16 @@ enum StructLitField<'a> {
             one_line_width,
         )?
     } else {
-        let field_iter = fields
-            .iter()
-            .map(StructLitField::Regular)
-            .chain(base.into_iter().map(StructLitField::Base));
+        let field_iter = fields.iter().map(StructLitField::Regular).chain(
+            match struct_rest {
+                ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
+                ast::StructRest::Rest(span) => Some(StructLitField::Rest(span)),
+                ast::StructRest::None => None,
+            }
+            .into_iter(),
+        );
 
-        let span_lo = |item: &StructLitField| match *item {
+        let span_lo = |item: &StructLitField<'_>| match *item {
             StructLitField::Regular(field) => field.span().lo(),
             StructLitField::Base(expr) => {
                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
@@ -1596,12 +1578,14 @@ enum StructLitField<'a> {
                 let pos = snippet.find_uncommented("..").unwrap();
                 last_field_hi + BytePos(pos as u32)
             }
+            StructLitField::Rest(span) => span.lo(),
         };
-        let span_hi = |item: &StructLitField| match *item {
+        let span_hi = |item: &StructLitField<'_>| match *item {
             StructLitField::Regular(field) => field.span().hi(),
             StructLitField::Base(expr) => expr.span.hi(),
+            StructLitField::Rest(span) => span.hi(),
         };
-        let rewrite = |item: &StructLitField| match *item {
+        let rewrite = |item: &StructLitField<'_>| match *item {
             StructLitField::Regular(field) => {
                 // The 1 taken from the v_budget is for the comma.
                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
@@ -1611,6 +1595,7 @@ enum StructLitField<'a> {
                 expr.rewrite(context, v_shape.offset_left(2)?)
                     .map(|s| format!("..{}", s))
             }
+            StructLitField::Rest(_) => Some("..".to_owned()),
         };
 
         let items = itemize_list(
@@ -1637,49 +1622,64 @@ enum StructLitField<'a> {
             nested_shape,
             tactic,
             context,
-            force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
+            force_no_trailing_comma || has_base || !context.use_block_indent(),
         );
 
         write_list(&item_vec, &fmt)?
     };
 
-    let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
+    let fields_str =
+        wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
     Some(format!("{} {{{}}}", path_str, fields_str))
 
     // FIXME if context.config.indent_style() == Visual, but we run out
     // of space, we should fall back to BlockIndent.
 }
 
-pub fn wrap_struct_field(
-    context: &RewriteContext,
+pub(crate) fn wrap_struct_field(
+    context: &RewriteContext<'_>,
+    attrs: &[ast::Attribute],
     fields_str: &str,
     shape: Shape,
     nested_shape: Shape,
     one_line_width: usize,
-) -> String {
-    if context.config.indent_style() == IndentStyle::Block
+) -> Option<String> {
+    let should_vertical = context.config.indent_style() == IndentStyle::Block
         && (fields_str.contains('\n')
             || !context.config.struct_lit_single_line()
-            || fields_str.len() > one_line_width)
-    {
-        format!(
-            "{}{}{}",
+            || fields_str.len() > one_line_width);
+
+    let inner_attrs = &inner_attributes(attrs);
+    if inner_attrs.is_empty() {
+        if should_vertical {
+            Some(format!(
+                "{}{}{}",
+                nested_shape.indent.to_string_with_newline(context.config),
+                fields_str,
+                shape.indent.to_string_with_newline(context.config)
+            ))
+        } else {
+            // One liner or visual indent.
+            Some(format!(" {} ", fields_str))
+        }
+    } else {
+        Some(format!(
+            "{}{}{}{}{}",
+            nested_shape.indent.to_string_with_newline(context.config),
+            inner_attrs.rewrite(context, shape)?,
             nested_shape.indent.to_string_with_newline(context.config),
             fields_str,
             shape.indent.to_string_with_newline(context.config)
-        )
-    } else {
-        // One liner or visual indent.
-        format!(" {} ", fields_str)
+        ))
     }
 }
 
-pub fn struct_lit_field_separator(config: &Config) -> &str {
-    colon_spaces(config.space_before_colon(), config.space_after_colon())
+pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
+    colon_spaces(config)
 }
 
-pub fn rewrite_field(
-    context: &RewriteContext,
+pub(crate) fn rewrite_field(
+    context: &RewriteContext<'_>,
     field: &ast::Field,
     shape: Shape,
     prefix_max_width: usize,
@@ -1728,7 +1728,7 @@ pub fn rewrite_field(
 }
 
 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     mut items: impl Iterator<Item = &'a T>,
     span: Span,
     shape: Shape,
@@ -1775,8 +1775,8 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
     Some(format!("({})", list_str))
 }
 
-pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
-    context: &'a RewriteContext,
+pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
+    context: &'a RewriteContext<'_>,
     items: impl Iterator<Item = &'a T>,
     span: Span,
     shape: Shape,
@@ -1810,8 +1810,8 @@ pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
     }
 }
 
-pub fn rewrite_unary_prefix<R: Rewrite>(
-    context: &RewriteContext,
+pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
+    context: &RewriteContext<'_>,
     prefix: &str,
     rewrite: &R,
     shape: Shape,
@@ -1823,8 +1823,8 @@ pub fn rewrite_unary_prefix<R: Rewrite>(
 
 // FIXME: this is probably not correct for multi-line Rewrites. we should
 // subtract suffix.len() from the last line budget, not the first!
-pub fn rewrite_unary_suffix<R: Rewrite>(
-    context: &RewriteContext,
+pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
+    context: &RewriteContext<'_>,
     suffix: &str,
     rewrite: &R,
     shape: Shape,
@@ -1838,7 +1838,7 @@ pub fn rewrite_unary_suffix<R: Rewrite>(
 }
 
 fn rewrite_unary_op(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     op: ast::UnOp,
     expr: &ast::Expr,
     shape: Shape,
@@ -1848,7 +1848,7 @@ fn rewrite_unary_op(
 }
 
 fn rewrite_assignment(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     lhs: &ast::Expr,
     rhs: &ast::Expr,
     op: Option<&ast::BinOp>,
@@ -1868,17 +1868,20 @@ fn rewrite_assignment(
 
 /// Controls where to put the rhs.
 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum RhsTactics {
+pub(crate) enum RhsTactics {
     /// Use heuristics.
     Default,
     /// Put the rhs on the next line if it uses multiple line, without extra indentation.
     ForceNextLineWithoutIndent,
+    /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
+    /// did not work.
+    AllowOverflow,
 }
 
 // The left hand side must contain everything up to, and including, the
 // assignment operator.
-pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
-    context: &RewriteContext,
+pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
+    context: &RewriteContext<'_>,
     lhs: S,
     ex: &R,
     shape: Shape,
@@ -1886,8 +1889,8 @@ pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
     rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
 }
 
-pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
-    context: &RewriteContext,
+pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
+    context: &RewriteContext<'_>,
     lhs: S,
     ex: &R,
     shape: Shape,
@@ -1916,14 +1919,16 @@ pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
 }
 
 fn choose_rhs<R: Rewrite>(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     expr: &R,
     shape: Shape,
     orig_rhs: Option<String>,
     rhs_tactics: RhsTactics,
 ) -> Option<String> {
     match orig_rhs {
-        Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
+        Some(ref new_str)
+            if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
+        {
             Some(format!(" {}", new_str))
         }
         _ => {
@@ -1949,6 +1954,10 @@ fn choose_rhs<R: Rewrite>(
                     Some(format!("{}{}", new_indent_str, new_rhs))
                 }
                 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
+                (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
+                    let shape = shape.infinite_width();
+                    expr.rewrite(context, shape).map(|s| format!(" {}", s))
+                }
                 (None, None) => None,
                 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
             }
@@ -1957,7 +1966,7 @@ fn choose_rhs<R: Rewrite>(
 }
 
 fn shape_from_rhs_tactic(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     shape: Shape,
     rhs_tactic: RhsTactics,
 ) -> Option<Shape> {
@@ -1965,14 +1974,27 @@ fn shape_from_rhs_tactic(
         RhsTactics::ForceNextLineWithoutIndent => shape
             .with_max_width(context.config)
             .sub_width(shape.indent.width()),
-        RhsTactics::Default => {
+        RhsTactics::Default | RhsTactics::AllowOverflow => {
             Shape::indented(shape.indent.block_indent(context.config), context.config)
                 .sub_width(shape.rhs_overhead(context.config))
         }
     }
 }
 
-pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
+/// Returns true if formatting next_line_rhs is better on a new line when compared to the
+/// original's line formatting.
+///
+/// It is considered better if:
+/// 1. the tactic is ForceNextLineWithoutIndent
+/// 2. next_line_rhs doesn't have newlines
+/// 3. the original line has more newlines than next_line_rhs
+/// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
+///    doesn't
+pub(crate) fn prefer_next_line(
+    orig_rhs: &str,
+    next_line_rhs: &str,
+    rhs_tactics: RhsTactics,
+) -> bool {
     rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
         || !next_line_rhs.contains('\n')
         || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
@@ -1982,22 +2004,25 @@ pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTac
 }
 
 fn rewrite_expr_addrof(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
+    borrow_kind: ast::BorrowKind,
     mutability: ast::Mutability,
     expr: &ast::Expr,
     shape: Shape,
 ) -> Option<String> {
-    let operator_str = match mutability {
-        ast::Mutability::Immutable => "&",
-        ast::Mutability::Mutable => "&mut ",
+    let operator_str = match (mutability, borrow_kind) {
+        (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
+        (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
+        (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
+        (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
     };
     rewrite_unary_prefix(context, operator_str, expr, shape)
 }
 
-pub fn is_method_call(expr: &ast::Expr) -> bool {
-    match expr.node {
+pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
+    match expr.kind {
         ast::ExprKind::MethodCall(..) => true,
-        ast::ExprKind::AddrOf(_, ref expr)
+        ast::ExprKind::AddrOf(_, _, ref expr)
         | ast::ExprKind::Box(ref expr)
         | ast::ExprKind::Cast(ref expr, _)
         | ast::ExprKind::Try(ref expr)